From e3979e9e32a181df8b4e0e24ff27b4375ee4034a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=89=E7=A7=8B?= <497055328@qq.com> Date: Wed, 4 Nov 2026 17:34:28 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=8C=E5=96=84=E6=9C=BA=E5=B7=A2?= =?UTF-8?q?=E4=BB=BB=E5=8A=A1=E5=AE=89=E5=85=A8=E6=8E=A7=E5=88=B6=E4=B8=8E?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E8=AF=8A=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 同步新版飞控与 WebSocket 回执合同,完善独立指令等待、暂停继续和返航状态;增加真机诊断并优化倒计时与素材库展示。 --- AGENTS.md | 15 + .../Core/Networking/APIConsoleFormat.swift | 9 +- .../Networking/DroneDockTaskDiagnostics.swift | 87 ++ .../DroneDock/API/DroneDockCommandAPI.swift | 17 +- .../Models/DroneDockCommandModels.swift | 35 +- .../Models/DroneDockCommandOperation.swift | 28 + .../Models/DroneDockFlightControl.swift | 87 ++ .../Models/DroneDockShootingModels.swift | 9 +- .../DroneDockShootingSocketMessage.swift | 10 +- .../Models/DroneDockTaskPresentation.swift | 14 +- .../Models/DroneDockTaskTraceFields.swift | 71 ++ .../DroneDockShootingRealtimeSession.swift | 4 + .../DroneDockPreparationViewModel.swift | 36 +- .../DroneDockShootingTaskViewModel.swift | 782 ++++++++++++++---- .../DroneDockMaterialsViewController.swift | 66 +- ...eDockRemotePreparationViewController.swift | 49 +- .../DroneDockShootingTaskViewController.swift | 314 +++++-- .../DroneDockStartShootSimulation.swift | 57 +- .../DroneDockTaskControlStateView.swift | 249 ++++++ .../UI/DroneDock/DroneDockTaskLiveView.swift | 38 +- .../DroneDock/DroneDockTaskStatusView.swift | 114 ++- .../UI/DroneDock/DroneShootingTaskViews.swift | 30 +- suixinkanTests/APIConsoleFormatTests.swift | 37 +- .../DroneDockArrivalCountdownTests.swift | 19 +- .../DroneDockArrivalCountdownViewTests.swift | 57 +- suixinkanTests/DroneDockCommandAPITests.swift | 57 +- .../DroneDockCommandProgressTests.swift | 384 +++++++++ .../DroneDockCommandViewModelTests.swift | 116 +-- .../DroneDockCommandViewTests.swift | 37 +- .../DroneDockFlightControlTests.swift | 468 +++++++++++ .../DroneDockMaterialsViewTests.swift | 90 +- .../DroneDockResummonLiveViewTests.swift | 8 +- .../DroneDockResummonViewModelTests.swift | 31 +- .../DroneDockShootingRealtimeTests.swift | 252 +++++- .../DroneDockShootingTaskTestSupport.swift | 16 + .../DroneDockShootingTaskViewModelTests.swift | 27 +- .../DroneDockSilentRefreshTests.swift | 6 +- .../DroneDockStartShootViewModelTests.swift | 7 +- .../DroneDockStatusContractTests.swift | 9 +- .../DroneDockTaskControlStateViewTests.swift | 695 ++++++++++++++++ .../DroneDockTaskDiagnosticsTests.swift | 196 +++++ .../DroneDockTaskFixedLayoutTests.swift | 78 +- .../DroneDockTaskPresentationTests.swift | 87 +- suixinkanTests/DroneDockTaskTraceTests.swift | 358 ++++++++ 44 files changed, 4575 insertions(+), 581 deletions(-) create mode 100644 suixinkan/Core/Networking/DroneDockTaskDiagnostics.swift create mode 100644 suixinkan/Features/DroneDock/Models/DroneDockCommandOperation.swift create mode 100644 suixinkan/Features/DroneDock/Models/DroneDockFlightControl.swift create mode 100644 suixinkan/Features/DroneDock/Models/DroneDockTaskTraceFields.swift create mode 100644 suixinkan/UI/DroneDock/DroneDockTaskControlStateView.swift create mode 100644 suixinkanTests/DroneDockCommandProgressTests.swift create mode 100644 suixinkanTests/DroneDockFlightControlTests.swift create mode 100644 suixinkanTests/DroneDockTaskControlStateViewTests.swift create mode 100644 suixinkanTests/DroneDockTaskDiagnosticsTests.swift create mode 100644 suixinkanTests/DroneDockTaskTraceTests.swift diff --git a/AGENTS.md b/AGENTS.md index a03dfea..25cb65b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -227,3 +227,18 @@ Swift · UIKit · SnapKit(代码布局,约束写在 `setupUI()` / `setupCons - 可信拍摄中阶段使用产品文案“无人机正在拍摄中”,说明分两行显示“请关注现场及实时画面。”和“请勿关闭本页或息屏。”。按 [机巢体验原型](https://voicestudio.suixinkan.cn/) 展示左侧浅蓝圆形视频图标、右侧标题与说明、下方整行浅蓝禁用“拍摄中”指示按钮。 - 拍摄中面板不显示设备摘要和中央刷新操作;导航栏刷新保留。禁用的“拍摄中”仅作状态展示,不提交飞控或其他主操作。 - 此调整只影响展示和操作布局,后台真实阶段、失败/取消优先级、任务身份与版本校验、安全门禁、HTTP/WS 读取及既有 Debug 禁飞保护不变;代理不执行真实任务创建、飞控或图传。 + +## 起飞准备、到点等待与独立安全控制(2026-11-04 最新合同) + +- 本节覆盖旧的暂停判定和指令全局等待锁。`starting` 表示召唤已受理、起飞准备,配合 `ui.phase=going_to_spot` 展示前往点位;仍在巢内不等于本批次已返航。`returned` 由后端确认本批次曾起飞/离巢且现在 inside,App 同时核对 `is_airborne=false`,不推测回巢。 +- 到点自动悬停为 `state=executing`、`pause_reason=arrival_wait`、`ui.phase=arrived_pending_start`;只有 `pause_reason=manual` 的可信 paused 才展示手动暂停。`resume_phase` 包括 `arrived_pending_start`,继续此阶段由后端软恢复,不直接开拍;返航暂停后继续恢复返航。 +- 安全控制按同任务批次的明确设备身份、`is_airborne` 和 `can_pause/can_resume/can_return_home` 独立授权。起飞准备按合同允许显式 `can_return_home=true` 的返航入口;前往、到点、拍摄时两个安全动作均可,手动暂停禁重复暂停,返航中禁重复返航。业务失败、录制完成、素材上传或渲染不能单独禁用仍在飞行的安全控制。 +- 每次点击生成 `client_request_id`,核对回执 `command_id`;HTTP/WS 的 `flight_control.pending_command` 和回执顶层 `pending_command` 按指令与请求标识关联。仅对应按钮 loading,中央保留业务阶段;一个动作等待/结果未知不无条件拦截另一安全动作。客户端只串行 HTTP 提交,不等待前一设备确认;后受理的指令取代旧意图,迟到回执不得重建旧锁。无明确结果不自动重发。 +- 明确设备确认可结束按钮动画,但仍需新完整快照更新中央状态及操作许可;同批次快照不得低于已受理回执的 `state_version`。新批次清理旧指令和版本下限,离页/后台取消读取与在途操作;Debug 网络及 RTC 拦截不变。 +- `metrics_stale=true` 仍展示后端最近值;App 同批次、同设备保留有效读数作为缺值防御并标记过期,不改写原始 JSON,不跨批次/设备继承。代理仅使用隔离替身、真机单元测试与无签名 Release 编译,不发真实飞控或图传。 + +## 拍摄真机录屏诊断(2026-11-04 用户要求) + +- 用户要求在 iOS 关键位置增加控制台日志,与其后续真实测试录屏对照。本节允许额外输出 `diagnostic=drone_task` 的任务关键事件,覆盖旧的“页面/解析/RTC 事件全部静默”限制;其它模块和接口 JSON 仍保持原 path/params/response 格式。 +- Debug/Release 均输出上海时区毫秒时间、单调耗时、会话 ID、事件序号及构建信息。记录准备与任务页导航、HTTP/WS 快照采纳/丢弃原因、后端证据与本地阶段/权限、指令幂等关联与按钮等待、读数过期及图传首帧/切换/停止。 +- UI 状态变化去重;倒计时只记开始、归零、隐藏,不逐秒输出;不恢复逐帧或心跳日志。复用已有安全控制台写入和系统日志回退,日志不得更改网络、状态、门禁或禁飞保护。代理仍仅以隔离替身和编译验证,真实设备操作由用户自行执行。 diff --git a/suixinkan/Core/Networking/APIConsoleFormat.swift b/suixinkan/Core/Networking/APIConsoleFormat.swift index 85ebe88..520457f 100644 --- a/suixinkan/Core/Networking/APIConsoleFormat.swift +++ b/suixinkan/Core/Networking/APIConsoleFormat.swift @@ -1,6 +1,6 @@ import Foundation -/// 控制台只展示路径、入参及原始返回 JSON,不输出诊断信封或业务事件。 +/// 接口日志保留路径、入参及原始返回;仅额外放行明确标识的拍摄任务关键事件。 enum APIConsoleFormat { /// 发起请求时立即输出路径和参数;响应记录携带同样参数,方便并发请求核对。 static func message(path: String, params: Any, response: Any? = nil) -> String { @@ -51,9 +51,14 @@ enum APIConsoleFormat { self.message(path: path, params: params, response: ["local_error": ["kind": kind, "message": message]]) } - /// 将内部诊断记录转换为简洁输出;解码、页面、心跳、RTC 等事件不进入控制台。 + /// 接口记录转换为简洁输出;只有 drone_task 专用事件保留诊断字段,其余内部事件仍过滤。 static func render(_ text: String) -> String? { guard let fields = try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] else { return nil } + if fields["diagnostic"] as? String == "drone_task" { + guard let event = fields["event"] as? String, + !event.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil } + return pretty(fields) + } if fields["event"] == nil, let path = fields["path"] as? String, let params = fields["params"] { return message(path: path, params: params, response: fields["response"]) } diff --git a/suixinkan/Core/Networking/DroneDockTaskDiagnostics.swift b/suixinkan/Core/Networking/DroneDockTaskDiagnostics.swift new file mode 100644 index 0000000..0d65a4e --- /dev/null +++ b/suixinkan/Core/Networking/DroneDockTaskDiagnostics.swift @@ -0,0 +1,87 @@ +import Foundation + +/// 拍摄任务会话的关键事件日志;与接口正文分开标识,Debug 和 Release 使用同一安全输出通道。 +final class DroneDockTaskDiagnostics: @unchecked Sendable { + /// 同一任务页及其 ViewModel 共用的会话标识,用于与录屏和接口日志对照。 + let sessionID: String + + private let lock = NSLock() + private let metadata: DroneDockTaskDiagnosticMetadata + private let now: @Sendable () -> Date + private let uptime: @Sendable () -> TimeInterval + private let sink: @Sendable (String) -> Void + private let startedUptime: TimeInterval + private var sequence = 0 + + /// 默认写入已有串行控制台出口;测试可注入时钟和纯内存 sink,不修改全局日志通道。 + init(sessionID: String = UUID().uuidString, + metadata: DroneDockTaskDiagnosticMetadata = .current, + now: @escaping @Sendable () -> Date = { Date() }, + uptime: @escaping @Sendable () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }, + sink: @escaping @Sendable (String) -> Void = { DroneDockDiagnostics.write($0) }) { + self.sessionID = sessionID + self.metadata = metadata + self.now = now + self.uptime = uptime + self.sink = sink + startedUptime = uptime() + } + + /// 按同一会话顺序同步生成并输出关键事件;业务字段完整保留,不能覆盖关联身份及时间字段。 + func record(_ event: String, taskID: Int, fields: [String: Any] = [:]) { + lock.lock() + defer { lock.unlock() } + sequence += 1 + let elapsed = max(0, (uptime() - startedUptime) * 1_000) + let milliseconds = elapsed.isFinite && elapsed < Double(Int.max) ? Int(elapsed) : 0 + sink(Self.makeMessage(event, taskID: taskID, fields: fields, sessionID: sessionID, + sequence: sequence, timestamp: now(), elapsedMilliseconds: milliseconds, metadata: metadata)) + } + + /// 纯格式化入口:使用上海时区的毫秒时间,单调耗时与系统墙钟彼此独立。 + static func makeMessage(_ event: String, taskID: Int, fields: [String: Any] = [:], + sessionID: String, sequence: Int, timestamp: Date, + elapsedMilliseconds: Int, + metadata: DroneDockTaskDiagnosticMetadata = .current) -> String { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.calendar = Calendar(identifier: .gregorian) + formatter.timeZone = TimeZone(identifier: "Asia/Shanghai") + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" + var value = fields + value["diagnostic"] = "drone_task" + value["event"] = event + value["timestamp"] = formatter.string(from: timestamp) + value["timezone"] = "Asia/Shanghai" + value["elapsed_ms"] = max(0, elapsedMilliseconds) + value["sequence"] = sequence + value["session_id"] = sessionID + value["task_id"] = taskID + value["app_version"] = metadata.appVersion + value["app_build"] = metadata.appBuild + value["configuration"] = metadata.configuration + return DroneDockDiagnostics.json(value) + } +} + +/// 构建信息在会话创建时固定,不因后续事件或外部传入字段变化。 +struct DroneDockTaskDiagnosticMetadata: Sendable { + /// App 对外版本号。 + let appVersion: String + /// App 构建号。 + let appBuild: String + /// 当前构建配置,值为 Debug 或 Release。 + let configuration: String + + /// 从当前 App 获取只读构建信息;缺失时明确标为 unknown。 + static var current: Self { + #if DEBUG + let configuration = "Debug" + #else + let configuration = "Release" + #endif + return Self(appVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown", + appBuild: Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown", + configuration: configuration) + } +} diff --git a/suixinkan/Features/DroneDock/API/DroneDockCommandAPI.swift b/suixinkan/Features/DroneDock/API/DroneDockCommandAPI.swift index 735af8f..9390d4c 100644 --- a/suixinkan/Features/DroneDock/API/DroneDockCommandAPI.swift +++ b/suixinkan/Features/DroneDock/API/DroneDockCommandAPI.swift @@ -4,7 +4,7 @@ import Foundation protocol DroneDockCommandSending: Sendable { /// 提交任务 ID 和白名单指令,不创建任务、不选机,也不自动重试。 @MainActor - func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse + func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse } /// 朱工 command 合同适配,真实传输仍受统一 Debug 禁飞策略阻断。 @@ -15,15 +15,17 @@ final class DroneDockCommandAPI: DroneDockCommandSending { /// 注入统一客户端;模拟调试使用完全不转发网络的响应替身。 init(client: APIClient) { self.client = client } - /// 每次仅发送 id 和 command,回执必须对应同一任务及同一指令。 - func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse { + /// 每次点击使用独立幂等键,回执必须对应同一任务、指令及请求。 + func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse { try Task.checkCancellation() - guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请返回任务页确认") } + guard taskID > 0, !clientRequestID.isEmpty else { throw APIError.networkFailed("缺少有效拍摄任务或指令标识,请返回任务页确认") } let response: DroneDockCommandResponse = try await client.send(APIRequest( method: .post, path: "/api/app/airport/command", - body: CommandBody(taskID: taskID, command: command.rawValue) + body: CommandBody(taskID: taskID, command: command.rawValue, clientRequestID: clientRequestID) )) - guard response.orderFlightTaskID == taskID, response.command == command.rawValue else { + guard response.orderFlightTaskID == taskID, response.command == command.rawValue, + DroneDockHomeMetric.usableText(response.commandID) != nil, + response.clientRequestID == nil || response.clientRequestID == clientRequestID else { throw APIError.decodeFailed("安全指令回执的任务或指令不一致,请核对原任务状态") } return response @@ -33,8 +35,9 @@ final class DroneDockCommandAPI: DroneDockCommandSending { private struct CommandBody: Encodable { let taskID: Int let command: String + let clientRequestID: String /// 朱工请求字段映射,不附加飞机或模拟标志。 - private enum CodingKeys: String, CodingKey { case taskID = "id", command } + private enum CodingKeys: String, CodingKey { case taskID = "id", command, clientRequestID = "client_request_id" } } } diff --git a/suixinkan/Features/DroneDock/Models/DroneDockCommandModels.swift b/suixinkan/Features/DroneDock/Models/DroneDockCommandModels.swift index cb16582..2d1be22 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockCommandModels.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockCommandModels.swift @@ -6,7 +6,7 @@ enum DroneDockSafetyCommand: String, CaseIterable, Sendable { case pause = "flighttask_pause" /// 恢复已暂停的航线。 case resume = "flighttask_recovery" - /// 立即返航;服务端会中断当前任务并释放飞行锁。 + /// 立即返航;中断拍摄结果,回巢前仍占用设备。 case returnHome = "return_home" /// 取消返航,不代表已恢复或重新创建原拍摄任务。 case cancelReturn = "return_home_cancel" @@ -14,6 +14,26 @@ enum DroneDockSafetyCommand: String, CaseIterable, Sendable { /// 指令受理回执;仅保留后端返回的身份、读数与状态,不推断设备已完成动作。 struct DroneDockCommandResponse: Decodable, Equatable, Sendable { + /// 明确受理标记,仅受理不表示设备已执行。 + let accepted: Bool? + /// 回执探测时是否确认设备状态;页面最终仍读取完整 shooting/WS。 + let deviceConfirmed: Bool? + /// 本次指令的服务端唯一标识。 + let commandID: String? + /// 回显本次点击的幂等键,提供时必须与请求一致。 + let clientRequestID: String? + /// 回执顶层的指令进度;完整任务快照位于 flight_control 内。 + let pendingCommand: DroneDockCommandProgress? + /// 受理提示原文,用于诊断,不作为展示状态。 + let hint: String? + /// 回执所属批次,必须与提交时一致。 + let executionBatch: Int64? + /// 回执对应快照版本,用作后续状态核对的最低版本。 + let stateVersion: Int64? + /// 设备身份在提供时必须匹配任务锁定设备。 + let planeID: Int? + /// 回执中的设备状态不替代完整任务快照。 + let flightControl: DroneDockFlightControl? /// 文档要求回显的订单飞行任务 ID。 let orderFlightTaskID: Int? /// 本次回显的指令码,API 核验其与请求一致。 @@ -29,6 +49,9 @@ struct DroneDockCommandResponse: Decodable, Equatable, Sendable { /// 朱工指令回执字段映射。 private enum CodingKeys: String, CodingKey { + case accepted, deviceConfirmed = "device_confirmed", hint, executionBatch = "execution_batch" + case commandID = "command_id", clientRequestID = "client_request_id", pendingCommand = "pending_command" + case stateVersion = "state_version", planeID = "plane_id", flightControl = "flight_control" case orderFlightTaskID = "order_flight_task_id", command, airportSN = "airport_sn" case djiStatus = "dji_status", metrics } @@ -36,6 +59,16 @@ struct DroneDockCommandResponse: Decodable, Equatable, Sendable { /// 不补造身份、状态或读数,完整 JSON 仍保留实际出现的 null 字段。 init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) + accepted = try container.decodeIfPresent(Bool.self, forKey: .accepted) + deviceConfirmed = try container.decodeIfPresent(Bool.self, forKey: .deviceConfirmed) + commandID = try container.decodeIfPresent(String.self, forKey: .commandID) + clientRequestID = try container.decodeIfPresent(String.self, forKey: .clientRequestID) + pendingCommand = try container.decodeIfPresent(DroneDockCommandProgress.self, forKey: .pendingCommand) + hint = try container.decodeIfPresent(String.self, forKey: .hint) + executionBatch = try container.decodeIfPresent(Int64.self, forKey: .executionBatch) + stateVersion = try container.decodeIfPresent(Int64.self, forKey: .stateVersion) + planeID = try container.decodeIfPresent(Int.self, forKey: .planeID) + flightControl = try container.decodeIfPresent(DroneDockFlightControl.self, forKey: .flightControl) orderFlightTaskID = try container.decodeIfPresent(Int.self, forKey: .orderFlightTaskID) command = try container.decodeIfPresent(String.self, forKey: .command) airportSN = try container.decodeIfPresent(String.self, forKey: .airportSN) diff --git a/suixinkan/Features/DroneDock/Models/DroneDockCommandOperation.swift b/suixinkan/Features/DroneDock/Models/DroneDockCommandOperation.swift new file mode 100644 index 0000000..52947e3 --- /dev/null +++ b/suixinkan/Features/DroneDock/Models/DroneDockCommandOperation.swift @@ -0,0 +1,28 @@ +import Foundation + +/// 单次点击的本地生命周期;等待只作用于对应按钮,不充当页面业务阶段。 +enum DroneDockCommandOperationPhase: Sendable { + case queued, sending, pending, unknown, confirmed, finished +} + +/// 同任务批次内的幂等指令上下文;设备身份和提交版本防止迟到响应恢复旧锁。 +struct DroneDockCommandOperation: Sendable { + let requestID: String + let command: DroneDockSafetyCommand + let batch: Int64 + let sequence: Int + let generation: Int + let submittedVersion: Int64 + let planeID: Int + let airportSN: String? + let resumePhase: String? + var commandID: String? + var minimumVersion: Int64? + var phase: DroneDockCommandOperationPhase = .queued + var error: String? + + /// 未获得明确结果时禁止重复提交同一动作,其他安全动作独立授权。 + var isWaiting: Bool { phase != .finished } + /// 已确认但尚未收到更新快照时停止动画,仍防止按旧权限重复点击同一动作。 + var isLoading: Bool { isWaiting && phase != .confirmed && phase != .unknown } +} diff --git a/suixinkan/Features/DroneDock/Models/DroneDockFlightControl.swift b/suixinkan/Features/DroneDock/Models/DroneDockFlightControl.swift new file mode 100644 index 0000000..c3dd63c --- /dev/null +++ b/suixinkan/Features/DroneDock/Models/DroneDockFlightControl.swift @@ -0,0 +1,87 @@ +import Foundation + +/// 设备执行态独立于拍摄结果;未知或不一致状态不提供控制权限。 +enum DroneDockFlightControlState: String, Sendable { + case starting, executing, paused, returning, returned, unknown +} + +/// shooting/WS 的批次设备状态;原值保留以兼容未来枚举,但未知值不会开放操作。 +struct DroneDockFlightControl: Decodable, Equatable, Sendable { + /// 后端原始执行态。 + let state: String? + /// 设备遥测确认是否仍在飞行;未知保持原值,不单独覆盖后端操作许可。 + let isAirborne: Bool? + /// arrival_wait 是自动到点等待,manual 才是已确认的手动暂停。 + let pauseReason: String? + /// 司空原始航线态仅用于联调对照,不能直接代替手动暂停判定。 + let djiTaskStatus: String? + /// 继续任务将恢复的业务阶段,返航暂停后仍恢复返航。 + let resumePhase: String? + /// manual、normal_complete 或 abnormal,区分拍摄中断和正常拍完。 + let returnReason: String? + /// 明确允许暂停。 + let canPause: Bool? + /// 明确允许继续任务。 + let canResume: Bool? + /// 明确允许立即返航。 + let canReturnHome: Bool? + /// inside 是已回巢的必要依据,缺失或 outside 均不能视为回巢。 + let droneInDock: String? + /// 状态所属航线批次。 + let executionBatch: Int64? + /// 当前批次指令进度,供对应按钮结束等待,不覆盖业务阶段。 + let pendingCommand: DroneDockCommandProgress? + + /// 字段与 HTTP/WS 共用合同对应。 + private enum CodingKeys: String, CodingKey { + case state, isAirborne = "is_airborne", pauseReason = "pause_reason" + case djiTaskStatus = "dji_task_status" + case resumePhase = "resume_phase", returnReason = "return_reason" + case canPause = "can_pause", canResume = "can_resume", canReturnHome = "can_return_home" + case droneInDock = "drone_in_dock", executionBatch = "execution_batch" + case pendingCommand = "pending_command" + } + + /// 仅同一有效批次返回已知执行态;回巢仍须 inside,遥测缺失不覆盖后端状态。 + func resolvedState(for batch: Int64?) -> DroneDockFlightControlState { + guard let batch, batch > 0, executionBatch == batch, + let state, let value = DroneDockFlightControlState(rawValue: state) else { return .unknown } + if value == .returned { return droneInDock == "inside" ? .returned : .unknown } + if value == .paused && pauseReason != "manual" { return .unknown } + return value + } +} + +/// HTTP 回执和完整快照共用的指令进度;标识均由服务端回显,不按到包顺序猜测成功。 +struct DroneDockCommandProgress: Decodable, Equatable, Sendable { + /// 服务端唯一指令标识。 + let commandID: String? + /// 本次点击生成的幂等请求标识。 + let clientRequestID: String? + /// 明确对应的安全指令。 + let command: String? + /// pending、succeeded、failed 或 superseded;未知值继续只读核对。 + let status: String? + /// 服务端若提供失败说明则用于本次操作提示。 + let message: String? + + /// 与后端原始字段对应。 + private enum CodingKeys: String, CodingKey { + case commandID = "command_id", clientRequestID = "client_request_id", command, status, message + } +} + +/// 服务端重召唤门禁;客户端仍需验证设备回巢、可用性及操作防重锁。 +struct DroneDockShootingRestartGate: Decodable, Equatable, Sendable { + /// true 才允许进入重召唤校验。 + let canRestart: Bool? + /// 后端诊断原因码。 + let code: String? + /// 后端限制原因,供用户核对。 + let message: String? + + /// 使用后端原始字段名。 + private enum CodingKeys: String, CodingKey { + case canRestart = "can_restart", code, message + } +} diff --git a/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift b/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift index 1785d77..037e522 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift @@ -40,6 +40,10 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable { let planeStatus: DroneDockShootingPlaneStatus? /// 执行门禁参与展示及本地模拟开拍校验,不能解除真实飞控禁令。 let executeGate: DroneDockShootingExecuteGate? + /// 重召唤许可独立于开拍门禁,缺失不视为允许。 + let restartGate: DroneDockShootingRestartGate? + /// 当前批次设备执行状态与逐项权限,不依赖服务端显示文案。 + let flightControl: DroneDockFlightControl? /// 服务端拍摄阶段和页面提示。 let ui: DroneDockShootingUI? /// 完整 data 的格式化 JSON,保留未知字段、空值及原 JSON 类型。 @@ -54,6 +58,7 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable { case orderNumber = "order_number", orderFlightTask = "order_flight_task", task case scenic, scenicSpot = "scenic_spot", airLine = "air_line" case header, currentPlane = "current_plane", executeGate = "execute_gate", ui + case restartGate = "restart_gate", flightControl = "flight_control" case metrics, planeStatus = "plane_status" } @@ -79,6 +84,8 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable { metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? [] planeStatus = try container.decodeIfPresent(DroneDockShootingPlaneStatus.self, forKey: .planeStatus) executeGate = try container.decodeIfPresent(DroneDockShootingExecuteGate.self, forKey: .executeGate) + restartGate = try container.decodeIfPresent(DroneDockShootingRestartGate.self, forKey: .restartGate) + flightControl = try container.decodeIfPresent(DroneDockFlightControl.self, forKey: .flightControl) ui = try container.decodeIfPresent(DroneDockShootingUI.self, forKey: .ui) let raw = try DroneDockHomeJSONValue(from: decoder) let encoder = JSONEncoder() @@ -95,7 +102,7 @@ struct DroneDockShootingTaskIdentity: Decodable, Equatable, Sendable { let orderNumber: String? /// 任务所属景区。 let scenicID: Int? - /// 订单飞行任务状态:10 待执行、20 执行中、30 成功、40 失败、50 取消、60 待确认。 + /// 订单飞行任务状态:10 待执行、20 执行中、25 素材上传中、30 成功、40 失败、50 取消、60 待确认。 let status: Int? /// 服务端任务状态文案。 let statusLabel: String? diff --git a/suixinkan/Features/DroneDock/Models/DroneDockShootingSocketMessage.swift b/suixinkan/Features/DroneDock/Models/DroneDockShootingSocketMessage.swift index c274705..d0f9d0f 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockShootingSocketMessage.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockShootingSocketMessage.swift @@ -10,6 +10,7 @@ enum DroneDockShootingSocketMessage { case opened case subscribed(taskID: Int, hasSnapshot: Bool) case snapshot(DroneDockShootingResponse) + case subscriptionRejected(code: Int, message: String) case rejected(code: Int, message: String) case unrelated @@ -24,9 +25,16 @@ enum DroneDockShootingSocketMessage { guard let root = json as? [String: Any], let code = root["code"] as? Int else { throw APIError.invalidResponse } if code != 100000 { - return .rejected(code: code, message: root["msg"] as? String ?? "任务订阅失败") + let message = root["msg"] as? String ?? "任务订阅失败" + if let body = root["data"] as? [String: Any], + body["type"] as? Int == 310, body["subscribed"] as? Bool == false { + return .subscriptionRejected(code: code, message: message) + } + return .rejected(code: code, message: message) } guard let body = root["data"] as? [String: Any] else { throw APIError.invalidResponse } + // 链路就绪和 310 已入站仅供诊断,不能替代正式订阅结果,即使误带了订阅字段。 + if let ack = body["ack"] as? String, ack == "ready" || ack == "received" { return .unrelated } if let subscribed = body["subscribed"] as? Bool, subscribed { guard let id = body["order_flight_task_id"] as? Int, let hasSnapshot = body["has_snapshot"] as? Bool else { throw APIError.invalidResponse } diff --git a/suixinkan/Features/DroneDock/Models/DroneDockTaskPresentation.swift b/suixinkan/Features/DroneDock/Models/DroneDockTaskPresentation.swift index 89af5e3..86caae4 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockTaskPresentation.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockTaskPresentation.swift @@ -18,6 +18,8 @@ enum DroneDockTaskDisplayPhase: String, Equatable, Sendable { case paused /// 服务端明确正在返航。 case returning + /// 明确返回机巢,本次拍摄仍为中断结果。 + case returned /// 服务端明确任务已完成。 case completed /// 已确认的任务或航线执行失败。 @@ -30,15 +32,15 @@ enum DroneDockTaskDisplayPhase: String, Equatable, Sendable { case readError } -/// 任务状态区可呈现的动作;开始仅在明确注入本地模拟服务时可用,真实飞控保持禁用。 +/// 本地状态区的动作,实际执行受操作服务、设备许可和防重复提交门禁共同约束。 enum DroneDockTaskDisplayAction: Equatable, Sendable { /// 重新读取同一任务。 case refresh - /// 开始拍摄动作;真实入口无服务,只有本地模拟可提交验证。 + /// 同一任务的开始拍摄动作。 case start - /// 恢复拍摄占位动作,本轮禁用。 + /// 继续已暂停的任务,包括恢复返航;实际许可由设备状态和操作锁决定。 case resume - /// 失败后的重新召唤占位动作;尚未接入重新准备流程,始终禁用。 + /// 设备已回巢且后端门禁允许后的重新召唤。 case retry /// 查看已明确完成任务的订单素材。 case materials @@ -52,7 +54,7 @@ struct DroneDockTaskPresentation: Equatable, Sendable { let phase: DroneDockTaskDisplayPhase /// 阶段标题。 let title: String - /// 服务端说明或读取错误,完整文字可由界面展开。 + /// 本地阶段说明或实际失败原因,完整文字可由界面展开。 let message: String /// 当前任务设备的状态文案。 let deviceStatus: String @@ -60,7 +62,7 @@ struct DroneDockTaskPresentation: Equatable, Sendable { let action: DroneDockTaskDisplayAction /// 主动作名称,无动作时为 nil。 let actionTitle: String? - /// 是否可触发动作;真实开始、恢复和重新召唤保持禁用。 + /// 是否可触发动作;禁用状态仍可保留按钮作为进度提示。 let isActionEnabled: Bool /// 主动作下方的真实设备限制说明,未提供时不展示。 let actionNote: String? diff --git a/suixinkan/Features/DroneDock/Models/DroneDockTaskTraceFields.swift b/suixinkan/Features/DroneDock/Models/DroneDockTaskTraceFields.swift new file mode 100644 index 0000000..f4c1826 --- /dev/null +++ b/suixinkan/Features/DroneDock/Models/DroneDockTaskTraceFields.swift @@ -0,0 +1,71 @@ +import Foundation + +/// 标记完整任务快照实际进入 App 的通道,避免把 HTTP 与 WS 的先后关系混淆。 +enum DroneDockTaskSnapshotSource: String, Sendable { + case http, webSocket = "websocket", unspecified +} + +/// 任务诊断摘要保留状态原值和明确身份;完整原始 JSON 仍由原网络日志输出。 +enum DroneDockTaskTraceFields { + /// 把可选值表示为 JSON null,不把缺失的设备证据补成 false 或零。 + static func value(_ value: T?) -> Any { value.map { $0 as Any } ?? NSNull() } + + /// 对照后端业务阶段、飞控事实、门禁及读数来源,不重写响应对象。 + static func snapshot(_ snapshot: DroneDockShootingResponse?) -> [String: Any] { + guard let snapshot else { return ["snapshot_present": false] } + let control = snapshot.flightControl + let raw = (try? JSONSerialization.jsonObject(with: Data(snapshot.dataJSON.utf8))) as? [String: Any] + let rawControl = raw?["flight_control"] as? [String: Any] + return [ + "snapshot_present": true, "order_flight_task_id": value(snapshot.orderFlightTaskID), + "task_id": value(snapshot.task?.id), "oft_id": value(snapshot.orderFlightTask?.id), + "execution_batch": value(snapshot.executionBatch), "state_version": value(snapshot.stateVersion), + "ui_phase": value(snapshot.ui?.phase), "task_status": value(snapshot.task?.status), + "oft_status": value(snapshot.orderFlightTask?.status), + "wayline_status": value(snapshot.task?.waylineStatus), + "oft_wayline_status": value(snapshot.orderFlightTask?.waylineStatus), + "result_code": value(snapshot.orderFlightTask?.resultCode ?? snapshot.task?.resultCode), + "plane_id": value(snapshot.currentPlane?.id), "airport_sn": value(snapshot.currentPlane?.snNumber), + "work_status": value(snapshot.currentPlane?.workStatus), + "flight_control": ["state": value(control?.state), + "resolved_state": control?.resolvedState(for: snapshot.executionBatch).rawValue ?? "unknown", + "execution_batch": value(control?.executionBatch), "is_airborne": value(control?.isAirborne), + "dji_task_status": value(control?.djiTaskStatus), + "pause_reason": value(control?.pauseReason), "resume_phase": value(control?.resumePhase), + "return_reason": value(control?.returnReason), "drone_in_dock": value(control?.droneInDock), + "can_pause": value(control?.canPause), "can_resume": value(control?.canResume), + "can_return_home": value(control?.canReturnHome), + "evidence": rawControl?["evidence"] ?? NSNull(), + "pending_command": progress(control?.pendingCommand)], + "can_start": value(snapshot.executeGate?.canExecute), "start_gate_code": value(snapshot.executeGate?.code), + "can_restart": value(snapshot.restartGate?.canRestart), "restart_gate_code": value(snapshot.restartGate?.code), + "metrics_count": snapshot.metrics.count, "metrics_stale": value(snapshot.metricsStale), + "metrics_updated_at": value(snapshot.metricsUpdatedAt), + "metrics": raw?["metrics"] ?? NSNull(), + "metric_display_values": snapshot.metrics.map { ["key": $0.key, "value": $0.displayText] } + ] + } + + /// 回执和快照共用的指令标识摘要,可与 client_request_id、command_id 逐条对应。 + static func progress(_ progress: DroneDockCommandProgress?) -> Any { + guard let progress else { return NSNull() } + return ["command_id": value(progress.commandID), "client_request_id": value(progress.clientRequestID), + "command": value(progress.command), "status": value(progress.status), "message": value(progress.message)] + } + + /// 召唤回执只摘录身份和阶段,记录是否存在初始前往状态依据。 + static func summon(_ receipt: DroneDockShootResponse?) -> [String: Any] { + guard let text = receipt?.dataJSON, + let object = try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] else { + return ["receipt_present": receipt != nil, "data_present": false] + } + var result: [String: Any] = ["receipt_present": true, "data_present": true] + for key in ["accepted", "order_flight_task_id", "task_id", "execution_batch", "state_version", "plane_id", "airport_sn", "ui", "flight_control"] { + result[key] = object[key] ?? NSNull() + } + if let task = object["order_flight_task"] as? [String: Any] { + result["order_flight_task"] = task.filter { ["id", "order_number", "scenic_id", "status", "wayline_task_id"].contains($0.key) } + } + return result + } +} diff --git a/suixinkan/Features/DroneDock/Services/DroneDockShootingRealtimeSession.swift b/suixinkan/Features/DroneDock/Services/DroneDockShootingRealtimeSession.swift index 1ca9164..4b98193 100644 --- a/suixinkan/Features/DroneDock/Services/DroneDockShootingRealtimeSession.swift +++ b/suixinkan/Features/DroneDock/Services/DroneDockShootingRealtimeSession.swift @@ -161,6 +161,10 @@ final class DroneDockShootingRealtimeSession { log("websocket.snapshot_ignored", fields: ["reason": "old_version"]) case .invalid: throw APIError.decodeFailed("任务快照身份或结构不一致") } + case .subscriptionRejected(let code, let message): + // 310 明确拒绝可按错误码处理,不依赖服务端说明的语言或措辞。 + if code == 100099 { deny(message) } + else { fail(message) } case .rejected(let code, let message): if code == 100099, message.contains("无权订阅") || message.contains("飞行任务不存在") { deny(message) diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift index d3c11ec..7be8862 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift @@ -54,6 +54,7 @@ final class DroneDockPreparationViewModel { outcomeUnknown: summonOutcomeUnknown, code: shootErrorCode) } + private let diagnostics: DroneDockTaskDiagnostics private let service: any DroneDockPreparationServing private let planeStatusService: any DroneDockPlaneStatusServing private let taskCreationService: any DroneDockTaskCreating @@ -80,7 +81,9 @@ final class DroneDockPreparationViewModel { taskCreationService: any DroneDockTaskCreating, shootService: any DroneDockShootServing, allowsTaskSubmission: Bool = true, + diagnostics: DroneDockTaskDiagnostics = DroneDockTaskDiagnostics(), currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) { + self.diagnostics = diagnostics self.context = context self.order = order self.service = service @@ -91,6 +94,23 @@ final class DroneDockPreparationViewModel { self.currentContext = currentContext } + /// 准备页会话可与后续任务页入口事件关联,区分重新进入和同一次召唤。 + var diagnosticSessionID: String { diagnostics.sessionID } + + /// 准备阶段日志只观察现有选择、门禁与请求结果,不发起任何额外请求。 + func recordPreparationEvent(_ event: String, fields: [String: Any] = [:]) { + let summary: [String: Any] = ["source": "preparation", "scenic_id": context.scenicID, + "order_number": DroneDockTaskTraceFields.value(order.orderNumber), + "spot_id": DroneDockTaskTraceFields.value(selectedSpotID), + "air_line_id": DroneDockTaskTraceFields.value(selectedRouteID), + "created_task_id": DroneDockTaskTraceFields.value(createdTask?.taskID), + "is_creating": isCreatingTask, "is_summoning": isSummoning, + "creation_outcome_unknown": taskCreationOutcomeUnknown, "summon_outcome_unknown": summonOutcomeUnknown, + "allows_task_submission": allowsTaskSubmission, "primary_action_enabled": isPrimaryActionEnabled] + diagnostics.record(event, taskID: createdTask?.taskID ?? 0, + fields: summary.merging(fields) { _, new in new }) + } + /// 当前阶段只创建待飞任务,不以设备电量或位置作为创建任务条件。 var canCreateTask: Bool { guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask, @@ -139,6 +159,7 @@ final class DroneDockPreparationViewModel { /// 主按钮串接创建与召唤;已有任务跳过创建,成功后的导航由页面处理。 @MainActor func prepareAndSummon(onStateChange: @escaping @MainActor () -> Void = {}) async { + recordPreparationEvent("preparation.primary_requested") // 禁飞调试在整条链开始前阻断,避免先残留真实待飞任务再拦截召唤。 guard allowsTaskSubmission, isPrimaryActionEnabled else { return } primaryActionGeneration &+= 1 @@ -180,10 +201,13 @@ final class DroneDockPreparationViewModel { guard acceptsSummon(requestGeneration, taskID: taskID) else { return } do { didSendSummon = true + recordPreparationEvent("summon.sending") let response = try await shootService.shoot(taskID: taskID) guard acceptsSummon(requestGeneration, taskID: taskID) else { return } shootResponse = response - DroneDockDiagnostics.event("summon.receipt_accepted", taskID: taskID) + recordPreparationEvent("summon.receipt_accepted", fields: ["receipt": DroneDockTaskTraceFields.summon(response), + "travel_transition_allowed": response.confirmsTravel(taskID: taskID, orderNumber: order.orderNumber, + scenicID: context.scenicID)]) hasSubmittedSummon = true summonOutcomeUnknown = false } catch { @@ -191,6 +215,7 @@ final class DroneDockPreparationViewModel { didSendSummon = false } guard acceptsSummon(requestGeneration, taskID: taskID) else { return } + recordPreparationEvent("summon.failed_or_unknown", fields: ["error": DroneDockDiagnostics.errorFields(error)]) if error is DeviceCommandDebugBlockedError { shootErrorMessage = DeviceCommandDebugPolicy.blockedMessage } else if case let APIError.serverCode(code, message) = error { @@ -223,6 +248,7 @@ final class DroneDockPreparationViewModel { /// 点击后先校验最新购买配置,再发送一次创建请求;成功留在准备页供核对。 @MainActor func createTask(onStateChange: @escaping @MainActor () -> Void = {}) async { + recordPreparationEvent("create.requested", fields: ["allowed": canCreateTask]) guard allowsTaskSubmission, canCreateTask, let spotID = selectedSpotID, let routeID = selectedRouteID, let number = order.orderNumber, let projectID = order.projectID else { return } taskCreationGeneration &+= 1 @@ -261,6 +287,7 @@ final class DroneDockPreparationViewModel { } guard acceptsTaskCreation(requestGeneration) else { return } didSendTaskCreation = true + recordPreparationEvent("create.sending") let response = try await taskCreationService.createTask(scenicID: context.scenicID, orderNumber: number, spotID: spotID, airLineID: routeID) guard acceptsTaskCreation(requestGeneration) else { return } @@ -269,7 +296,7 @@ final class DroneDockPreparationViewModel { throw APIError.decodeFailed("创建回执与当前订单或项目不一致,请核对任务") } createdTask = response - DroneDockDiagnostics.event("create.receipt_accepted", taskID: response.taskID) + recordPreparationEvent("create.receipt_accepted", fields: ["receipt_task_id": DroneDockTaskTraceFields.value(response.taskID)]) hasCreatedTask = true taskCreationOutcomeUnknown = false } catch { @@ -277,6 +304,7 @@ final class DroneDockPreparationViewModel { didSendTaskCreation = false } guard acceptsTaskCreation(requestGeneration) else { return } + recordPreparationEvent("create.failed_or_unknown", fields: ["error": DroneDockDiagnostics.errorFields(error)]) if error is DeviceCommandDebugBlockedError { taskCreationErrorMessage = DeviceCommandDebugPolicy.blockedMessage } else if didSendTaskCreation { @@ -580,16 +608,16 @@ final class DroneDockPreparationViewModel { } private func markSummonUnknown(reason: String? = nil) { - DroneDockDiagnostics.event("summon.outcome_unknown", taskID: createdTask?.taskID) summonOutcomeUnknown = true shootErrorCode = nil shootErrorMessage = (reason.map { "\($0)。" } ?? "") + "召唤结果待核对,请先核对任务状态,勿重复提交" + recordPreparationEvent("summon.outcome_unknown") } private func markTaskCreationUnknown(reason: String? = nil) { - DroneDockDiagnostics.event("taskcreation.outcome_unknown", taskID: createdTask?.taskID) taskCreationOutcomeUnknown = true taskCreationErrorMessage = (reason.map { "\($0)。" } ?? "") + "创建结果待核对,请先查看订单任务,勿重复提交" + recordPreparationEvent("taskcreation.outcome_unknown") } private static func message(for error: Error) -> String? { diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift index 7a749e1..8376be1 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift @@ -24,16 +24,20 @@ final class DroneDockShootingTaskViewModel { private(set) var hasSubmittedStart = false /// 同任务开拍回执;受理成功不直接替代 shooting 的完整状态快照。 private(set) var startResponse: DroneDockStartShootResponse? - /// 指令提交及其后单次回查期间锁定控制动作,旧状态继续展示。 - private(set) var isSendingCommand = false - /// 当前正在提交或核对的指令;结束后清空。 - private(set) var activeCommand: DroneDockSafetyCommand? - /// 最近一次明确受理且身份一致的指令回执,不作为设备已执行的证据。 + /// 当前有安全指令 HTTP 提交,供生命周期取消使用,不作为其他安全按钮的总锁。 + var isSendingCommand: Bool { commandOperations.values.contains { $0.phase == .sending } } + /// 最近正在提交的动作,仅供诊断;按钮分别读取 isCommandLoading。 + var activeCommand: DroneDockSafetyCommand? { + commandOperations.values.filter { $0.phase == .sending }.max { $0.sequence < $1.sequence }?.command + } + /// 最近一次明确受理且身份一致的指令回执,不替代任务快照。 private(set) var commandResponse: DroneDockCommandResponse? - /// 指令业务拒绝、本地拦截或结果待核对提示。 - private(set) var commandErrorMessage: String? - /// 已发但结果不明确时保持锁定,普通读取不能自动解除或重发。 - private(set) var commandOutcomeUnknown = false + /// 最近一次操作提示,界面按对应动作读取,不覆盖中央业务文案。 + var commandErrorMessage: String? { + commandOperations.values.filter { $0.error != nil }.max { $0.sequence < $1.sequence }?.error + } + /// 任一动作结果未知时,开拍和重召唤保持保护,安全动作仍独立授权。 + var commandOutcomeUnknown: Bool { commandOperations.values.contains { $0.phase == .unknown } } /// 重新召唤提交及其后单次回查期间保留旧画面并锁定其他操作。 private(set) var isResummoning = false /// 重新召唤明确拒绝、本地拦截或待核对的说明。 @@ -45,6 +49,7 @@ final class DroneDockShootingTaskViewModel { /// 重新召唤的原始受理回执,不替代 shooting 的设备状态。 private(set) var resummonResponse: DroneDockShootResponse? + private let diagnostics: DroneDockTaskDiagnostics private let service: any DroneDockShootingServing private let startService: (any DroneDockStartShooting)? private let commandService: (any DroneDockCommandSending)? @@ -60,14 +65,25 @@ final class DroneDockShootingTaskViewModel { private var startGeneration = 0 private var didSendStart = false private var commandGeneration = 0 - private var didSendCommand = false private var resummonGeneration = 0 private var didSendResummon = false private var awaitingResummonSnapshot = false // 仅在首份完整快照返回之前使用同一任务的 going_to_spot 回执,不补造设备状态。 private var hasInitialTravelReceipt: Bool - // 回查仍提供的已受理指令分别保留防重锁,避免另一条指令受理覆盖旧锁。 - private var pendingAcceptedCommands: Set = [] + private var commandOperations: [DroneDockSafetyCommand: DroneDockCommandOperation] = [:] + private var commandSequence = 0 + private var commandTasks: [String: Task] = [:] + private var commandTransportTail: Task? + private var supersededCommandIDs: Set = [] + private var minimumCommandSnapshotVersion: Int64? + private var retainedMetrics: [String: DroneDockHomeMetric] = [:] + private var isUsingRetainedMetrics = false + + /// 当前等待确认的动作,仅用于开拍/重召唤保护,不覆盖页面阶段。 + var pendingCommand: DroneDockSafetyCommand? { + commandOperations.values.filter { $0.phase == .pending || $0.phase == .unknown || $0.phase == .confirmed } + .max { $0.sequence < $1.sequence }?.command ?? remotePendingCommand + } /// 默认只读;仅显式注入操作服务时开放对应动作,Release 入口按授权注入。 init(context: DroneDockHomeContext, taskID: Int, order: DroneDockHomeOrder, @@ -77,7 +93,9 @@ final class DroneDockShootingTaskViewModel { resummonService: (any DroneDockResummonServing)? = nil, initialSummonReceipt: DroneDockShootResponse? = nil, countdownNow: @escaping @Sendable () -> ContinuousClock.Instant = { ContinuousClock.now }, + diagnostics: DroneDockTaskDiagnostics = DroneDockTaskDiagnostics(), currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) { + self.diagnostics = diagnostics self.context = context self.taskID = taskID self.order = order @@ -89,6 +107,45 @@ final class DroneDockShootingTaskViewModel { self.countdownNow = countdownNow self.hasInitialTravelReceipt = context.canLoad && initialSummonReceipt?.confirmsTravel( taskID: taskID, orderNumber: order.orderNumber, scenicID: context.scenicID) == true + recordTaskEvent("task.created", fields: ["initial_travel_receipt": hasInitialTravelReceipt, + "summon_receipt": DroneDockTaskTraceFields.summon(initialSummonReceipt), + "debug_flight_blocked": DeviceCommandDebugPolicy.blocksFlightRequests, + "debug_live_blocked": DeviceCommandDebugPolicy.blocksLiveRequests]) + } + + /// 页面与业务层共享会话标识,串联准备页导航、快照和按钮事件。 + var diagnosticSessionID: String { diagnostics.sessionID } + + /// 记录任务关键事件,不改变接口、定时器、门禁或任何业务状态。 + func recordTaskEvent(_ event: String, fields: [String: Any] = [:]) { + let contextFields: [String: Any] = ["scenic_id": context.scenicID, + "order_number": DroneDockTaskTraceFields.value(order.orderNumber), + "execution_batch": DroneDockTaskTraceFields.value(response?.executionBatch), + "state_version": DroneDockTaskTraceFields.value(response?.stateVersion)] + diagnostics.record(event, taskID: taskID, fields: contextFields.merging(fields) { _, new in new }) + } + + /// 同一时刻的后端证据与本地判断,用于和录屏中的实际显示逐段对照。 + var taskDiagnosticFields: [String: Any] { + let state = presentation + let metrics = telemetry + return ["backend": DroneDockTaskTraceFields.snapshot(response), "local": [ + "phase": state.phase.rawValue, "conflict": resolvedDisplayPhase().1, + "title": state.title, "message": state.message, "action": String(describing: state.action), + "action_enabled": state.isActionEnabled, "countdown_seconds": DroneDockTaskTraceFields.value(state.countdownSeconds), + "pause_allowed": canSendCommand(.pause), "resume_allowed": canSendCommand(.resume), + "return_allowed": canSendCommand(.returnHome), "start_allowed": canStartShooting, + "restart_allowed": canResummon, "pause_loading": isCommandLoading(.pause), + "resume_loading": isCommandLoading(.resume), "return_loading": isCommandLoading(.returnHome), + "start_outcome_unknown": startOutcomeUnknown, "command_outcome_unknown": commandOutcomeUnknown, + "resummon_outcome_unknown": resummonOutcomeUnknown, + "read_access_error": DroneDockTaskTraceFields.value(readAccessError), + "read_error": DroneDockTaskTraceFields.value(errorMessage), + "recording_finished": isRecordingFinished, "stop_live": shouldStopLiveReception, + "using_retained_metrics": isUsingRetainedMetrics, "telemetry_stale": isTelemetryStale, + "telemetry": ["battery": metrics.batteryText, "env_temp": metrics.temperatureText, + "wind_speed": metrics.windText, "rainfall": metrics.rainText, + "signal": metrics.signalText, "satellite": metrics.satelliteText]]] } /// 页面可见时读取同一任务;刷新及普通失败保留旧快照,身份失效立即清除。 @@ -120,11 +177,12 @@ final class DroneDockShootingTaskViewModel { private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false, allowWhileResummoning: Bool = false) async { guard !isLoading, !identityInvalidated, readAccessError == nil, !isStartingShooting || allowWhileStarting, - !isSendingCommand || allowWhileCommand, !isResummoning || allowWhileResummoning else { return } + !isResummoning || allowWhileResummoning else { return } generation &+= 1 let requestGeneration = generation let revisionAtRequest = snapshotRevision isLoading = true + recordTaskEvent("snapshot.http_requested", fields: ["read_generation": requestGeneration, "live_battery": 0]) // 已失败的旧快照须等有效新响应再恢复操作,避免每次重查先短暂放开。 defer { if generation == requestGeneration { @@ -140,8 +198,13 @@ final class DroneDockShootingTaskViewModel { } do { let value = try await service.shooting(taskID: taskID, liveBattery: false) - guard accepts(requestGeneration) else { return } - if applyTaskSnapshot(value) == .invalid { + guard accepts(requestGeneration) else { + recordTaskEvent("snapshot.http_ignored", fields: ["read_generation": requestGeneration, + "current_generation": generation, "reason": "cancelled_or_stale_read", + "incoming": DroneDockTaskTraceFields.snapshot(value)]) + return + } + if applyTaskSnapshot(value, source: .http) == .invalid { response = nil throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取") } @@ -154,7 +217,7 @@ final class DroneDockShootingTaskViewModel { // 迟到 HTTP 失败不能覆盖请求期间已收到的有效实时状态。 guard snapshotRevision == revisionAtRequest else { return } if !(error is CancellationError) { errorMessage = error.localizedDescription } - DroneDockDiagnostics.event("shooting.refresh_failed", taskID: taskID, fields: [ + recordTaskEvent("snapshot.http_failed", fields: [ "retained_snapshot": response != nil, "error": DroneDockDiagnostics.errorFields(error) ]) } @@ -163,34 +226,86 @@ final class DroneDockShootingTaskViewModel { /// HTTP 和推送共享完整快照入口,按执行批次、版本去重,绝不按到达顺序覆盖。 @MainActor @discardableResult - func applyTaskSnapshot(_ value: DroneDockShootingResponse) -> DroneDockSnapshotAcceptance { - guard readAccessError == nil, accepts(generation), matchesIdentity(value) else { return .invalid } + func applyTaskSnapshot(_ value: DroneDockShootingResponse, + source: DroneDockTaskSnapshotSource = .unspecified) -> DroneDockSnapshotAcceptance { + let incoming = DroneDockTaskTraceFields.snapshot(value) + func rejected(_ result: DroneDockSnapshotAcceptance, reason: String) -> DroneDockSnapshotAcceptance { + recordTaskEvent("snapshot.ignored", fields: ["source": source.rawValue, + "result": String(describing: result), "reason": reason, "incoming": incoming]) + return result + } + guard readAccessError == nil else { return rejected(.invalid, reason: "read_access_denied") } + guard accepts(generation) else { return rejected(.invalid, reason: "cancelled_or_identity_changed") } + guard matchesIdentity(value) else { return rejected(.invalid, reason: "task_order_or_scenic_mismatch") } + let previousBatch = response?.executionBatch + let previousVersion = response?.stateVersion + let previousPhase = presentation.phase.rawValue if let oldBatch = response?.executionBatch, let oldVersion = response?.stateVersion { - guard let batch = value.executionBatch, let version = value.stateVersion else { return .outdated } - if batch < oldBatch || (batch == oldBatch && version < oldVersion) { return .outdated } + guard let batch = value.executionBatch, let version = value.stateVersion else { + return rejected(.outdated, reason: "missing_batch_or_version") + } + if batch == oldBatch, version < (minimumCommandSnapshotVersion ?? 0) { + return rejected(.outdated, reason: "below_command_receipt_version_floor") + } + if batch < oldBatch || (batch == oldBatch && version < oldVersion) { + return rejected(.outdated, reason: "older_batch_or_version") + } if batch == oldBatch && version == oldVersion { errorMessage = nil snapshotRevision &+= 1 - return .duplicate + return rejected(.duplicate, reason: "same_batch_and_version") + } + } + if let oldBatch = response?.executionBatch, let newBatch = value.executionBatch, newBatch > oldBatch { + recordTaskEvent("task.new_batch", fields: ["old_batch": oldBatch, "new_batch": newBatch]) + // 新批次是新的控制上下文;旧请求无论成功、失败还是取消均不得重建旧锁。 + startGeneration &+= 1 + invalidateCommand() + resummonGeneration &+= 1 + isStartingShooting = false + isResummoning = false + didSendStart = false + didSendResummon = false + awaitingResummonSnapshot = false + clearPendingCommand() + minimumCommandSnapshotVersion = nil + commandResponse = nil + hasSubmittedStart = false + startOutcomeUnknown = false + startErrorMessage = nil + startResponse = nil + hasSubmittedResummon = false + resummonOutcomeUnknown = false + resummonErrorMessage = nil + resummonResponse = nil + } + if response?.executionBatch != value.executionBatch || response?.currentPlane?.id != value.currentPlane?.id { + retainedMetrics.removeAll() + } + isUsingRetainedMetrics = false + for key in ["battery", "env_temp", "wind_speed", "rainfall", "signal", "satellite"] { + if let metric = value.metrics.first(where: { $0.key == key && $0.displayText != "—" }) { + retainedMetrics[key] = metric + } else if retainedMetrics[key] != nil { + isUsingRetainedMetrics = true } } response = value + reconcilePendingCommand() if resolvedDisplayPhase().0 == .ready, arrivalCountdownDeadlines[recordingExecutionID] == nil { arrivalCountdownDeadlines[recordingExecutionID] = countdownNow().advanced(by: .seconds(30)) + recordTaskEvent("countdown.started", fields: ["seconds": 30, "source": source.rawValue]) } hasInitialTravelReceipt = false errorMessage = nil snapshotRevision &+= 1 - DroneDockDiagnostics.event("shooting.snapshot_applied", taskID: taskID, fields: [ - "phase": presentation.phase.rawValue, - "execution_batch": value.executionBatch as Any? ?? NSNull(), - "state_version": value.stateVersion as Any? ?? NSNull(), - "plane_id": value.currentPlane?.id as Any? ?? NSNull() - ]) if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .postShootUploading, .postShootUploadFailed, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) { awaitingResummonSnapshot = false } - pendingAcceptedCommands.formIntersection(availableSafetyCommands) + recordTaskEvent("snapshot.applied", fields: ["source": source.rawValue, + "previous_batch": DroneDockTaskTraceFields.value(previousBatch), + "previous_version": DroneDockTaskTraceFields.value(previousVersion), + "previous_local_phase": previousPhase, "state": taskDiagnosticFields]) return .applied } @@ -201,6 +316,7 @@ final class DroneDockShootingTaskViewModel { isLoading = false readAccessError = message errorMessage = message + recordTaskEvent("task.read_access_stopped", fields: ["message": message]) } /// 只把已确认的权限信息视为终止条件,不把所有 100099 业务错误一概当成无权限。 @@ -213,6 +329,7 @@ final class DroneDockShootingTaskViewModel { /// 使旧请求失效;同一身份离页或进入后台可保留快照,账号变化始终清除并停止旧任务读取。 @MainActor func invalidate(preservingSnapshot: Bool = false) { + recordTaskEvent("task.invalidated", fields: ["preserving_snapshot": preservingSnapshot]) invalidateStartShooting() invalidateCommand() invalidateResummon() @@ -226,10 +343,9 @@ final class DroneDockShootingTaskViewModel { startResponse = nil startErrorMessage = nil commandResponse = nil - commandErrorMessage = nil resummonResponse = nil resummonErrorMessage = nil - pendingAcceptedCommands.removeAll() + clearPendingCommand() errorMessage = "账号或景区已变化,请返回工作台重新进入" } else { if !preservingSnapshot { response = nil } @@ -240,9 +356,13 @@ final class DroneDockShootingTaskViewModel { /// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;Debug 真实页面保持禁用。 var canStartShooting: Bool { startService != nil && context.canLoad && taskID > 0 && !identityInvalidated + && hasControlSnapshotIdentity + && hasKnownShootingTaskState && readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil && !hasSubmittedStart && !startOutcomeUnknown - && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot && pendingAcceptedCommands.isEmpty + && !commandOperations.values.contains(where: { $0.isWaiting }) + && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot && pendingCommand == nil + && flightControlState == .executing && resolvedDisplayPhase().0 == .ready && response?.executeGate?.canExecute == true && response?.executeGate?.primaryAction == "start_shoot" @@ -252,6 +372,7 @@ final class DroneDockShootingTaskViewModel { /// 提交一次开拍并单次读取同任务;失败保留原快照,不重建、不自动重发控制请求。 @MainActor func startShooting(onStateChange: @escaping @MainActor () -> Void = {}) async { + recordTaskEvent("start.requested", fields: ["allowed": canStartShooting, "state": taskDiagnosticFields]) guard canStartShooting, let startService else { return } guard context.hasSameIdentity(as: currentContext()) else { identityInvalidated = true @@ -289,7 +410,8 @@ final class DroneDockShootingTaskViewModel { throw APIError.decodeFailed("开始拍摄回执与当前任务或飞机不一致,请先核对任务状态") } startResponse = value - DroneDockDiagnostics.event("start.receipt_accepted", taskID: taskID) + recordTaskEvent("start.receipt_accepted", fields: ["receipt_task_id": DroneDockTaskTraceFields.value(value.orderFlightTaskID), + "receipt_plane_id": DroneDockTaskTraceFields.value(value.planeID)]) hasSubmittedStart = true startOutcomeUnknown = false onStateChange() @@ -317,34 +439,63 @@ final class DroneDockShootingTaskViewModel { didSendStart = false } - /// 只识别当前快照明确提供的四种指令,未知值忽略,同一指令只展示一次。 - var availableSafetyCommands: [DroneDockSafetyCommand] { - var commands: [DroneDockSafetyCommand] = [] - for item in response?.ui?.commands ?? [] { - guard let raw = item.command, let command = DroneDockSafetyCommand(rawValue: raw), - !commands.contains(command) else { continue } - commands.append(command) - } - return commands + /// 设备执行态必须属于当前完整快照批次;空对象、未知枚举或缺少回巢依据保持未知。 + var flightControlState: DroneDockFlightControlState { + response?.flightControl?.resolvedState(for: response?.executionBatch) ?? .unknown } - /// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。 + /// 安全操作服从同批次的后端明确许可;遥测未知或拍摄结果不单独否决权限。 + var availableSafetyCommands: [DroneDockSafetyCommand] { + guard hasControlSnapshotIdentity, let control = response?.flightControl else { return [] } + switch flightControlState { + case .starting: + return control.canReturnHome == true ? [.returnHome] : [] + case .executing: + return [(DroneDockSafetyCommand.pause, control.canPause), (.returnHome, control.canReturnHome)] + .compactMap { $0.1 == true ? $0.0 : nil } + case .paused: + return [(DroneDockSafetyCommand.resume, control.canResume), (.returnHome, control.canReturnHome)] + .compactMap { $0.1 == true ? $0.0 : nil } + case .returning: + return control.canPause == true ? [.pause] : [] + case .returned, .unknown: + return [] + } + } + + /// 本次按钮独立等待,包括重进页读取到的服务端 pending;未知结果不自动重发。 + func isCommandLoading(_ command: DroneDockSafetyCommand) -> Bool { + commandOperations[command]?.isLoading == true || remotePendingCommand == command + } + + /// 指令结果未知仅影响该动作的辅助提示和防重。 + func isCommandOutcomeUnknown(_ command: DroneDockSafetyCommand) -> Bool { + commandOperations[command]?.phase == .unknown + } + + /// 读取对应动作的错误,不让暂停失败污染返航按钮。 + func commandErrorMessage(for command: DroneDockSafetyCommand) -> String? { + commandOperations[command]?.error + } + + /// 已知飞行状态与逐项权限授权,不按业务失败/素材状态或另一按钮 loading 拦截。 func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool { commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated - && !isTaskAwaitingConfirmation - && readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil - && !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot - && !pendingAcceptedCommands.contains(command) - && (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID) + && readAccessError == nil && !isStartingShooting && !isResummoning + && !resummonOutcomeUnknown && !awaitingResummonSnapshot + && commandOperations[command]?.isWaiting != true && !isCommandLoading(command) && (response?.currentPlane?.id ?? 0) > 0 && availableSafetyCommands.contains(command) } - /// 只提交当前任务的一次指令,受理后单次回查;不轮询、不改派飞机、不自动重试。 + /// 每次点击立即进入对应按钮等待;只串行 HTTP 提交,不等待前一设备指令确认。 @MainActor func sendCommand(_ command: DroneDockSafetyCommand, onStateChange: @escaping @MainActor () -> Void = {}) async { - guard canSendCommand(command), let commandService else { return } + recordTaskEvent("command.requested", fields: ["command": command.rawValue, + "allowed": canSendCommand(command), "state": taskDiagnosticFields]) + guard canSendCommand(command), let batch = response?.executionBatch, + let plane = response?.currentPlane else { return } guard context.hasSameIdentity(as: currentContext()) else { identityInvalidated = true invalidate() @@ -352,71 +503,180 @@ final class DroneDockShootingTaskViewModel { return } guard !Task.isCancelled else { return } - invalidatePendingRefresh() - commandGeneration &+= 1 - let requestGeneration = commandGeneration - isSendingCommand = true - activeCommand = command - didSendCommand = false - commandResponse = nil - commandErrorMessage = nil - onStateChange() - defer { - if commandGeneration == requestGeneration { - if Task.isCancelled && didSendCommand && commandResponse == nil { markCommandUnknown() } - isSendingCommand = false - activeCommand = nil - didSendCommand = false - onStateChange() - } + commandSequence += 1 + let operation = DroneDockCommandOperation(requestID: UUID().uuidString, command: command, + batch: batch, sequence: commandSequence, generation: commandGeneration, + submittedVersion: response?.stateVersion ?? 0, planeID: plane.id ?? 0, + airportSN: plane.snNumber, resumePhase: response?.flightControl?.resumePhase) + commandOperations[command] = operation + recordCommandEvent("command.queued", operation: operation) + let predecessor = commandTransportTail + let task = Task { @MainActor [weak self] in + await predecessor?.value + guard let self else { return } + await self.submitCommand(operation, onStateChange: onStateChange) } - guard acceptsCommand(requestGeneration) else { return } + commandTransportTail = task + commandTasks[operation.requestID] = task + onStateChange() + await withTaskCancellationHandler { + await task.value + } onCancel: { + task.cancel() + } + commandTasks[operation.requestID] = nil + guard acceptsCommand(operation) else { return } + if commandOperations[command]?.commandID != nil { + await refreshSnapshot(allowWhileStarting: false, allowWhileCommand: true) + } + onStateChange() + } + + /// 回执只处理对应请求的按钮进度;随后由统一快照更新业务阶段。 + @MainActor + private func submitCommand(_ operation: DroneDockCommandOperation, + onStateChange: @escaping @MainActor () -> Void) async { + guard acceptsCommand(operation), let commandService else { + recordCommandEvent("command.queue_discarded", operation: operation, + fields: ["reason": "cancelled_or_task_context_changed"]) + if commandOperations[operation.command]?.requestID == operation.requestID, + commandOperations[operation.command]?.phase == .queued { commandOperations[operation.command] = nil } + onStateChange() + return + } + guard readAccessError == nil, !isStartingShooting, !isResummoning, + response?.currentPlane?.id == operation.planeID, + response?.currentPlane?.snNumber == operation.airportSN, + availableSafetyCommands.contains(operation.command) else { + commandOperations[operation.command]?.phase = .finished + commandOperations[operation.command]?.error = "设备状态或操作权限已变化,本次指令未发送" + recordCommandEvent("command.queue_discarded", operation: operation, + fields: ["reason": "latest_permission_or_plane_changed", "state": taskDiagnosticFields]) + onStateChange() + return + } + invalidatePendingRefresh() + commandOperations[operation.command]?.phase = .sending + recordCommandEvent("command.sending", operation: operation) + onStateChange() + defer { onStateChange() } do { - didSendCommand = true - let value = try await commandService.sendCommand(taskID: taskID, command: command) - guard acceptsCommand(requestGeneration) else { return } - guard value.orderFlightTaskID == taskID, value.command == command.rawValue else { - throw APIError.decodeFailed("安全指令回执与当前任务或指令不一致,请先核对任务状态") + let value = try await commandService.sendCommand(taskID: taskID, command: operation.command, + clientRequestID: operation.requestID) + try Task.checkCancellation() + guard acceptsCommand(operation) else { + recordCommandEvent("command.receipt_ignored", operation: operation, + fields: ["reason": "stale_task_context", "receipt_batch": DroneDockTaskTraceFields.value(value.executionBatch), + "receipt_command_id": DroneDockTaskTraceFields.value(value.commandID)]) + return + } + recordCommandEvent("command.receipt_received", operation: operation, fields: [ + "receipt_task_id": DroneDockTaskTraceFields.value(value.orderFlightTaskID), + "receipt_batch": DroneDockTaskTraceFields.value(value.executionBatch), + "receipt_version": DroneDockTaskTraceFields.value(value.stateVersion), + "receipt_command": DroneDockTaskTraceFields.value(value.command), + "receipt_command_id": DroneDockTaskTraceFields.value(value.commandID), + "receipt_client_request_id": DroneDockTaskTraceFields.value(value.clientRequestID), + "accepted": DroneDockTaskTraceFields.value(value.accepted), + "device_confirmed": DroneDockTaskTraceFields.value(value.deviceConfirmed), + "pending_command": DroneDockTaskTraceFields.progress(value.pendingCommand)]) + guard value.orderFlightTaskID == taskID, value.command == operation.command.rawValue, + value.executionBatch == operation.batch, + value.clientRequestID == nil || value.clientRequestID == operation.requestID, + value.flightControl == nil || value.flightControl?.executionBatch == operation.batch, + value.planeID == nil || value.planeID == operation.planeID, + value.airportSN == nil || value.airportSN == operation.airportSN, + value.stateVersion == nil || value.stateVersion! >= operation.submittedVersion else { + throw APIError.decodeFailed("安全指令回执与当前任务、批次、设备或请求不一致,请核对状态") + } + if value.accepted == false { throw APIError.serverCode(100099, "指令未受理,请核对任务状态后重试") } + guard value.accepted == true, let commandID = usable(value.commandID) else { + throw APIError.decodeFailed("指令回执缺少明确受理结果或 command_id,请核对状态") } commandResponse = value - DroneDockDiagnostics.event("command.receipt_accepted", taskID: taskID) - pendingAcceptedCommands.insert(command) - commandOutcomeUnknown = false - onStateChange() - guard acceptsCommand(requestGeneration) else { return } - await refreshSnapshot(allowWhileStarting: false, allowWhileCommand: true) + if let version = value.stateVersion { + minimumCommandSnapshotVersion = max(minimumCommandSnapshotVersion ?? 0, version) + } + // HTTP 严格按点击顺序提交;后受理的本地请求按合同取代之前的等待意图。 + for (command, old) in commandOperations where old.sequence < operation.sequence && old.isWaiting { + if let id = old.commandID { supersededCommandIDs.insert(id) } + commandOperations[command]?.phase = .finished + commandOperations[command]?.error = nil + recordCommandEvent("command.superseded", operation: old, + fields: ["superseded_by_client_request_id": operation.requestID, + "superseded_by_command_id": commandID]) + } + if let old = response?.flightControl?.pendingCommand, let id = old.commandID, + id != commandID { supersededCommandIDs.insert(id) } + commandOperations[operation.command]?.commandID = commandID + commandOperations[operation.command]?.minimumVersion = value.stateVersion + commandOperations[operation.command]?.phase = .pending + commandOperations[operation.command]?.error = nil + if let progress = value.pendingCommand { + guard progressMatches(progress, operation: commandOperations[operation.command]!) else { + throw APIError.decodeFailed("指令进度与本次请求不一致,请核对状态") + } + applyCommandProgress(progress, command: operation.command) + } else if value.deviceConfirmed == true { + commandOperations[operation.command]?.phase = .confirmed + supersededCommandIDs.insert(commandID) + } + reconcilePendingCommand() + recordCommandEvent("command.receipt_applied", operation: operation) } catch { - if error is DeviceCommandDebugBlockedError, commandGeneration == requestGeneration { didSendCommand = false } - guard acceptsCommand(requestGeneration) else { return } + guard acceptsCommand(operation, allowingCancellation: true) else { + recordCommandEvent("command.error_ignored", operation: operation, + fields: ["reason": "stale_task_context", "error": DroneDockDiagnostics.errorFields(error)]) + return + } if error is DeviceCommandDebugBlockedError { - commandErrorMessage = DeviceCommandDebugPolicy.blockedMessage + commandOperations[operation.command]?.phase = .finished + commandOperations[operation.command]?.error = DeviceCommandDebugPolicy.blockedMessage } else if case APIError.serverCode = error { - commandErrorMessage = error.localizedDescription + commandOperations[operation.command]?.phase = .finished + commandOperations[operation.command]?.error = error.localizedDescription } else { - markCommandUnknown(reason: error.localizedDescription) + commandOperations[operation.command]?.phase = .unknown + commandOperations[operation.command]?.error = "安全指令结果待核对,请刷新任务状态,勿重复提交" + } + recordCommandEvent("command.failed_or_unknown", operation: operation, + fields: ["error": DroneDockDiagnostics.errorFields(error)]) + } + } + + /// 离页取消在途请求;已发送的结果保持待核对,回前台仅通过快照核对。 + @MainActor + func invalidateCommand() { + recordTaskEvent("command.lifecycle_cancelled", fields: ["operation_count": commandOperations.count, + "transport_count": commandTasks.count]) + commandGeneration &+= 1 + for task in commandTasks.values { task.cancel() } + commandTasks.removeAll() + commandTransportTail = nil + for (command, operation) in commandOperations { + switch operation.phase { + case .queued: commandOperations[command] = nil + case .sending: + commandOperations[command]?.phase = .unknown + commandOperations[command]?.error = "安全指令结果待核对,请刷新任务状态,勿重复提交" + default: break } } } - /// 离页或后台取消控制流程;已发而未受理时保留未知结果锁,忽略迟到回执。 - @MainActor - func invalidateCommand() { - if isSendingCommand && didSendCommand && commandResponse == nil { markCommandUnknown() } - commandGeneration &+= 1 - isSendingCommand = false - activeCommand = nil - didSendCommand = false - } - - /// 本地模拟服务显式注入、当前任务明确失败且没有在途或未知操作时才可重召唤。 - /// 此门禁用于客户端模拟交互,不代表后端已提供真实重试许可。 + /// 任务失败或中断回巢后,设备空闲且后端明确允许,无在途或未知操作时才可重召唤。 var canResummon: Bool { resummonService != nil && context.canLoad && taskID > 0 && !identityInvalidated + && hasControlSnapshotIdentity && !isTaskAwaitingConfirmation && readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil && !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown - && !hasSubmittedResummon && pendingAcceptedCommands.isEmpty - && resolvedDisplayPhase().0 == .failed + && !hasSubmittedResummon && pendingCommand == nil + && !commandOperations.values.contains(where: { $0.isWaiting }) + && [.failed, .returned].contains(resolvedDisplayPhase().0) + && response?.restartGate?.canRestart == true + && flightControlState == .returned + && response?.currentPlane?.workStatus == 1 && (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID) && (response?.currentPlane?.id ?? 0) > 0 && !isResummonDeviceUnavailable @@ -425,6 +685,7 @@ final class DroneDockShootingTaskViewModel { /// 复用同一任务提交一次 restart=true;受理后只查询一次 shooting,不推断已经到达。 @MainActor func resummon(onStateChange: @escaping @MainActor () -> Void = {}) async { + recordTaskEvent("resummon.requested", fields: ["allowed": canResummon, "state": taskDiagnosticFields]) guard canResummon, let resummonService else { return } guard context.hasSameIdentity(as: currentContext()) else { identityInvalidated = true @@ -458,7 +719,7 @@ final class DroneDockShootingTaskViewModel { throw APIError.decodeFailed("重新召唤回执与当前任务或订单不一致,请先核对任务状态") } resummonResponse = value - DroneDockDiagnostics.event("resummon.receipt_accepted", taskID: taskID) + recordTaskEvent("resummon.receipt_accepted", fields: ["receipt": DroneDockTaskTraceFields.summon(value)]) hasSubmittedResummon = true resummonOutcomeUnknown = false awaitingResummonSnapshot = true @@ -466,7 +727,6 @@ final class DroneDockShootingTaskViewModel { startResponse = nil startErrorMessage = nil commandResponse = nil - commandErrorMessage = nil onStateChange() guard acceptsResummon(requestGeneration) else { return } await refreshSnapshot(allowWhileStarting: false, allowWhileResummoning: true) @@ -515,9 +775,22 @@ final class DroneDockShootingTaskViewModel { /// 录制完成与素材就绪分别保留;只由可信阶段触发完成提示,不修改后端任务状态。 var isRecordingFinished: Bool { - let phase = resolvedDisplayPhase().0 + guard !isInterruptedReturn else { return false } + let phase = resolvedBusinessPhase().0 + let tasks = [response?.task, response?.orderFlightTask].compactMap { $0 } + let statuses = tasks.compactMap(\.status) + let completedWhilePaused = response?.flightControl?.returnReason == "normal_complete" + && !statuses.contains(where: { [40, 50, 60].contains($0) }) + && statuses.contains(where: { [25, 30].contains($0) }) + && tasks.contains(where: { [24, 30, 40, 50].contains($0.waylineStatus ?? -1) }) return [.postShootUploading, .postShootUploadFailed, .completed].contains(phase) || (phase == .failed && hasMediaProcessingFailure) + || completedWhilePaused + } + + /// 已正常拍完或中断后确认回巢均停止本机接收;回巢不触发拍摄成功提示。 + var shouldStopLiveReception: Bool { + isRecordingFinished || resolvedDevicePhase().0 == .returned } /// 只有录制正常结束或素材就绪才弹出完成提示,素材处理失败只展示失败状态。 @@ -532,6 +805,9 @@ final class DroneDockShootingTaskViewModel { guard !waylines.contains(where: { [30, 40, 50].contains($0) }) else { return false } let flags = [response?.shootCompleteReturning, response?.ui?.shootCompleteReturning].compactMap { $0 } if flags.contains(false) { return false } + if let control = response?.flightControl { + return flightControlState == .returning && control.returnReason == "normal_complete" + } if flags.contains(true) || response?.ui?.waylineStage == "shoot_done_returning" { return true } // 旧回包仍保留明确的设备返航文案;新合同不再依赖只有忙闲的 work_status。 guard response?.ui?.waylineStage == nil else { return false } @@ -553,23 +829,15 @@ final class DroneDockShootingTaskViewModel { return Int(min(30, parts.seconds + (parts.attoseconds > 0 ? 1 : 0))) } - /// 根据可信阶段使用产品标题,其余保留服务端标题,不从 GET 成功推导到达或拍摄完成。 + /// 页面标题由本地显示阶段决定,服务端文案只保留在诊断数据中。 var statusTitle: String { if response == nil { if errorMessage != nil { return "任务状态读取失败" } if hasInitialTravelReceipt { return "无人机正在赶来" } if isLoading { return "正在获取任务状态" } } - if resolvedDisplayPhase().0 == .navigating { return "无人机正在赶来" } - if resolvedDisplayPhase().0 == .shooting { return "无人机正在拍摄中" } - if resolvedDisplayPhase().0 == .failed { return "任务执行失败" } - if resolvedDisplayPhase().0 == .postShootUploadFailed { return mediaFailureTitle } - if isTaskAwaitingConfirmation { return "任务待确认" } - if resolvedDisplayPhase().0 == .postShootUploading { - return "拍摄已完成" - } - return usable(response?.ui?.title) ?? usable(response?.task?.statusLabel) - ?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认" + let (phase, conflict) = resolvedDisplayPhase() + return presentationTitle(for: phase, conflict: conflict) } /// 拍摄阶段使用产品提示,其余保留服务端说明;操作结果未知时优先提示核对。 @@ -581,7 +849,16 @@ final class DroneDockShootingTaskViewModel { } if let resummonErrorMessage { return resummonErrorMessage } if awaitingResummonSnapshot { return "重新召唤请求已受理,请刷新核对任务状态" } - if let commandErrorMessage { return commandErrorMessage } + switch resolvedDisplayPhase().0 { + case .paused: + return response?.flightControl?.resumePhase == "returning" + ? "当前悬停待命。\n确认安全后,继续任务将恢复返航。" + : "当前悬停待命。\n确认安全后,可继续任务或立即返航。" + case .returning: return "本次拍摄已中断。请留意实时画面与无人机状态。" + case .returned: return "无人机已返回机巢,可在满足条件后重新召唤。" + case .unknown where isInterruptedReturn: return "暂无法确认无人机是否已返回机巢,请等待设备状态更新。" + default: break + } if resolvedDisplayPhase().0 == .failed { return failureMessage } if resolvedDisplayPhase().0 == .postShootUploadFailed { return mediaFailureMessage } if isTaskAwaitingConfirmation { return usable(response?.ui?.message) ?? "任务结果待确认,请刷新核对状态。" } @@ -589,6 +866,9 @@ final class DroneDockShootingTaskViewModel { if resolvedDisplayPhase().0 == .ready { if let startErrorMessage { return startErrorMessage } if hasSubmittedStart { return "开始拍摄请求已受理,请刷新确认任务状态" } + if response?.executeGate?.canExecute != true, let message = usable(response?.executeGate?.message) { + return message + } } if resolvedDisplayPhase().0 == .postShootUploading { let waylines = [response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus] @@ -600,7 +880,13 @@ final class DroneDockShootingTaskViewModel { return "本次拍摄已结束,可前往查看素材。\n" + note } if resolvedDisplayPhase().0 == .shooting { return "请关注现场及实时画面。\n请勿关闭本页或息屏。" } - return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—" + switch resolvedDisplayPhase().0 { + case .navigating: return "请留在拍摄点,等待无人机到达。" + case .ready: return "确认游客站位与取景后,即可开始拍摄。" + case .completed: return "素材已就绪,可前往素材库查看。" + case .unknown: return "暂无法确认任务状态,请刷新后重试。" + default: return usable(response?.executeGate?.message) ?? "请等待任务状态更新。" + } } /// 组合可信阶段与本轮可用动作,不从请求成功、执行中或指令列表推断飞行进度。 @@ -635,21 +921,26 @@ final class DroneDockShootingTaskViewModel { case .ready: action = .start actionTitle = isStartingShooting ? "正在提交开拍…" - : startErrorMessage == nil ? (usable(response?.executeGate?.primaryActionLabel) ?? "开始拍摄") : "重试开始拍摄" + : startErrorMessage == nil ? "开始拍摄" : "重试开始拍摄" enabled = canStartShooting - case .paused where response?.executeGate?.canExecute == true: + case .paused: action = .resume - actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "继续拍摄" + actionTitle = "继续任务" + enabled = canSendCommand(.resume) + case .returning: + action = .none + actionTitle = "拍摄已中断" enabled = false case .completed, .postShootUploading, .postShootUploadFailed: action = .materials actionTitle = "查看素材" enabled = true - case .failed where hasSubmittedResummon || resummonOutcomeUnknown: + case .failed where hasSubmittedResummon || resummonOutcomeUnknown, + .returned where hasSubmittedResummon || resummonOutcomeUnknown: action = .refresh actionTitle = "刷新状态" enabled = !identityInvalidated - case .failed: + case .failed, .returned: action = .retry actionTitle = isResummoning ? "正在重新召唤…" : "重新召唤无人机" enabled = canResummon @@ -660,20 +951,20 @@ final class DroneDockShootingTaskViewModel { } return DroneDockTaskPresentation(phase: phase, title: title, message: message, deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle, - isActionEnabled: enabled && readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh), - actionNote: phase == .failed && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil, + isActionEnabled: enabled && readAccessError == nil && !isStartingShooting && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh), + actionNote: [.failed, .returned].contains(phase) && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil, countdownSeconds: countdownRemainingSeconds) } /// 后端六项展示读数,不解析文案反推设备状态或数值单位。 var telemetry: DroneDockShootingTelemetry { - func text(_ key: String) -> String { response?.metrics.first(where: { $0.key == key })?.displayText ?? "—" } + func text(_ key: String) -> String { response == nil ? "—" : retainedMetrics[key]?.displayText ?? "—" } return DroneDockShootingTelemetry(batteryText: text("battery"), temperatureText: text("env_temp"), windText: text("wind_speed"), rainText: text("rainfall"), signalText: text("signal"), satelliteText: text("satellite")) } /// 无快照或后端标记缓存过期时使用非实时样式;已有读数仍保留展示。 - var isTelemetryStale: Bool { response == nil || response?.metricsStale == true } + var isTelemetryStale: Bool { response == nil || response?.metricsStale == true || isUsingRetainedMetrics } /// 完整服务端 data,供页面展示和联调查看。 var dataJSON: String? { response?.dataJSON } @@ -701,14 +992,15 @@ final class DroneDockShootingTaskViewModel { } @MainActor - private func acceptsCommand(_ requestGeneration: Int) -> Bool { - guard commandGeneration == requestGeneration else { return false } + private func acceptsCommand(_ operation: DroneDockCommandOperation, allowingCancellation: Bool = false) -> Bool { + guard commandGeneration == operation.generation, response?.executionBatch == operation.batch, + commandOperations[operation.command]?.requestID == operation.requestID else { return false } guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else { identityInvalidated = true invalidate() return false } - return !Task.isCancelled + return allowingCancellation || !Task.isCancelled } @MainActor @@ -723,9 +1015,9 @@ final class DroneDockShootingTaskViewModel { } private func markResummonUnknown(reason: String? = nil) { - DroneDockDiagnostics.event("resummon.outcome_unknown", taskID: taskID) resummonOutcomeUnknown = true resummonErrorMessage = (reason.map { "\($0)。" } ?? "") + "重新召唤结果待核对,请刷新任务状态,勿重复提交" + recordTaskEvent("resummon.outcome_unknown") } /// shoot 顶层 task_id 是实际航线任务 ID;只核对明确的订单任务身份,不混淆两种任务。 @@ -741,16 +1033,10 @@ final class DroneDockShootingTaskViewModel { && (identity.planeID == nil || identity.planeID == response?.currentPlane?.id) } - private func markCommandUnknown(reason: String? = nil) { - DroneDockDiagnostics.event("command.outcome_unknown", taskID: taskID) - commandOutcomeUnknown = true - commandErrorMessage = (reason.map { "\($0)。" } ?? "") + "安全指令结果待核对,请刷新任务状态,勿重复提交" - } - private func markStartUnknown(reason: String? = nil) { - DroneDockDiagnostics.event("start.outcome_unknown", taskID: taskID) startOutcomeUnknown = true startErrorMessage = (reason.map { "\($0)。" } ?? "") + "开始拍摄结果待核对,请刷新任务状态,勿重复提交" + recordTaskEvent("start.outcome_unknown") } private func matchesIdentity(_ value: DroneDockShootingResponse) -> Bool { @@ -764,8 +1050,184 @@ final class DroneDockShootingTaskViewModel { && scenicIDs.allSatisfy { $0 == context.scenicID } } + /// 手动或保护返航独立于拍摄结果,不能被普通失败摘要隐藏,也不升级为成功。 + private var isInterruptedReturn: Bool { + ["manual", "abnormal"].contains(response?.flightControl?.returnReason ?? "") + || response?.orderFlightTask?.resultCode == "return_home" + || response?.task?.resultCode == "return_home" + || response?.ui?.phase == "returning_home" + } + + /// 缺任务身份、版本或未知任务枚举的快照可只读展示,不能作为控制指令的授权依据。 + private var hasControlSnapshotIdentity: Bool { + guard let response, (response.stateVersion ?? 0) > 0, (response.executionBatch ?? 0) > 0, + response.orderFlightTaskID == taskID || response.orderFlightTask?.id == taskID || response.task?.id == taskID else { return false } + return matchesIdentity(response) + } + + /// 开拍仍要求已知任务业务态;紧急控制只依赖有效设备身份和逐项飞控许可。 + private var hasKnownShootingTaskState: Bool { + let statuses = [response?.task?.status, response?.orderFlightTask?.status].compactMap { $0 } + return !statuses.isEmpty && statuses.allSatisfy { [10, 20, 25, 30, 40, 50, 60].contains($0) } + } + + private func resolvedDisplayPhase() -> (DroneDockTaskDisplayPhase, Bool) { resolvedDevicePhase() } + + /// 先校验业务冲突,再用同批次设备状态覆盖暂停和中断返航;正常录制完成单独保留。 + private func resolvedDevicePhase() -> (DroneDockTaskDisplayPhase, Bool) { + let business = resolvedBusinessPhase() + guard let response else { return business } + let tasks = [response.task, response.orderFlightTask].compactMap { $0 } + let statuses = Set(tasks.compactMap(\.status)) + if statuses.contains(50) || statuses.contains(60) || tasks.contains(where: { $0.waylineStatus == 90 }) { + return (.blocked, false) + } + guard let control = response.flightControl else { + return isInterruptedReturn ? (.unknown, false) : business + } + if statuses.count > 1 { return (.unknown, true) } + if isInterruptedReturn && control.returnReason == "normal_complete" { return (.unknown, true) } + let recorded = [.postShootUploading, .postShootUploadFailed, .completed].contains(business.0) + && !isInterruptedReturn && !business.1 + switch flightControlState { + case .starting: + return business.0 == .navigating && !business.1 ? business : (.unknown, true) + case .unknown: + // 飞控暂缺不抹掉已明确的业务进度,操作许可仍需单独的可信飞控数据。 + return recorded || [.navigating, .ready, .shooting].contains(business.0) ? business : (.unknown, false) + case .returned: + if isInterruptedReturn { + guard !statuses.contains(30), !statuses.contains(25) else { return (.unknown, true) } + return (.returned, false) + } + if recorded || business.0 == .failed { return business } + return (.unknown, true) + case .returning: + if isInterruptedReturn { + guard !statuses.contains(30), !statuses.contains(25) else { return (.unknown, true) } + return (.returning, false) + } + if recorded && control.returnReason == "normal_complete" { return business } + return (.unknown, true) + case .paused: + guard ["going_to_spot", "arrived_pending_start", "shooting", "returning"].contains(control.resumePhase ?? "") else { + return (.unknown, false) + } + if isInterruptedReturn { + guard control.resumePhase == "returning", !statuses.contains(30), !statuses.contains(25) else { + return (.unknown, true) + } + return (.paused, false) + } + if isRecordingFinished && control.returnReason == "normal_complete" && control.resumePhase == "returning" { + return (.paused, false) + } + guard !business.1, [.navigating, .ready, .shooting, .paused, .blocked, .failed].contains(business.0) else { return business } + return (.paused, false) + case .executing: + if isInterruptedReturn { return (.unknown, true) } + // 执行态不是到达证据,正常业务进度仍由 ui.phase 和开拍门禁共同决定。 + return business + } + } + + /// 重进页也展示服务端当前指令的等待,仅识别已知且有唯一标识的动作。 + private var remotePendingCommand: DroneDockSafetyCommand? { + guard let control = response?.flightControl, control.executionBatch == response?.executionBatch, + let progress = control.pendingCommand, progress.status == "pending", + let id = usable(progress.commandID), !supersededCommandIDs.contains(id), + let command = progress.command.flatMap(DroneDockSafetyCommand.init(rawValue:)) else { return nil } + return command + } + + private func progressMatches(_ progress: DroneDockCommandProgress, operation: DroneDockCommandOperation) -> Bool { + guard progress.command == operation.command.rawValue, + progress.clientRequestID == nil || progress.clientRequestID == operation.requestID, + progress.commandID == nil || operation.commandID == nil || progress.commandID == operation.commandID else { return false } + return progress.clientRequestID == operation.requestID || (operation.commandID != nil && progress.commandID == operation.commandID) + } + + private func applyCommandProgress(_ progress: DroneDockCommandProgress, command: DroneDockSafetyCommand) { + let previousPhase = commandOperations[command]?.phase + defer { + if let operation = commandOperations[command], previousPhase != operation.phase { + recordCommandEvent("command.progress_changed", operation: operation, + fields: ["previous_phase": previousPhase.map { String(describing: $0) } ?? "none", + "server_progress": DroneDockTaskTraceFields.progress(progress)]) + } + } + switch progress.status { + case "pending": + if commandOperations[command]?.phase != .confirmed { commandOperations[command]?.phase = .pending } + case "succeeded": + if let id = progress.commandID { supersededCommandIDs.insert(id) } + commandOperations[command]?.phase = .confirmed + commandOperations[command]?.error = nil + case "superseded": + if let id = progress.commandID { supersededCommandIDs.insert(id) } + commandOperations[command]?.phase = .finished + commandOperations[command]?.error = nil + case "failed": + if let id = progress.commandID { supersededCommandIDs.insert(id) } + commandOperations[command]?.phase = .finished + commandOperations[command]?.error = usable(progress.message) ?? "安全指令执行失败,请核对设备状态" + default: break + } + } + + /// 匹配本次 command_id/幂等键的进度优先;无进度样例仅由更新的明确设备状态核对。 + private func reconcilePendingCommand() { + guard let response, let batch = response.executionBatch, let version = response.stateVersion else { return } + for (command, operation) in commandOperations where operation.batch == batch && operation.isWaiting { + if let progress = response.flightControl?.pendingCommand, progressMatches(progress, operation: operation) { + commandOperations[command]?.commandID = progress.commandID ?? operation.commandID + applyCommandProgress(progress, command: command) + if commandOperations[command]?.phase != .confirmed { continue } + } + guard version > operation.submittedVersion, version >= (operation.minimumVersion ?? 0), + commandOperations[command]?.commandID != nil, + response.flightControl?.pendingCommand == nil || commandOperations[command]?.phase == .confirmed else { continue } + let confirmed: Bool + switch command { + case .pause: confirmed = flightControlState == .paused + case .resume: + confirmed = operation.resumePhase == "returning" ? flightControlState == .returning + : flightControlState == .executing && response.ui?.phase == operation.resumePhase + case .returnHome: confirmed = flightControlState == .returned + case .cancelReturn: confirmed = false + } + if confirmed || flightControlState == .returned { + commandOperations[command]?.phase = .finished + recordCommandEvent("command.snapshot_confirmed", operation: operation, + fields: ["confirmed_flight_state": flightControlState.rawValue, + "confirmed_ui_phase": DroneDockTaskTraceFields.value(response.ui?.phase)]) + } + } + } + + /// 指令日志同时记录提交时与当前批次,便于识别旧回执、被替代动作和按钮等待原因。 + private func recordCommandEvent(_ event: String, operation: DroneDockCommandOperation, + fields: [String: Any] = [:]) { + let current = commandOperations[operation.command] + let summary: [String: Any] = ["command": operation.command.rawValue, + "client_request_id": operation.requestID, "command_id": DroneDockTaskTraceFields.value(current?.commandID ?? operation.commandID), + "submitted_batch": operation.batch, "submitted_version": operation.submittedVersion, + "command_sequence": operation.sequence, "submitted_plane_id": operation.planeID, + "submitted_airport_sn": DroneDockTaskTraceFields.value(operation.airportSN), + "operation_phase": current.map { String(describing: $0.phase) } ?? "discarded", + "button_loading": isCommandLoading(operation.command), + "button_allowed": canSendCommand(operation.command), + "command_error": DroneDockTaskTraceFields.value(current?.error)] + recordTaskEvent(event, fields: summary.merging(fields) { _, new in new }) + } + + private func clearPendingCommand() { + commandOperations.removeAll() + supersededCommandIDs.removeAll() + } + /// 按任务终态、明确 UI 阶段与航线失败判断,不把机巢忙闲或订单执行中当作拍摄进度。 - private func resolvedDisplayPhase() -> (DroneDockTaskDisplayPhase, Bool) { + private func resolvedBusinessPhase() -> (DroneDockTaskDisplayPhase, Bool) { guard let response else { return (.unknown, false) } let tasks = [response.task, response.orderFlightTask].compactMap { $0 } let statuses = Set(tasks.compactMap(\.status)) @@ -784,7 +1246,7 @@ final class DroneDockShootingTaskViewModel { "navigating": .navigating, "arrived_pending_start": .ready, "shooting": .shooting, "post_shoot_uploading": .postShootUploading, "post_shoot_upload_failed": .postShootUploadFailed, - "paused": .paused, "returning": .returning, "completed": .completed, "failed": .failed, "blocked": .blocked + "manual_paused": .paused, "returning_home": .returning, "completed": .completed, "failed": .failed, "blocked": .blocked ] let phase = rawPhase.flatMap { known[$0] } if rawPhase != nil && phase == nil { return (.unknown, false) } @@ -797,49 +1259,35 @@ final class DroneDockShootingTaskViewModel { if phase == .completed { return statuses.isEmpty ? (.completed, false) : (.unknown, true) } - if phase == .ready { - guard let allowed = response.executeGate?.canExecute else { return (.unknown, false) } - if !allowed { return (.blocked, false) } + if phase == .ready, response.executeGate?.canExecute == true { if let action = usable(response.executeGate?.primaryAction), action != "start_shoot" { return (.unknown, true) } } - if phase == .paused, response.executeGate?.canExecute == true, - response.executeGate?.primaryAction == "blocked" { return (.unknown, true) } return (phase ?? .unknown, false) } private func presentationTitle(for phase: DroneDockTaskDisplayPhase, conflict: Bool) -> String { if conflict { return "状态待确认" } - let tasks = [response?.task, response?.orderFlightTask].compactMap { $0 } - if phase == .failed { return "任务执行失败" } - if phase == .postShootUploadFailed { return mediaFailureTitle } - if phase == .blocked, isTaskAwaitingConfirmation { return "任务待确认" } - if phase == .blocked, let cancelled = tasks.first(where: { $0.status == 50 }) { - return usable(cancelled.statusLabel) ?? "任务已取消" - } - if phase == .blocked, tasks.contains(where: { $0.waylineStatus == 90 }) { return "任务已取消" } - if phase == .blocked, response?.ui?.phase == "arrived_pending_start" { return "暂不可开始拍摄" } - if phase == .postShootUploading { return "拍摄已完成" } - if phase == .completed { - return usable(response?.ui?.phase == "completed" ? response?.ui?.title : nil) - ?? tasks.first(where: { $0.status == 30 }).flatMap { usable($0.statusLabel) } ?? "拍摄已完成" - } - if phase == .unknown { return "状态待确认" } - if phase == .navigating { return "无人机正在赶来" } - if phase == .shooting { return "无人机正在拍摄中" } - if let title = usable(response?.ui?.title) { return title } switch phase { + case .loading: return "正在获取任务状态" + case .readError: return "任务状态读取失败" case .navigating: return "无人机正在赶来" case .ready: return "无人机已到达" - case .shooting: return "正在拍摄" - case .postShootUploading: return "拍摄已完成" + case .shooting: return "无人机正在拍摄中" + case .postShootUploading, .completed: return "拍摄已完成" case .postShootUploadFailed: return mediaFailureTitle - case .paused: return "拍摄已暂停" + case .paused: return "无人机已暂停" case .returning: return "无人机正在返航" + case .returned: return "本次拍摄已中断" case .failed: return "任务执行失败" - case .blocked: return "当前任务暂不可执行" - default: return "状态待确认" + case .blocked: + if isTaskAwaitingConfirmation { return "任务待确认" } + let tasks = [response?.task, response?.orderFlightTask].compactMap { $0 } + if tasks.contains(where: { $0.status == 50 || $0.waylineStatus == 90 }) { return "任务已取消" } + if response?.ui?.phase == "arrived_pending_start" { return "暂不可开始拍摄" } + return "当前任务暂不可执行" + case .unknown: return "状态待确认" } } @@ -862,7 +1310,6 @@ final class DroneDockShootingTaskViewModel { } private var mediaFailureTitle: String { - if response?.ui?.phase == "post_shoot_upload_failed", let title = usable(response?.ui?.title) { return title } return [response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus].contains(49) ? "素材渲染失败" : "素材上传失败" } @@ -884,12 +1331,10 @@ final class DroneDockShootingTaskViewModel { } } - /// 明确离线或返航时保持禁用,不从普通空闲文案推导后端重试许可。 + /// 设备断连、离线或忙碌时禁用重召唤,不从显示文案推导设备可用性。 private var isResummonDeviceUnavailable: Bool { let plane = response?.currentPlane return response?.planeStatus?.connected == false || isResummonDeviceOffline || plane?.workStatus == 2 - || ["返航中", "正在返航"].contains(usable(plane?.workStatusLabel) ?? "") - || response?.ui?.phase == "returning" } /// 正式入口未注入操作服务时说明当前限制;模拟页保留实际设备不可用原因。 @@ -902,7 +1347,8 @@ final class DroneDockShootingTaskViewModel { if let status = usable(plane?.workStatusLabel), ["返航中", "正在返航"].contains(status) { return "无人机返航中,暂不可召唤" } - return "暂不可重新召唤,请返回准备页确认设备状态" + if flightControlState != .returned { return "等待设备确认已返回机巢后再重新召唤" } + return usable(response?.restartGate?.message) ?? "暂不可重新召唤,请返回准备页确认设备状态" } } diff --git a/suixinkan/UI/DroneDock/DroneDockMaterialsViewController.swift b/suixinkan/UI/DroneDock/DroneDockMaterialsViewController.swift index a8cbf19..73139ff 100644 --- a/suixinkan/UI/DroneDock/DroneDockMaterialsViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockMaterialsViewController.swift @@ -16,8 +16,6 @@ final class DroneDockMaterialsViewController: BaseViewController { private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController private let downloadSourceDescription: String? private let downloadIsSimulated: Bool - private let taskControllerFactory: (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController - private var taskButton: UIBarButtonItem? /// 元数据与媒体分区独立,任务没有素材时也保留其状态。 private enum Section: Hashable { case order, filters, summary, task(Int), media(Int), message } @@ -45,16 +43,12 @@ final class DroneDockMaterialsViewController: BaseViewController { mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)? = nil, downloadViewModel: DroneDockMaterialDownloadViewModel? = nil, downloadSourceDescription: String? = nil, - downloadIsSimulated: Bool = false, - taskControllerFactory: ((Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) { + downloadIsSimulated: Bool = false) { self.viewModel = viewModel self.downloadViewModel = downloadViewModel ?? DroneDockMaterialDownloadViewModel( isContextValid: { [weak viewModel] in viewModel?.acceptsDownloadContext() == true }) self.downloadSourceDescription = downloadSourceDescription self.downloadIsSimulated = downloadIsSimulated - self.taskControllerFactory = taskControllerFactory ?? { id, order, context in - DroneDockShootingTaskEntry.makeController(taskID: id, order: order, context: context) - } self.thumbnailProvider = thumbnailProvider self.mediaPreviewControllerFactory = mediaPreviewControllerFactory self.deliveryControllerFactory = deliveryControllerFactory ?? DroneDockDeliveryEntry.makeController @@ -73,11 +67,7 @@ final class DroneDockMaterialsViewController: BaseViewController { let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain, target: self, action: #selector(refreshTapped)) refresh.accessibilityLabel = "刷新素材状态" refresh.accessibilityIdentifier = "drone.materials.remote.refresh" - let tasks = UIBarButtonItem(title: "查看任务", style: .plain, target: self, action: #selector(viewTasksTapped)) - tasks.accessibilityIdentifier = "drone.materials.remote.viewTasks" - tasks.isEnabled = false - taskButton = tasks - navigationItem.rightBarButtonItems = [refresh, tasks] + navigationItem.rightBarButtonItems = [refresh] } override func setupUI() { @@ -168,8 +158,8 @@ final class DroneDockMaterialsViewController: BaseViewController { return cell case .filter(let id): let cell = collection.dequeueReusableCell(withReuseIdentifier: "filter", for: path) as! DroneMaterialFilterCell - let title = id.flatMap { id in self.viewModel.spots.first { $0.id == id } }.map { Self.usable($0.name, fallback: "点位 \($0.id)") } ?? "全部点位" - cell.apply(title: title, id: id.map(String.init), selected: id == self.displayedSpotID, locked: self.viewModel.detail == nil || self.selectionLocked) + cell.apply(title: self.filterTitle(for: id), id: id.map(String.init), selected: id == self.displayedSpotID, + locked: self.viewModel.detail == nil || self.selectionLocked, wrapsTitle: true) return cell case .task(let taskID): let cell = collection.dequeueReusableCell(withReuseIdentifier: "record", for: path) as! DroneDockMaterialRecordCell @@ -228,8 +218,20 @@ final class DroneDockMaterialsViewController: BaseViewController { guard sections.indices.contains(index) else { return nil } switch sections[index] { case .filters: - let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1))) - let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .estimated(104), heightDimension: .absolute(36)), subitems: [item]) + let maximumWidth = min(200, max(1, environment.container.effectiveContentSize.width - 32)) + let sizes = dataSource.snapshot().itemIdentifiers(inSection: .filters).compactMap { item -> CGSize? in + guard case .filter(let id) = item else { return nil } + return DroneMaterialFilterCell.wrappedSize(title: self.filterTitle(for: id), maximumWidth: maximumWidth) + } + let width = sizes.reduce(0) { $0 + $1.width } + CGFloat(max(0, sizes.count - 1)) * 8 + let height = sizes.map(\.height).max() ?? 40 + let group = NSCollectionLayoutGroup.custom(layoutSize: .init(widthDimension: .absolute(max(1, width)), heightDimension: .absolute(height))) { _ in + var x: CGFloat = 0 + return sizes.map { size in + defer { x += size.width + 8 } + return NSCollectionLayoutGroupCustomItem(frame: CGRect(x: x, y: 0, width: size.width, height: size.height)) + } + } let section = NSCollectionLayoutSection(group: group) section.orthogonalScrollingBehavior = .continuous section.interGroupSpacing = 8 @@ -267,7 +269,6 @@ final class DroneDockMaterialsViewController: BaseViewController { private func applySnapshot(animated: Bool) { guard dataSource != nil else { return } - taskButton?.isEnabled = operation == nil && !selectionLocked && viewModel.canViewRecordedTasks var snapshot = NSDiffableDataSourceSnapshot() if viewModel.detail != nil { snapshot.appendSections([.order, .filters]) @@ -375,7 +376,6 @@ final class DroneDockMaterialsViewController: BaseViewController { private func updateDownloadFooter() { navigationItem.rightBarButtonItem?.isEnabled = !selectionLocked - taskButton?.isEnabled = operation == nil && !selectionLocked && viewModel.canViewRecordedTasks let model = downloadViewModel let identifier = "drone.materials.remote.download" switch model.phase { @@ -401,31 +401,6 @@ final class DroneDockMaterialsViewController: BaseViewController { } } - /// 从张工已返回的任务中选择并进入状态页,不创建新任务或调用召唤接口。 - @objc private func viewTasksTapped() { - guard operation == nil, !selectionLocked, viewModel.canViewRecordedTasks, - viewModel.acceptsDownloadContext(), presentedViewController == nil else { return } - if let task = viewModel.tasks.first, viewModel.tasks.count == 1 { - openRecordedTask(id: task.id) - return - } - let sheet = UIAlertController(title: "选择拍摄任务", message: nil, preferredStyle: .actionSheet) - for task in viewModel.tasks { - let spot = task.spotName.isEmpty ? "拍摄任务" : task.spotName - let sequence = task.sequence.map { "第\($0)次拍摄" } ?? "拍摄记录" - let title = "\(spot) · \(sequence)" + (task.createdAt.map { " · \($0)" } ?? "") - sheet.addAction(UIAlertAction(title: title, style: .default) { [weak self] _ in self?.openRecordedTask(id: task.id) }) - } - sheet.addAction(UIAlertAction(title: "取消", style: .cancel)) - present(sheet, animated: true) - } - - private func openRecordedTask(id: Int) { - guard operation == nil, !selectionLocked, viewModel.taskForViewing(id: id) != nil, - navigationController?.topViewController === self else { return } - navigationController?.pushViewController(taskControllerFactory(id, viewModel.order, viewModel.context), animated: true) - } - private func previewFile(taskID: Int, fileID: Int) { guard operation == nil, let file = task(taskID)?.materials.first(where: { $0.id == fileID }), let url = file.previewURL else { return } preview(url: url, isVideo: file.fileType == 2, title: file.fileName ?? "原素材") @@ -447,6 +422,11 @@ final class DroneDockMaterialsViewController: BaseViewController { DroneDockHomeMetric.usableText(value) ?? fallback } + private func filterTitle(for id: Int?) -> String { + id.flatMap { id in viewModel.spots.first { $0.id == id } } + .map { Self.usable($0.name, fallback: "点位 \($0.id)") } ?? "全部点位" + } + } diff --git a/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift b/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift index 617860f..7ad0568 100644 --- a/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift @@ -140,12 +140,14 @@ final class DroneDockRemotePreparationViewController: BaseViewController { super.viewWillAppear(animated) isPageVisible = true isApplicationActive = UIApplication.shared.applicationState == .active + logPreparationEvent("preparation.page.appeared") refreshPreparation() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) isPageVisible = false + logPreparationEvent("preparation.page.disappeared", fields: ["moving_from_parent": isMovingFromParent]) stopPlaneStatusPolling() refreshTask?.cancel() creationTask?.cancel() @@ -183,7 +185,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController { /// 首次创建并召唤;成功后进入原任务,再次查看不经过创建或召唤接口。 private func createSelectedTask() { - DroneDockDiagnostics.event("preparation.confirm_tapped", taskID: viewModel.createdTask?.taskID, fields: [ + logPreparationEvent("preparation.confirm_tapped", fields: [ "order_number": viewModel.order.orderNumber as Any? ?? NSNull(), "scenic_id": viewModel.context.scenicID, "spot_id": viewModel.selectedSpotID as Any? ?? NSNull(), @@ -191,12 +193,18 @@ final class DroneDockRemotePreparationViewController: BaseViewController { "enabled": viewModel.isPrimaryActionEnabled, "blocked": viewModel.isTaskSubmissionBlocked ]) - guard !isRefreshing, !isStartingCreation else { return } + guard !isRefreshing, !isStartingCreation else { + logPreparationEvent("preparation.confirm_rejected", fields: ["reason": "refresh_or_submission_in_progress"]) + return + } if viewModel.canOpenShootingTask { _ = openShootingTask(automatically: false) return } - guard viewModel.isPrimaryActionEnabled else { return } + guard viewModel.isPrimaryActionEnabled else { + logPreparationEvent("preparation.confirm_rejected", fields: ["reason": "primary_action_disabled"]) + return + } isStartingCreation = true applySnapshot(animated: false) creationTask = Task { @MainActor [weak self] in @@ -204,6 +212,10 @@ final class DroneDockRemotePreparationViewController: BaseViewController { await self.viewModel.prepareAndSummon { [weak self] in self?.applySnapshot(animated: false) } guard !Task.isCancelled else { return } self.isStartingCreation = false + self.logPreparationEvent("preparation.submission_presented", fields: [ + "has_summon_receipt": self.viewModel.shootResponse != nil, + "can_open_task": self.viewModel.canOpenShootingTask, + "error_message": self.viewModel.errorMessage as Any? ?? NSNull()]) if self.openShootingTask(automatically: true) { return } self.applySnapshot(animated: true) { [weak self] in guard let self, @@ -230,11 +242,23 @@ final class DroneDockRemotePreparationViewController: BaseViewController { guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask, let taskID = viewModel.createdTask?.taskID, let navigationController, navigationController.topViewController === self, - !automatically || (viewModel.shootResponse != nil && automaticallyOpenedTaskID != taskID) else { return false } - DroneDockDiagnostics.event("navigation.open_task", taskID: taskID) + !automatically || (viewModel.shootResponse != nil && automaticallyOpenedTaskID != taskID) else { + logPreparationEvent("navigation.open_task_rejected", fields: ["automatic": automatically, + "can_open_task": viewModel.canOpenShootingTask, + "is_navigation_top": navigationController?.topViewController === self, + "has_summon_receipt": viewModel.shootResponse != nil, + "previously_opened_task_id": automaticallyOpenedTaskID as Any? ?? NSNull()]) + return false + } automaticallyOpenedTaskID = taskID let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context) let stack = navigationController.viewControllers + let fields: [String: Any] = ["automatic": automatically, "task_id": taskID, + "preparation_session_id": viewModel.diagnosticSessionID, + "replaces_preparation": stack.count > 1, + "navigation_stack_before": stack.map { String(describing: type(of: $0)) }] + logPreparationEvent("navigation.open_task", fields: fields) + (controller as? DroneDockShootingTaskViewController)?.recordNavigationEntry(source: "preparation", fields: fields) if stack.count > 1 { navigationController.setViewControllers(Array(stack.dropLast()) + [controller], animated: true) } else { @@ -278,6 +302,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController { @objc private func applicationWillResignActive() { isApplicationActive = false + logPreparationEvent("preparation.app.inactive") stopPlaneStatusPolling() footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation, isLocalSimulation: simulationRecordsProvider != nil) @@ -285,9 +310,23 @@ final class DroneDockRemotePreparationViewController: BaseViewController { @objc private func applicationDidBecomeActive() { isApplicationActive = true + logPreparationEvent("preparation.app.active") startPlaneStatusPolling() } + /// 准备页 UI 事件沿用业务会话,可与后续任务页的导航记录关联。 + private func logPreparationEvent(_ name: String, fields: [String: Any] = [:]) { + var fields = fields + fields["source"] = simulationRecordsProvider == nil ? "preparation_page" : "local_simulation" + fields["task_id"] = viewModel.createdTask?.taskID as Any? ?? NSNull() + fields["page_visible"] = isPageVisible + fields["app_active"] = isApplicationActive + fields["refreshing"] = isRefreshing + fields["submitting"] = isStartingCreation + fields["debug_flight_blocked"] = DeviceCommandDebugPolicy.blocksFlightRequests + viewModel.recordPreparationEvent(name, fields: fields) + } + private func configureDataSource() { dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { [weak self] list, path, item in guard let self else { return nil } diff --git a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift index e764b80..d29ff62 100644 --- a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift @@ -29,7 +29,9 @@ final class DroneDockShootingTaskViewController: BaseViewController { private var pollGeneration = 0 private var refreshTask: Task? private var startTask: Task? - private var commandTask: Task? + private var commandTasks: [UUID: Task] = [:] + private var commandAttemptIDs: [DroneDockSafetyCommand: UUID] = [:] + private var submittingCommands: Set = [] private var resummonTask: Task? private var liveTask: Task? private var liveParameterTask: Task? @@ -40,16 +42,19 @@ final class DroneDockShootingTaskViewController: BaseViewController { private var isApplicationActive = false private var isRequesting = false private var isStartingAction = false - private var isSendingSafetyAction = false + private var isSendingSafetyAction: Bool { !submittingCommands.isEmpty } private var isResummoningAction = false private var wasRealtimeLive = false private let coverURL: URL? - private var finishedExecutions: Set = [] + private var stoppedLiveExecutionTitles: [String: String] = [:] private var displayedCompletionIDs: Set = [] private var completionNotice: DroneDockRecordingCompletionView? private let countdownDelay: @Sendable () async throws -> Void private var countdownTask: Task? private var countdownGeneration = 0 + private var diagnosticStateData: [String: Data] = [:] + private var countdownDiagnosticKey: String? + private var entrySource = "existing_task_or_direct" /// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。 init(viewModel: DroneDockShootingTaskViewModel, @@ -83,7 +88,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { hidesBottomBarWhenPushed = true realtimeSession?.onSnapshot = { [weak self] snapshot in guard let self, self.isPageVisible, self.isApplicationActive else { return .invalid } - let result = self.viewModel.applyTaskSnapshot(snapshot) + let result = self.viewModel.applyTaskSnapshot(snapshot, source: .webSocket) self.applySnapshot() return result } @@ -95,11 +100,17 @@ final class DroneDockShootingTaskViewController: BaseViewController { @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + /// 仅记录导航来源与上游诊断会话,不改变任务身份、页面加载或设备操作。 + func recordNavigationEntry(source: String, fields: [String: Any] = [:]) { + entrySource = source + logEvent("navigation.task_entry", fields: fields) + } + deinit { pollTask?.cancel() refreshTask?.cancel() startTask?.cancel() - commandTask?.cancel() + commandTasks.values.forEach { $0.cancel() } resummonTask?.cancel() liveTask?.cancel() liveParameterTask?.cancel() @@ -192,6 +203,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { /// 只按设备可用尺寸调整固定区域,数据、错误和加载状态不会改变它们的高度。 override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() + defer { recordRenderedState() } let availableHeight = view.bounds.height - view.safeAreaInsets.top - view.safeAreaInsets.bottom let compact = availableHeight < 680 let inset = view.safeAreaInsets.bottom @@ -211,8 +223,11 @@ final class DroneDockShootingTaskViewController: BaseViewController { statusView.onDetails = { [weak self] in self?.showStatusDetails() } safetyView.onCommand = { [weak self] command in self?.safetyCommandTriggered(command) } feedPlaceholder.onRequest = { [weak self] in self?.refreshLiveIfVisible() } + feedPlaceholder.onDiagnosticEvent = { [weak self] event, fields in self?.logEvent(event, fields: fields) } feedPlaceholder.onPlaybackEvent = { [weak self] event, sessionID in - guard let self, self.isPageVisible, self.isApplicationActive else { return } + guard let self else { return } + self.recordPlaybackEvent(event, sessionID: sessionID) + guard self.isPageVisible, self.isApplicationActive else { return } self.liveViewModel.receivePlaybackEvent(event, sessionID: sessionID) if self.liveViewModel.playbackSessionID == nil { self.liveParameterTask?.cancel() @@ -230,8 +245,8 @@ final class DroneDockShootingTaskViewController: BaseViewController { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) isPageVisible = true - logEvent("page.appeared") isApplicationActive = UIApplication.shared.applicationState == .active + logEvent("page.appeared", fields: ["navigation_stack": navigationController?.viewControllers.map { String(describing: type(of: $0)) } ?? []]) refreshTaskIfVisible() refreshLiveIfVisible(automatically: true) } @@ -241,25 +256,30 @@ final class DroneDockShootingTaskViewController: BaseViewController { super.viewWillDisappear(animated) isPageVisible = false dismissCompletionNotice() - logEvent("page.disappeared") + logEvent("page.disappeared", fields: ["moving_from_parent": isMovingFromParent, "being_dismissed": isBeingDismissed]) cancelRefresh() stopLive() } private func applySnapshot() { guard isViewLoaded else { return } - if viewModel.isRecordingFinished { finishedExecutions.insert(viewModel.recordingExecutionID) } - let recordingFinished = finishedExecutions.contains(viewModel.recordingExecutionID) + if viewModel.shouldStopLiveReception { + stoppedLiveExecutionTitles[viewModel.recordingExecutionID] = viewModel.isRecordingFinished + ? "拍摄已完成" : "无人机已返回机巢" + } + let stoppedLiveTitle = stoppedLiveExecutionTitles[viewModel.recordingExecutionID] + let liveReceptionEnded = stoppedLiveTitle != nil if !viewModel.shouldPresentRecordingCompletion { dismissCompletionNotice() } - if recordingFinished, liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil { + if liveReceptionEnded, liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil { stopLive() } - feedPlaceholder.showRecordingCover(recordingFinished, url: coverURL) + feedPlaceholder.showRecordingCover(liveReceptionEnded, url: coverURL, + title: stoppedLiveTitle ?? "拍摄已完成") let loading = (viewModel.response == nil && (isRequesting || viewModel.isLoading)) || isStartingAction || viewModel.isStartingShooting - || isSendingSafetyAction || viewModel.isSendingCommand || isResummoningAction || viewModel.isResummoning + || isResummoningAction || viewModel.isResummoning feedPlaceholder.apply(liveViewModel) - feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive && !recordingFinished) + feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive && !liveReceptionEnded) taskTitleLabel.text = viewModel.title subtitleLabel.text = viewModel.subtitle + (viewModel.response?.metricsStale == true ? " · 读数已过期" : "") let telemetry = viewModel.telemetry @@ -270,21 +290,25 @@ final class DroneDockShootingTaskViewController: BaseViewController { let value = loading && viewModel.response == nil && presentation.phase != .navigating ? DroneDockTaskPresentation( phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务", deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : presentation - statusView.apply(value, isRefreshing: loading) + statusView.apply(value, isRefreshing: loading, isPrimaryActionLoading: value.action == .resume + && (submittingCommands.contains(.resume) || viewModel.isCommandLoading(.resume))) updateArrivalCountdown() safetyView.apply(model: viewModel, isSimulation: simulationRecordsProvider != nil, - isInteractive: isPageVisible && isApplicationActive && !loading) + isInteractive: isPageVisible && isApplicationActive && !loading, + submittingCommands: submittingCommands) statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading navigationItem.rightBarButtonItems?.forEach { $0.isEnabled = isPageVisible && isApplicationActive && !loading } navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil + recordRenderedState() presentCompletionNoticeIfNeeded() refreshLiveIfVisible(automatically: true) } - /// 倒计时只更新独立秒数标签;网络读取、飞控及后端阶段仍由原有流程驱动。 + /// 倒计时只更新开拍按钮文案;网络读取、飞控及后端阶段仍由原有流程驱动。 private func updateArrivalCountdown() { let seconds = viewModel.countdownRemainingSeconds statusView.updateCountdown(seconds: seconds) + recordCountdownState(seconds) guard isPageVisible, isApplicationActive, let seconds, seconds > 0 else { stopArrivalCountdown() return @@ -300,6 +324,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { self.isPageVisible, self.isApplicationActive else { return } let remaining = self.viewModel.countdownRemainingSeconds self.statusView.updateCountdown(seconds: remaining) + self.recordCountdownState(remaining) if remaining == nil || remaining == 0 { self.countdownTask = nil return @@ -321,10 +346,15 @@ final class DroneDockShootingTaskViewController: BaseViewController { displayedCompletionIDs.insert(id) let notice = DroneDockRecordingCompletionView() completionNotice = notice - notice.onLater = { [weak self] in self?.dismissCompletionNotice() } + logEvent("ui.completion_notice.shown") + notice.onLater = { [weak self] in + self?.logEvent("ui.completion_notice.later") + self?.dismissCompletionNotice() + } notice.onViewMaterials = { [weak self] in guard let self, self.isPageVisible, self.isApplicationActive, self.viewModel.recordingExecutionID == id else { return } + self.logEvent("ui.completion_notice.view_materials") self.dismissCompletionNotice() self.openMaterials() } @@ -335,6 +365,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { } private func dismissCompletionNotice() { + if completionNotice != nil { logEvent("ui.completion_notice.dismissed") } completionNotice?.removeFromSuperview() completionNotice = nil } @@ -352,10 +383,15 @@ final class DroneDockShootingTaskViewController: BaseViewController { "enabled": viewModel.presentation.isActionEnabled]) guard isPageVisible, isApplicationActive, !isStartingAction, !viewModel.isStartingShooting, - !isSendingSafetyAction, !viewModel.isSendingCommand, - !isResummoningAction, !viewModel.isResummoning else { return } + !isResummoningAction, !viewModel.isResummoning else { + logEvent("action.primary.rejected", fields: ["reason": "page_or_submission_guard", "ui": statusView.diagnosticFields]) + return + } let state = viewModel.presentation - guard state.isActionEnabled else { return } + guard state.isActionEnabled else { + logEvent("action.primary.rejected", fields: ["reason": "presentation_action_disabled", "ui": statusView.diagnosticFields]) + return + } switch state.action { case .refresh: refreshTaskIfVisible() @@ -365,7 +401,9 @@ final class DroneDockShootingTaskViewController: BaseViewController { resummonIfAllowed() case .materials: openMaterials() - case .resume, .none: + case .resume: + safetyCommandTriggered(.resume) + case .none: break } } @@ -394,10 +432,8 @@ final class DroneDockShootingTaskViewController: BaseViewController { private func refreshTaskIfVisible(isPolling: Bool = false) { guard isPageVisible, isApplicationActive, viewModel.readAccessError == nil, !isRequesting, !viewModel.isLoading, !isStartingAction, !viewModel.isStartingShooting, - !isSendingSafetyAction, !viewModel.isSendingCommand, !isResummoningAction, !viewModel.isResummoning else { return } cancelScheduledPoll() - logEvent("shooting.refresh", fields: ["trigger": isPolling ? "poll" : "page_or_manual", "live_battery": 0]) requestGeneration &+= 1 let generation = requestGeneration isRequesting = true @@ -424,11 +460,10 @@ final class DroneDockShootingTaskViewController: BaseViewController { cancelScheduledPoll() guard isPageVisible, isApplicationActive, viewModel.canContinuePolling, realtimeSession?.state != .live, - !isRequesting, !isStartingAction, !isSendingSafetyAction, !isResummoningAction else { return } + !isRequesting, !isStartingAction, !isResummoningAction else { return } let generation = pollGeneration let delay = shootingPollDelay let interval = viewModel.pollIntervalNanoseconds - logEvent("poll.scheduled", fields: ["delay_ms": interval / 1_000_000]) pollTask = Task { @MainActor [weak self] in do { try await delay(interval) } catch { return } guard !Task.isCancelled, let self, self.pollGeneration == generation else { return } @@ -438,7 +473,6 @@ final class DroneDockShootingTaskViewController: BaseViewController { } private func cancelScheduledPoll() { - if pollTask != nil { logEvent("poll.cancelled") } pollGeneration &+= 1 pollTask?.cancel() pollTask = nil @@ -464,12 +498,13 @@ final class DroneDockShootingTaskViewController: BaseViewController { refreshTask = nil startTask?.cancel() startTask = nil - commandTask?.cancel() - commandTask = nil + commandTasks.values.forEach { $0.cancel() } + commandTasks.removeAll() + commandAttemptIDs.removeAll() + submittingCommands.removeAll() resummonTask?.cancel() resummonTask = nil isResummoningAction = false - isSendingSafetyAction = false isStartingAction = false isRequesting = false viewModel.invalidate(preservingSnapshot: true) @@ -477,6 +512,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { } private func connectionStateChanged(_ state: DroneDockShootingRealtimeSession.State) { + logChangedEvent("page.realtime_state", fields: ["state": String(describing: state)]) guard isPageVisible, isApplicationActive else { return } switch state { case .live: @@ -564,12 +600,12 @@ final class DroneDockShootingTaskViewController: BaseViewController { /// 可见且活跃时自动开启一次;失败可手动重试,不随 shooting/Socket 刷新重复请求。 private func refreshLiveIfVisible(automatically: Bool = false, keepingPlayback: Bool = false) { guard viewModel.response != nil, viewModel.readAccessError == nil, - !finishedExecutions.contains(viewModel.recordingExecutionID), !viewModel.isRecordingFinished else { return } + stoppedLiveExecutionTitles[viewModel.recordingExecutionID] == nil, !viewModel.shouldStopLiveReception else { return } guard !automatically || liveViewModel.loadsAutomatically else { return } guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return } liveParameterTask?.cancel() liveParameterTask = nil - logEvent("live.request", fields: ["automatic": automatically]) + logEvent("live.request", fields: ["automatic": automatically, "keeping_playback": keepingPlayback]) liveGeneration &+= 1 let generation = liveGeneration liveTask = Task { @MainActor [weak self] in @@ -602,6 +638,10 @@ final class DroneDockShootingTaskViewController: BaseViewController { /// 离页或进入后台立即释放播放器,使旧图传响应无法恢复播放。 private func stopLive() { + if liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil { + logEvent("live.reception_stopping", fields: ["recording_finished": viewModel.isRecordingFinished, + "task_requires_stop": viewModel.shouldStopLiveReception, "ui": feedPlaceholder.diagnosticFields]) + } liveGeneration &+= 1 liveParameterTask?.cancel() liveParameterTask = nil @@ -616,49 +656,62 @@ final class DroneDockShootingTaskViewController: BaseViewController { private func safetyCommandTriggered(_ command: DroneDockSafetyCommand) { logEvent("action.safety", fields: ["command": command.rawValue, "enabled": viewModel.canSendCommand(command)]) guard allowsControlActions, isPageVisible, isApplicationActive, - presentedViewController == nil, !isSendingSafetyAction, !isStartingAction, - !isResummoningAction, viewModel.canSendCommand(command) else { return } + presentedViewController == nil, !submittingCommands.contains(command), !isStartingAction, + !isResummoningAction, viewModel.canSendCommand(command) else { + logSafetyRejection(command, stage: "tap") + return + } if command == .returnHome { let simulated = simulationRecordsProvider != nil let alert = UIAlertController(title: simulated ? "立即返航(本地模拟)" : "立即返航", message: simulated ? "模拟返航会中断本次任务。取消返航也不会恢复已经中断的任务。\n仅验证本地请求与回执,不向无人机发送指令。" : "返航会中断本次任务。取消返航也不会恢复已经中断的任务。确定立即返航?", preferredStyle: .alert) - alert.addAction(UIAlertAction(title: "取消", style: .cancel)) + alert.addAction(UIAlertAction(title: "取消", style: .cancel) { [weak self] _ in + self?.logEvent("action.return_confirmation.cancelled") + }) alert.addAction(UIAlertAction(title: simulated ? "模拟返航" : "立即返航", style: .destructive) { [weak self] _ in + self?.logEvent("action.return_confirmation.confirmed") self?.sendSafetyCommand(command) }) + logEvent("action.return_confirmation.shown") present(alert, animated: true) } else { sendSafetyCommand(command) } } - /// 同步锁覆盖异步调度间隙;界面保留旧快照,只有同任务回查成功才更新阶段。 + /// 同步锁只覆盖同一按钮;不同安全动作可各自等待,设备确认由 ViewModel 和快照处理。 private func sendSafetyCommand(_ command: DroneDockSafetyCommand) { guard allowsControlActions, isPageVisible, isApplicationActive, - !isSendingSafetyAction, !isStartingAction, !isResummoningAction, - viewModel.canSendCommand(command) else { return } + !submittingCommands.contains(command), !isStartingAction, !isResummoningAction, + viewModel.canSendCommand(command) else { + logSafetyRejection(command, stage: "submit") + return + } cancelPendingReadForAction() - let generation = requestGeneration - isSendingSafetyAction = true + let attemptID = UUID() + logEvent("action.safety.submitting", fields: ["command": command.rawValue, "ui_attempt_id": attemptID.uuidString]) + commandAttemptIDs[command] = attemptID + submittingCommands.insert(command) applySnapshot() - commandTask = Task { @MainActor [weak self] in + commandTasks[attemptID] = Task { @MainActor [weak self] in guard let self else { return } - await self.viewModel.sendCommand(command) { [weak self] in self?.applySnapshot() } + await self.viewModel.sendCommand(command) { [weak self] in + guard let self, self.commandAttemptIDs[command] == attemptID else { return } + // ViewModel 已建立本次操作后,加载状态完全交由其管理;后续只读回查不延长动画。 + self.submittingCommands.remove(command) + self.applySnapshot() + } + self.commandTasks.removeValue(forKey: attemptID) guard self.isPageVisible, self.isApplicationActive, - self.requestGeneration == generation, !Task.isCancelled else { return } - self.commandTask = nil - self.isSendingSafetyAction = false + self.commandAttemptIDs[command] == attemptID, !Task.isCancelled else { return } + self.commandAttemptIDs.removeValue(forKey: command) + self.submittingCommands.remove(command) self.applySnapshot() self.scheduleNextPoll() - if let error = self.viewModel.commandErrorMessage { + if let error = self.viewModel.commandErrorMessage(for: command) { self.showToast(error) - } else if let error = self.viewModel.errorMessage { - self.showToast("指令已受理,状态刷新失败:\(error)") - } else { - self.showToast(self.simulationRecordsProvider != nil - ? "本地模拟指令已受理,未发送设备指令" : "指令已受理,请等待任务状态更新") } } } @@ -671,15 +724,17 @@ final class DroneDockShootingTaskViewController: BaseViewController { } @objc private func refreshTriggered() { + logEvent("action.refresh") guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { + logEvent("action.refresh.rejected", fields: ["reason": "page_or_read_guard", "read_in_progress": isRequesting || viewModel.isLoading]) return } refreshTaskIfVisible() } @objc private func applicationWillResignActive() { - logEvent("app.inactive") isApplicationActive = false + logEvent("app.inactive") cancelRefresh() stopLive() } @@ -695,9 +750,86 @@ final class DroneDockShootingTaskViewController: BaseViewController { private func logEvent(_ name: String, fields: [String: Any] = [:]) { var fields = fields fields["source"] = simulationRecordsProvider == nil ? "task_page" : "local_simulation" - fields["scenic_id"] = viewModel.context.scenicID - fields["order_number"] = viewModel.order.orderNumber - DroneDockDiagnostics.event(name, taskID: viewModel.taskID, fields: fields) + fields["entry_source"] = entrySource + fields["page_visible"] = isPageVisible + fields["app_active"] = isApplicationActive + fields["view_in_window"] = isViewLoaded && view.window != nil + fields["debug_flight_blocked"] = DeviceCommandDebugPolicy.blocksFlightRequests + fields["debug_live_blocked"] = DeviceCommandDebugPolicy.blocksLiveRequests + fields["allows_control_actions"] = allowsControlActions + viewModel.recordTaskEvent(name, fields: fields) + } + + /// 去重只比较 UI 可观察值,不把快照版本或逐秒计时加入比较。 + private func logChangedEvent(_ name: String, fields: [String: Any]) { + guard let data = try? JSONSerialization.data(withJSONObject: fields, options: [.sortedKeys]), + diagnosticStateData[name] != data else { return } + diagnosticStateData[name] = data + logEvent(name, fields: fields) + } + + private func recordRenderedState() { + logChangedEvent("ui.render", fields: ["central": statusView.diagnosticFields, + "safety": safetyView.diagnosticFields, "page_visible": isPageVisible, + "app_active": isApplicationActive, "starting": isStartingAction || viewModel.isStartingShooting, + "resummoning": isResummoningAction || viewModel.isResummoning, + "submitting_commands": submittingCommands.map(\.rawValue).sorted()]) + var liveFields = feedPlaceholder.diagnosticFields + switch liveViewModel.state { + case .restricted: liveFields["state"] = "restricted" + case .idle: liveFields["state"] = "idle" + case .loading: liveFields["state"] = "loading" + case .connecting: liveFields["state"] = "connecting" + case .playing: liveFields["state"] = "playing" + case .localPreview: liveFields["state"] = "local_preview" + case .unavailable(let message): liveFields["state"] = "unavailable"; liveFields["reason"] = message + case .failed(let message): liveFields["state"] = "failed"; liveFields["reason"] = message + } + liveFields["active_role"] = liveViewModel.activeRole as Any? ?? NSNull() + liveFields["playback_session"] = liveViewModel.playbackSessionID?.uuidString as Any? ?? NSNull() + logChangedEvent("live.render", fields: liveFields) + } + + private func recordCountdownState(_ seconds: Int?) { + let stage = !isPageVisible || !isApplicationActive || seconds == nil ? "hidden" : seconds == 0 ? "zero" : "running" + let key = viewModel.recordingExecutionID + ":" + stage + guard countdownDiagnosticKey != key else { return } + countdownDiagnosticKey = key + logEvent("ui.countdown", fields: ["state": stage, "remaining_seconds": seconds as Any? ?? NSNull(), + "execution_id": viewModel.recordingExecutionID]) + } + + private func recordPlaybackEvent(_ event: DroneDockLivePlaybackEvent, sessionID: UUID) { + var fields: [String: Any] = ["playback_session": sessionID.uuidString, + "page_session_valid": isPageVisible && isApplicationActive && liveViewModel.playbackSessionID == sessionID, + "previous_role": liveViewModel.activeRole as Any? ?? NSNull()] + let name: String + switch event { + case .firstFrame: + name = "live.first_frame" + fields["role"] = liveViewModel.rtcConfiguration?.role as Any? ?? NSNull() + case .sourceChanged(let role): + name = "live.source_changed" + fields["role"] = role as Any? ?? NSNull() + fields["fallback_to_airport"] = liveViewModel.activeRole == "drone" && role == "airport" + case .failed(let message): name = "live.receiver.failed"; fields["message"] = message + case .expired: name = "live.receiver.expired" + } + logChangedEvent(name, fields: fields) + } + + private func logSafetyRejection(_ command: DroneDockSafetyCommand, stage: String) { + var reasons: [String] = [] + if !allowsControlActions { reasons.append("debug_policy") } + if !isPageVisible { reasons.append("page_hidden") } + if !isApplicationActive { reasons.append("app_inactive") } + if stage == "tap", presentedViewController != nil { reasons.append("modal_presented") } + if submittingCommands.contains(command) { reasons.append("same_command_submitting") } + if isStartingAction { reasons.append("start_submitting") } + if isResummoningAction { reasons.append("resummon_submitting") } + if !viewModel.canSendCommand(command) { reasons.append("model_command_not_allowed") } + logEvent("action.safety.rejected", fields: ["command": command.rawValue, "stage": stage, + "reasons": reasons, "safety": safetyView.diagnosticFields]) } private var allowsControlActions: Bool { @@ -743,13 +875,11 @@ final class DroneDockSimulationRecordsViewController: BaseViewController { @objc private func close() { dismiss(animated: true) } } -/// 固定底部的安全控制,只在隔离模拟入口按当前接口提供的指令展示可用操作。 +/// 固定底部的安全控制,文案来自本地阶段,操作许可统一由任务模型判断。 @MainActor private final class DroneDockTaskSafetyView: UIView { /// 将用户选择的白名单指令交给页面,不直接调用任何服务。 var onCommand: ((DroneDockSafetyCommand) -> Void)? - private var pauseCommand = DroneDockSafetyCommand.pause - private var returnCommand = DroneDockSafetyCommand.returnHome private let header = DroneDockStyle.label("安全控制", size: 11, color: DroneDockStyle.secondary) private let pauseButton = DroneShootingTaskSafetyButton(symbol: "pause.circle", color: UIColor(hex: 0xEC982A), filled: true) private let returnButton = DroneShootingTaskSafetyButton(symbol: "arrow.uturn.backward", color: UIColor(hex: 0xD85762), filled: false) @@ -759,6 +889,11 @@ private final class DroneDockTaskSafetyView: UIView { private var buttonGap: Constraint? private var buttonHeight: Constraint? + /// 两个固定按钮实际显示的标题、字幕、启用和加载状态。 + var diagnosticFields: [String: Any] { + ["pause": pauseButton.diagnosticFields, "return_home": returnButton.diagnosticFields] + } + /// 复用安全按钮样式,初始没有状态数据时保持禁用。 override init(frame: CGRect) { super.init(frame: frame) @@ -799,36 +934,51 @@ private final class DroneDockTaskSafetyView: UIView { @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } - /// 保持两列固定布局,暂停/继续与返航/取消由快照中的指令白名单决定。 - func apply(model: DroneDockShootingTaskViewModel, isSimulation: Bool, isInteractive: Bool) { - let commands = model.availableSafetyCommands + /// 两个按钮始终表示暂停与返航;已暂停、返航中和回巢使用本地文案,恢复入口位于中央。 + func apply(model: DroneDockShootingTaskViewModel, isSimulation: Bool, isInteractive: Bool, + submittingCommands: Set = []) { let allowsControls = isSimulation || !DeviceCommandDebugPolicy.blocksFlightRequests - pauseCommand = commands.contains(.resume) ? .resume : .pause - returnCommand = commands.contains(.cancelReturn) ? .cancelReturn : .returnHome - header.text = model.commandOutcomeUnknown ? "安全控制 · 结果待核对" - : model.isSendingCommand ? (isSimulation ? "安全控制 · 本地模拟发送中" : "安全控制 · 指令发送中") - : isSimulation ? "安全控制 · 本地模拟,不发送设备指令" : "安全控制" - for (button, command) in [(pauseButton, pauseCommand), (returnButton, returnCommand)] { - let title: String - let subtitle: String - switch command { - case .pause: title = "紧急暂停"; subtitle = "悬停待命" - case .resume: title = "继续拍摄"; subtitle = "恢复航线" - case .returnHome: title = "立即返航"; subtitle = "中断任务" - case .cancelReturn: title = "取消返航"; subtitle = "不恢复已中断任务" + let phase = model.presentation.phase + var controlState = model.flightControlState + if model.response?.flightControl == nil { + switch phase { + case .paused: controlState = .paused + case .returning: controlState = .returning + case .returned: controlState = .returned + default: break } + } + header.text = isSimulation ? "安全控制 · 本地模拟,不发送设备指令" : "安全控制" + for (button, command) in [(pauseButton, DroneDockSafetyCommand.pause), (returnButton, .returnHome)] { + var title = command == .pause ? "紧急暂停" : "立即返航" + var subtitle = command == .pause ? "悬停待命" : "中断任务" + if controlState == .paused, command == .pause { + title = "已暂停" + } else if controlState == .returning { + if command == .returnHome { + title = "返航中" + subtitle = "返回机巢" + } + } else if controlState == .returned { + title = command == .pause ? "紧急暂停" : "已返航" + subtitle = command == .pause ? "当前未执行任务" : "已返回机巢" + } else if controlState == .unknown, model.response?.flightControl != nil { + subtitle = "暂不可用" + } else if [.loading, .readError, .unknown].contains(phase) { + subtitle = "暂不可用" + } + if model.isCommandOutcomeUnknown(command) { + subtitle = "结果待核对" + } + let loading = submittingCommands.contains(command) || model.isCommandLoading(command) let enabled = allowsControls && isInteractive && model.canSendCommand(command) - let detail = model.activeCommand == command ? (isSimulation ? "本地模拟发送中…" : "指令发送中…") - : model.commandOutcomeUnknown ? "结果待核对" - : !allowsControls || !commands.contains(command) ? "暂不可用" : subtitle - button.apply(title: title, subtitle: detail, enabled: enabled) - button.setControlSymbol(command == .resume ? "play.circle" : command == .pause ? "pause.circle" - : command == .cancelReturn ? "xmark.circle" : "arrow.uturn.backward") + button.apply(title: title, subtitle: subtitle, enabled: enabled, isLoading: loading) + button.setControlSymbol(command == .pause ? "pause.circle" : "arrow.uturn.backward") } } - @objc private func pauseTapped() { guard pauseButton.isEnabled else { return }; onCommand?(pauseCommand) } - @objc private func returnTapped() { guard returnButton.isEnabled else { return }; onCommand?(returnCommand) } + @objc private func pauseTapped() { guard pauseButton.isEnabled else { return }; onCommand?(.pause) } + @objc private func returnTapped() { guard returnButton.isEnabled else { return }; onCommand?(.returnHome) } /// 高度仅依设备空间切换,不随任务状态、按钮文案或网络响应变化。 func configure(compact: Bool) { diff --git a/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift b/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift index ae45765..f08aa1b 100644 --- a/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift +++ b/suixinkan/UI/DroneDock/DroneDockStartShootSimulation.swift @@ -106,10 +106,13 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { private var hasCreated: Bool private var hasSummoned: Bool private var hasStarted: Bool + private var lastCommandProgress: [String: Any]? private var isPaused = false private var isReturning = false private var wasInterrupted = false private var hasFailed: Bool + private var executionBatch = 9_001 + private var stateVersion = 1 private var exchanges: [Exchange] = [] /// 固定当前实例结果,不能用参数切换到真实传输。 @@ -191,7 +194,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { } if request.httpMethod == "GET", url.path == "/api/app/airport/plane-status" { guard queryMatches(url, required: ["scenic_id": "128", "live_battery": "1"]) else { throw URLError(.badURL) } - let plane: [String: Any] = ["id": 201, "name": "本地模拟无人机", "sn_number": "LOCAL-MOCK-PLANE-201", + let plane: [String: Any] = ["id": 201, "name": "本地模拟无人机", "sn_number": "LOCAL-MOCK-DOCK-201", "online_status": 1, "work_status": 1, "work_status_label": "空闲(模拟)", "status_text": "本地模拟 · 电量 95%", "battery_percent": 95, "can_fly": true, "is_receive_order": 1] @@ -230,11 +233,15 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { hasFailed = false hasStarted = false isPaused = false + isReturning = false + wasInterrupted = false + executionBatch += 1 } } else if !hasCreated || hasSummoned { return try envelope([:], code: 100099, message: "本地模拟:任务尚未创建或已召唤") } hasSummoned = true + stateVersion += 1 return try envelope(["order_flight_task": taskData(), "order_flight_task_id": 901, "plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201", "task_uuid": "LOCAL-MOCK-TASK-UUID-901", @@ -262,7 +269,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { if request.httpMethod == "POST", url.path == "/api/app/airport/command" { guard url.query == nil, let body = request.httpBody, let object = try JSONSerialization.jsonObject(with: body) as? [String: Any], - Set(object.keys) == ["id", "command"], + Set(object.keys) == ["id", "command", "client_request_id"], let values = try? JSONDecoder().decode(CommandBody.self, from: body), values.id == 901, let command = DroneDockSafetyCommand(rawValue: values.command) else { throw URLError(.badURL) @@ -282,7 +289,17 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { case .returnHome: isReturning = true; wasInterrupted = true; isPaused = false case .cancelReturn: isReturning = false; isPaused = true } - return try envelope(["command": command.rawValue, "order_flight_task_id": 901, + stateVersion += 1 + let commandID = "LOCAL-MOCK-COMMAND-\(stateVersion)" + lastCommandProgress = ["command_id": commandID, "client_request_id": values.clientRequestID, + "command": command.rawValue, "status": "succeeded"] + return try envelope(["accepted": true, "device_confirmed": true, + "command_id": commandID, "client_request_id": values.clientRequestID, + "pending_command": lastCommandProgress ?? [:], + "acceptance": command == .returnHome ? "accepted" : "device_confirmed", + "command": command.rawValue, "order_flight_task_id": 901, + "execution_batch": executionBatch, "state_version": stateVersion, + "flight_control": flightControlData(), "airport_sn": "LOCAL-MOCK-DOCK-201", "dji_status": simulatedPhase, "metrics": simulatedMetrics]) } @@ -308,6 +325,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { throw URLError(.timedOut) case .success: hasStarted = true + stateVersion += 1 return try envelope([ "task_uuid": "LOCAL-MOCK-TASK-UUID-901", "order_flight_task_id": 901, "order_flight_task": taskData(), "plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201", @@ -355,13 +373,15 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { } let deviceLabel = isReturning ? "返航中" : isPaused ? "悬停中" : hasStarted ? "拍摄中" : "空闲" return ["order_number": "LOCAL-MOCK-ORDER-901", "order_flight_task": taskData(), "task": taskData(), + "execution_batch": executionBatch, "state_version": stateVersion, "snapshot_kind": "full", + "flight_control": flightControlData(), "scenic": ["id": 128, "name": "本地模拟景区"], "scenic_spot": ["id": 301, "name": "模拟点位"], "air_line": ["id": 401, "name": "模拟航线", "scenic_spot_id": 301], "header": ["order_number": "LOCAL-MOCK-ORDER-901", "title": "模拟点位 · 模拟航线", "tourist_label": "本地模拟,无设备指令", "package_name": "模拟套餐 · 含5次拍摄"], - "current_plane": ["id": 201, "sn_number": "LOCAL-MOCK-PLANE-201", "online_status": 1, - "work_status": hasStarted ? 2 : 1, "work_status_label": deviceLabel, + "current_plane": ["id": 201, "sn_number": "LOCAL-MOCK-DOCK-201", "online_status": 1, + "work_status": hasFailed ? 1 : 2, "work_status_label": deviceLabel, "status_text": "本地模拟 · \(deviceLabel) · 电量95%"], "metrics": simulatedMetrics, "plane_status": ["scenic_id": 128, "connected": true, "poll_hint_ms": 5000], @@ -369,12 +389,14 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { "message": hasStarted ? "本地模拟:开拍已受理" : "本地模拟:允许验证开拍请求", "primary_action": canStart ? "start_shoot" : simulatedPhase, "primary_action_label": hasStarted ? "拍摄中" : "开始拍摄"], + "restart_gate": ["can_restart": hasFailed, "code": hasFailed ? "ok" : "running"], "ui": ["phase": simulatedPhase, "title": phaseTitle, "commands": commands, "message": wasInterrupted ? phaseTitle : "本地模拟状态回查,未向设备发送指令。"]] } private func taskData() -> [String: Any] { var task: [String: Any] = ["id": 901, "order_number": "LOCAL-MOCK-ORDER-901", "scenic_id": 128, + "wayline_task_id": executionBatch, "plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201", "status": 20, "status_label": "执行中(模拟)", "wayline_status": 20, "wayline_status_label": "执行中(模拟)"] if hasFailed { task["status"] = 40 @@ -385,7 +407,7 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { } else if wasInterrupted { task["status"] = 40 task["status_label"] = "任务已中断(模拟)" - task["wayline_status"] = 40 + task["wayline_status"] = 91 task["wayline_status_label"] = "已中断(模拟)" task["result_code"] = "return_home" task["result_message"] = isReturning ? "本地模拟:立即返航中断任务;无人机返航中。" @@ -396,19 +418,34 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { private var availableCommands: [DroneDockSafetyCommand] { guard hasSummoned, !hasFailed else { return [] } - if isReturning { return [.cancelReturn] } + if isReturning { return [isPaused ? .resume : .pause] } if wasInterrupted { return [] } return [isPaused ? .resume : .pause, .returnHome] } private var simulatedPhase: String { if hasFailed { return "failed" } - if isReturning { return "returning" } + if isPaused { return "manual_paused" } + if isReturning { return "returning_home" } if wasInterrupted { return "failed" } - if isPaused { return "paused" } return hasStarted ? "shooting" : "arrived_pending_start" } + /// 同一模拟批次的执行状态和权限;回巢仅在显式失败起始场景中提供 inside 证据。 + private func flightControlData() -> [String: Any] { + let state = hasFailed ? "returned" : isPaused ? "paused" : isReturning ? "returning" : "executing" + let pauseReason: Any = isPaused ? "manual" : (hasStarted ? NSNull() : "arrival_wait" as Any) + return ["state": state, "execution_batch": executionBatch, + "is_airborne": !hasFailed, "pause_reason": pauseReason, + "pending_command": lastCommandProgress ?? [:], + "resume_phase": isReturning ? "returning" : hasStarted ? "shooting" : "arrived_pending_start", + "return_reason": wasInterrupted ? "manual" : NSNull(), + "drone_in_dock": hasFailed ? "inside" : "outside", + "can_pause": availableCommands.contains(.pause), + "can_resume": availableCommands.contains(.resume), + "can_return_home": availableCommands.contains(.returnHome)] + } + private var simulatedMetrics: [[String: String]] { [["key": "battery", "value": "95%"], ["key": "env_temp", "value": "20.3℃"], ["key": "wind_speed", "value": "0m/s"], ["key": "rainfall", "value": "无雨"], @@ -456,6 +493,8 @@ private final class DroneDockStartShootMockSession: LocalSimulationURLSession { private struct CommandBody: Decodable { let id: Int let command: String + let clientRequestID: String + private enum CodingKeys: String, CodingKey { case id, command, clientRequestID = "client_request_id" } } } #endif diff --git a/suixinkan/UI/DroneDock/DroneDockTaskControlStateView.swift b/suixinkan/UI/DroneDock/DroneDockTaskControlStateView.swift new file mode 100644 index 0000000..d05f1d2 --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneDockTaskControlStateView.swift @@ -0,0 +1,249 @@ +import SnapKit +import UIKit + +/// 暂停、返航及回巢面板,使用本地状态文案及整行主按钮,不显示设备摘要。 +@MainActor +final class DroneDockTaskControlStateView: UIView { + /// 用户点击已允许的主操作时交给任务页面执行。 + var onPrimaryAction: (() -> Void)? + /// 当前固定区域使用的排版比例,不通过 transform 缩小点击区域。 + private(set) var effectiveScale: CGFloat = 1 + /// 可用高度不足时收紧图标、字号与间距。 + private(set) var usesCompactLayout = false + + private let content = UIView() + private let header = UIView() + private let iconBackground = UIView() + private let icon = UIImageView() + private let titleLabel = DroneDockStyle.label(size: 22, weight: .semibold, color: UIColor(hex: 0x101523)) + private let messageLabel = DroneDockStyle.label(size: 14, color: UIColor(hex: 0x6A79A0)) + private let actionButton = UIButton(type: .system) + private let actionActivityIndicator = UIActivityIndicatorView(style: .medium) + private let noteLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary) + private var presentation: DroneDockTaskPresentation? + private var identifiersActive = false + private var isPrimaryActionLoading = false + private var headerHeight: Constraint? + private var iconSize: Constraint? + private var textLeading: Constraint? + private var titleHeight: Constraint? + private var messageTop: Constraint? + private var messageHeight: Constraint? + private var actionTop: Constraint? + private var actionHeight: Constraint? + private var noteTop: Constraint? + private var noteHeight: Constraint? + + /// 创建与任务固定状态区域配合的控制状态视图。 + override init(frame: CGRect) { + super.init(frame: frame) + setupUI() + setupConstraints() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 文案和动作均由本地展示模型提供,禁用按钮只显示状态且不会触发回调。 + func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false, isPrimaryActionLoading: Bool = false) { + self.presentation = presentation + self.isPrimaryActionLoading = isPrimaryActionLoading + titleLabel.text = presentation.title + messageLabel.text = presentation.message + noteLabel.text = presentation.actionNote + switch presentation.phase { + case .paused: icon.image = UIImage(systemName: "pause.fill") + case .returning: icon.image = UIImage(systemName: "arrow.uturn.backward") + case .returned: icon.image = UIImage(systemName: "house.fill") + default: icon.image = UIImage(systemName: "clock") + } + actionButton.isEnabled = presentation.action != .none && presentation.isActionEnabled && !isRefreshing && !isPrimaryActionLoading + actionButton.configuration?.title = presentation.actionTitle + let actionSymbol: String? = switch presentation.action { + case .resume: "play.fill" + case .retry: "paperplane.fill" + case .refresh: "arrow.clockwise" + default: nil + } + actionButton.configuration?.image = actionSymbol.flatMap { UIImage(systemName: $0) } + if isPrimaryActionLoading { actionActivityIndicator.startAnimating() } + else { actionActivityIndicator.stopAnimating() } + actionButton.accessibilityValue = isPrimaryActionLoading ? "处理中" : nil + setIdentifiersActive(identifiersActive) + actionButton.setNeedsUpdateConfiguration() + setNeedsLayout() + } + + /// 只有可见面板暴露通用标识,状态切换后不会匹配到隐藏的旧按钮。 + func setIdentifiersActive(_ active: Bool) { + identifiersActive = active + if !active { actionActivityIndicator.stopAnimating() } + titleLabel.accessibilityIdentifier = active ? "drone.task.remote.statusTitle" : nil + messageLabel.accessibilityIdentifier = active ? "drone.task.remote.statusMessage" : nil + actionButton.accessibilityIdentifier = active + ? (presentation?.action == .refresh ? "drone.task.remote.refresh" : "drone.task.remote.primary") : nil + actionActivityIndicator.accessibilityIdentifier = active ? "drone.task.remote.primary.loading" : nil + } + + /// 在固定区域内收紧排版,主按钮始终至少 44 点高。 + override func layoutSubviews() { + updateContentLayout() + super.layoutSubviews() + } + + private func setupUI() { + accessibilityIdentifier = "drone.task.remote.controlState" + backgroundColor = .white + addSubview(content) + [header, actionButton, noteLabel].forEach(content.addSubview) + [iconBackground, titleLabel, messageLabel].forEach(header.addSubview) + iconBackground.addSubview(icon) + iconBackground.backgroundColor = UIColor(hex: 0xFFF3E0) + iconBackground.layer.cornerRadius = 20.5 + icon.contentMode = .scaleAspectFit + icon.tintColor = UIColor(hex: 0xF39819) + titleLabel.accessibilityTraits = .header + titleLabel.numberOfLines = 1 + titleLabel.lineBreakMode = .byTruncatingTail + messageLabel.numberOfLines = 3 + messageLabel.lineBreakMode = .byTruncatingTail + noteLabel.numberOfLines = 1 + noteLabel.textAlignment = .center + noteLabel.accessibilityIdentifier = "drone.task.remote.controlNote" + var configuration = UIButton.Configuration.filled() + configuration.imagePadding = 10 + configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 20, weight: .semibold) + configuration.background.cornerRadius = 8 + configuration.cornerStyle = .fixed + configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8) + actionButton.configuration = configuration + actionButton.configurationUpdateHandler = { [weak self] button in + guard let self, var configuration = button.configuration else { return } + let emphasizesAction = button.isEnabled || self.isPrimaryActionLoading + let foreground = emphasizesAction ? UIColor.white : UIColor(hex: 0x929BAE) + let font = UIFont.systemFont(ofSize: self.usesCompactLayout ? 16 : 18, weight: .semibold) + configuration.background.backgroundColor = emphasizesAction + ? DroneDockStyle.primary : UIColor(hex: 0xEDF0F5) + configuration.baseForegroundColor = foreground + configuration.imageColorTransformer = UIConfigurationColorTransformer { _ in foreground } + // loading 会禁用按钮;显式设置最终文字色,避免系统禁用态再次把白字变暗。 + configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in + var result = attributes + result.font = font + result.foregroundColor = foreground + return result + } + button.configuration = configuration + } + actionActivityIndicator.color = .white + actionActivityIndicator.hidesWhenStopped = true + actionActivityIndicator.isUserInteractionEnabled = false + actionButton.addSubview(actionActivityIndicator) + actionButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside) + } + + private func setupConstraints() { + content.snp.makeConstraints { make in + make.leading.trailing.equalToSuperview().inset(18) + make.centerY.equalToSuperview() + } + header.snp.makeConstraints { make in + make.top.leading.trailing.equalToSuperview() + headerHeight = make.height.equalTo(81).constraint + } + iconBackground.snp.makeConstraints { make in + make.top.leading.equalToSuperview() + iconSize = make.size.equalTo(41).constraint + } + icon.snp.makeConstraints { make in + make.center.equalToSuperview() + make.size.equalTo(iconBackground.snp.width).multipliedBy(24.0 / 41.0) + } + titleLabel.snp.makeConstraints { make in + make.top.trailing.equalToSuperview() + textLeading = make.leading.equalTo(iconBackground.snp.trailing).offset(12).constraint + titleHeight = make.height.equalTo(28).constraint + } + messageLabel.snp.makeConstraints { make in + messageTop = make.top.equalTo(titleLabel.snp.bottom).offset(6).constraint + make.leading.trailing.equalTo(titleLabel) + messageHeight = make.height.equalTo(45).constraint + } + actionButton.snp.makeConstraints { make in + actionTop = make.top.equalTo(header.snp.bottom).offset(16).constraint + make.leading.trailing.equalToSuperview() + actionHeight = make.height.equalTo(50).constraint + } + actionActivityIndicator.snp.makeConstraints { make in + make.centerY.equalToSuperview() + make.trailing.equalToSuperview().inset(14) + make.size.equalTo(20) + } + noteLabel.snp.makeConstraints { make in + noteTop = make.top.equalTo(actionButton.snp.bottom).offset(6).constraint + make.leading.trailing.bottom.equalToSuperview() + noteHeight = make.height.equalTo(16).constraint + } + } + + private func updateContentLayout() { + guard let presentation, bounds.width > 0, bounds.height > 0 else { return } + let wasCompact = usesCompactLayout + usesCompactLayout = bounds.height < 190 + let extreme = bounds.height < 120 + let compact = usesCompactLayout + let diameter: CGFloat = extreme ? 24 : compact ? 32 : 41 + let iconGap: CGFloat = extreme ? 8 : compact ? 10 : 12 + let titleSize: CGFloat = extreme ? 17 : compact ? 20 : 22 + let messageSize: CGFloat = compact ? 13 : 14 + let textGap: CGFloat = extreme ? 3 : compact ? 4 : 6 + let buttonGap: CGFloat = extreme ? 8 : compact ? 12 : 16 + let buttonHeight: CGFloat = compact ? 44 : 50 + let available = max(1, bounds.height - (extreme ? 8 : 12)) + let textWidth = max(1, bounds.width - 36 - diameter - iconGap) + titleLabel.font = .systemFont(ofSize: titleSize, weight: .semibold) + let title = ceil(titleLabel.font.lineHeight) + let paragraph = NSMutableParagraphStyle() + paragraph.minimumLineHeight = messageSize * 1.5 + paragraph.maximumLineHeight = messageSize * 1.5 + let attributes: [NSAttributedString.Key: Any] = [ + .font: UIFont.systemFont(ofSize: messageSize), + .foregroundColor: UIColor(hex: 0x6A79A0), .paragraphStyle: paragraph + ] + messageLabel.attributedText = NSAttributedString(string: presentation.message, attributes: attributes) + let measured = (presentation.message as NSString).boundingRect( + with: CGSize(width: textWidth, height: .greatestFiniteMagnitude), + options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil).height + let hasNote = !extreme && DroneDockHomeMetric.usableText(presentation.actionNote) != nil + let note = hasNote ? ceil(noteLabel.font.lineHeight) : 0 + let noteGap: CGFloat = hasNote ? 6 : 0 + var lines = extreme || presentation.message.isEmpty ? 0 : 3 + var body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines))) + while max(diameter, title + (lines > 0 ? textGap + body : 0)) + buttonGap + buttonHeight + note + noteGap > available, + lines > 0 { + lines -= 1 + body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines))) + } + messageLabel.numberOfLines = max(1, lines) + messageLabel.isHidden = lines == 0 + noteLabel.isHidden = !hasNote + effectiveScale = compact ? 0.8 : 1 + headerHeight?.update(offset: max(diameter, title + (lines > 0 ? textGap + body : 0))) + iconSize?.update(offset: diameter) + iconBackground.layer.cornerRadius = diameter / 2 + textLeading?.update(offset: iconGap) + titleHeight?.update(offset: title) + messageTop?.update(offset: lines > 0 ? textGap : 0) + messageHeight?.update(offset: body) + actionTop?.update(offset: buttonGap) + actionHeight?.update(offset: buttonHeight) + noteTop?.update(offset: noteGap) + noteHeight?.update(offset: note) + if wasCompact != usesCompactLayout { actionButton.setNeedsUpdateConfiguration() } + } + + @objc private func primaryTapped() { + guard !isHidden, actionButton.isEnabled else { return } + onPrimaryAction?() + } +} diff --git a/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift b/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift index 760b139..75f1803 100644 --- a/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift +++ b/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift @@ -10,6 +10,8 @@ final class DroneDockTaskLiveView: UIView { var onRequest: (() -> Void)? /// 播放事件附带会话 ID,控制器据此丢弃离页或重连后的旧回调。 var onPlaybackEvent: ((DroneDockLivePlaybackEvent, UUID) -> Void)? + /// 只上报接收端启动、更新和停止等离散事件;不输出帧数据或解锁旧 SDK 日志。 + var onDiagnosticEvent: ((String, [String: Any]) -> Void)? private let playerLayer = AVPlayerLayer() private let titleLabel = DroneDockStyle.label(size: 15, weight: .medium, color: .white) @@ -31,12 +33,25 @@ final class DroneDockTaskLiveView: UIView { private var labelsCenterY: Constraint? private var isShowingCover = false private var coverURL: URL? + private var coverTitle = "拍摄已完成" private let rtcPlayer: any DroneDockLivePlaying private var requestedRTC: [DroneDockVolcLiveConfiguration] = [] private var activeRTC: [DroneDockVolcLiveConfiguration] = [] private var requestedSessionID: UUID? private var activeSessionID: UUID? + /// 图传区域实际显示与接收状态;不记录 RTC token 或播放地址。 + var diagnosticFields: [String: Any] { + ["playback_active": isPlaybackActive, "showing_cover": isShowingCover, + "cover_title": isShowingCover ? coverTitle : "", + "badge_visible": !sourceBadge.isHidden, "badge_title": sourceLabel.text ?? "", + "display_title": titleLabel.isHidden ? "" : titleLabel.text ?? "", + "display_message": messageLabel.isHidden ? "" : messageLabel.text ?? "", + "receiver_session": activeSessionID?.uuidString as Any? ?? NSNull(), + "receiver_rooms": activeRTC.map { ["role": $0.role, "room_id": $0.roomID] }, + "local_preview_active": player != nil] + } + /// 保留原任务页图传区域的访问标识,外部负责 16:9 约束。 override init(frame: CGRect) { rtcPlayer = DroneDockVolcLivePlayer() @@ -99,11 +114,12 @@ final class DroneDockTaskLiveView: UIView { updatePlayback() } - /// 录制结束后仅展示静态封面;隐藏实时标记和重试按钮,旧模型不能恢复播放。 - func showRecordingCover(_ show: Bool, url: URL?) { - guard isShowingCover != show || coverURL != url else { return } + /// 录制结束或中断回巢后展示静态封面;调用方提供本地标题,避免将中断任务显示为成功。 + func showRecordingCover(_ show: Bool, url: URL?, title: String = "拍摄已完成") { + guard isShowingCover != show || coverURL != url || coverTitle != title else { return } isShowingCover = show coverURL = url + coverTitle = title coverView.isHidden = !show coverShade.isHidden = !show coverIcon.isHidden = !show || url != nil @@ -112,13 +128,13 @@ final class DroneDockTaskLiveView: UIView { setPlaybackActive(false) coverView.contentMode = .scaleAspectFill coverView.kf.setImage(with: url) - titleLabel.text = "拍摄已完成" + titleLabel.text = title titleLabel.isHidden = false messageLabel.text = "拍摄封面 · 实时图传已结束" messageLabel.isHidden = false sourceBadge.isHidden = true requestButton.isHidden = true - accessibilityLabel = "拍摄已完成,拍摄封面,实时图传已结束" + accessibilityLabel = "\(title),拍摄封面,实时图传已结束" } private func setupUI() { @@ -209,9 +225,13 @@ final class DroneDockTaskLiveView: UIView { if !requestedRTC.isEmpty, let sessionID = requestedSessionID { releasePlayer() guard activeSessionID != sessionID || activeRTC != requestedRTC else { return } - if activeSessionID != sessionID { releaseRTC() } + let isNewSession = activeSessionID != sessionID + if isNewSession { releaseRTC() } activeSessionID = sessionID activeRTC = requestedRTC + onDiagnosticEvent?(isNewSession ? "live.receiver.start_requested" : "live.receiver.rooms_updated", [ + "receiver_session": sessionID.uuidString, + "rooms": requestedRTC.map { ["role": $0.role, "room_id": $0.roomID] }]) rtcPlayer.start(requestedRTC, in: rtcView) { [weak self] event in guard let self, self.activeSessionID == sessionID else { return } self.onPlaybackEvent?(event, sessionID) @@ -232,16 +252,20 @@ final class DroneDockTaskLiveView: UIView { activeURL = requestedURL playerLayer.player = queue queue.play() + onDiagnosticEvent?("live.local_preview.started", ["simulation": true]) } private func releaseRTC() { - guard activeSessionID != nil else { return } + guard let sessionID = activeSessionID else { return } + onDiagnosticEvent?("live.receiver.stopped", ["receiver_session": sessionID.uuidString, + "rooms": activeRTC.map { ["role": $0.role, "room_id": $0.roomID] }]) activeSessionID = nil activeRTC = [] rtcPlayer.stop() } private func releasePlayer() { + if player != nil { onDiagnosticEvent?("live.local_preview.stopped", ["simulation": true]) } player?.pause() looper?.disableLooping() player?.removeAllItems() diff --git a/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift b/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift index 5105d0e..18031c8 100644 --- a/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift +++ b/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift @@ -18,13 +18,13 @@ final class DroneDockTaskStatusView: UIView { private let iconView = UIImageView() private let titleLabel = DroneDockStyle.label(size: 22, weight: .semibold) private let messageLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary) - private let countdownLabel = DroneDockStyle.label(size: 13, weight: .medium, color: DroneDockStyle.primary) private let deviceLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary) private let actionRow = UIView() private let primaryButton = UIButton(type: .system) private let failureView = DroneDockTaskFailureView() private let completedView = DroneDockTaskCompletedView() private let shootingView = DroneDockTaskShootingView() + private let controlStateView = DroneDockTaskControlStateView() private var presentation: DroneDockTaskPresentation? private var countdownSeconds: Int? private var contentTop: Constraint? @@ -36,6 +36,35 @@ final class DroneDockTaskStatusView: UIView { private var messageHeight: Constraint? private var deviceHeight: Constraint? + /// 读取当前可见控件的实际文案和许可,用于对照录屏;不改变布局或任务状态。 + var diagnosticFields: [String: Any] { + func descendants(_ root: UIView) -> [UIView] { [root] + root.subviews.flatMap(descendants) } + func isVisible(_ view: UIView) -> Bool { + if view === self { return !view.isHidden } + return !view.isHidden && (view.superview.map(isVisible) ?? false) + } + let visible = descendants(self).filter(isVisible) + let buttonIDs = ["drone.task.remote.primary", "drone.task.remote.refresh", "drone.task.remote.failureRetry", + "drone.task.remote.shooting.indicator"] + let button = visible.compactMap { $0 as? UIButton }.first { buttonIDs.contains($0.accessibilityIdentifier ?? "") } + ?? visible.compactMap { $0 as? UIButton }.first + let label = visible.compactMap { $0 as? UILabel }.first { + ["drone.task.remote.statusTitle", "drone.task.remote.failureTitle"].contains($0.accessibilityIdentifier ?? "") + } + let message = visible.compactMap { $0 as? UILabel }.first { + ["drone.task.remote.statusMessage", "drone.task.remote.failureReason"].contains($0.accessibilityIdentifier ?? "") + } + let countdownState = countdownSeconds == nil ? "hidden" : countdownSeconds == 0 ? "zero" : "running" + return ["phase": presentation?.phase.rawValue ?? "uninitialized", + "title": label?.text ?? presentation?.title ?? "", + "message": message?.text ?? "", "message_visible": message != nil, + "action": presentation.map { String(describing: $0.action) } ?? "none", + "action_title": button?.configuration?.title ?? button?.title(for: .normal) ?? "", + "action_enabled": button?.isEnabled == true && isUserInteractionEnabled, + "action_loading": visible.compactMap { $0 as? UIActivityIndicatorView }.contains { $0.isAnimating }, + "interactive": isUserInteractionEnabled, "countdown": countdownState] + } + /// 创建固定状态槽,完成、失败与进行中使用各自的内容布局。 override init(frame: CGRect) { super.init(frame: frame) @@ -52,20 +81,29 @@ final class DroneDockTaskStatusView: UIView { } /// 更新真实状态与动作许可;刷新期间保留内容,只暂时禁用主操作。 - func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false) { + func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false, isPrimaryActionLoading: Bool = false) { self.presentation = presentation updateCountdown(seconds: presentation.countdownSeconds) let isFailure = presentation.phase == .failed let isCompleted = [.postShootUploading, .completed].contains(presentation.phase) let isShooting = presentation.phase == .shooting - contentStack.isHidden = isFailure || isCompleted || isShooting + let isControlState = [.paused, .returning, .returned].contains(presentation.phase) + contentStack.isHidden = isFailure || isCompleted || isShooting || isControlState failureView.isHidden = !isFailure completedView.isHidden = !isCompleted shootingView.isHidden = !isShooting + controlStateView.isHidden = !isControlState completedView.setIdentifiersActive(isCompleted) shootingView.setIdentifiersActive(isShooting) - titleLabel.accessibilityIdentifier = isCompleted || isShooting ? nil : "drone.task.remote.statusTitle" - messageLabel.accessibilityIdentifier = isCompleted || isShooting ? nil : "drone.task.remote.statusMessage" + controlStateView.setIdentifiersActive(isControlState) + titleLabel.accessibilityIdentifier = isCompleted || isShooting || isControlState ? nil : "drone.task.remote.statusTitle" + messageLabel.accessibilityIdentifier = isCompleted || isShooting || isControlState ? nil : "drone.task.remote.statusMessage" + if isControlState { + primaryButton.accessibilityIdentifier = nil + controlStateView.apply(presentation, isRefreshing: isRefreshing, isPrimaryActionLoading: isPrimaryActionLoading) + setNeedsLayout() + return + } if isShooting { primaryButton.accessibilityIdentifier = nil shootingView.apply(presentation) @@ -91,7 +129,7 @@ final class DroneDockTaskStatusView: UIView { iconView.tintColor = style.color let actionTitle = DroneDockHomeMetric.usableText(presentation.actionTitle) primaryButton.isHidden = presentation.action == .none || actionTitle == nil - primaryButton.setTitle(actionTitle, for: .normal) + updatePrimaryButtonTitle() primaryButton.isEnabled = presentation.isActionEnabled && !primaryButton.isHidden && !isRefreshing primaryButton.backgroundColor = primaryButton.isEnabled ? DroneDockStyle.primary : DroneDockStyle.primary.withAlphaComponent(0.35) @@ -100,19 +138,41 @@ final class DroneDockTaskStatusView: UIView { setNeedsLayout() } - /// 只刷新已到达阶段的剩余秒数,不变更主操作、服务端阶段或执行任何回调。 + /// 只刷新开拍按钮中的剩余秒数,不变更操作许可、服务端阶段或执行任何回调。 func updateCountdown(seconds: Int?) { - let value = presentation?.phase == .ready ? seconds.map { max(0, $0) } : nil + let value = presentation?.phase == .ready && presentation?.action == .start + ? seconds.map { max(0, $0) } : nil guard value != countdownSeconds else { return } - let visibilityChanged = (value == nil) != (countdownSeconds == nil) countdownSeconds = value - countdownLabel.text = value.map { "自动开拍倒计时:\($0) 秒" } - countdownLabel.isHidden = value == nil - if visibilityChanged { setNeedsLayout() } + updatePrimaryButtonTitle() + } + + private func updatePrimaryButtonTitle() { + guard let presentation else { return } + let title = DroneDockHomeMetric.usableText(presentation.actionTitle) + let displayedTitle: String? + if presentation.phase == .ready, presentation.action == .start, + let title, let countdownSeconds { + displayedTitle = "\(title)(\(countdownSeconds)s)" + } else { + displayedTitle = title + } + // 秒数直接替换,避免系统按钮的标题过渡暂时保留旧数字。 + UIView.performWithoutAnimation { + primaryButton.setTitle(displayedTitle, for: .normal) + primaryButton.layoutIfNeeded() + } } /// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。 override func layoutSubviews() { + if let phase = presentation?.phase, [.paused, .returning, .returned].contains(phase) { + super.layoutSubviews() + controlStateView.layoutIfNeeded() + effectiveScale = controlStateView.effectiveScale + usesCompactLayout = controlStateView.usesCompactLayout + return + } if presentation?.phase == .shooting { super.layoutSubviews() shootingView.layoutIfNeeded() @@ -140,6 +200,9 @@ final class DroneDockTaskStatusView: UIView { private func setupUI() { backgroundColor = .white + addSubview(controlStateView) + controlStateView.isHidden = true + controlStateView.onPrimaryAction = { [weak self] in self?.onPrimaryAction?() } addSubview(shootingView) shootingView.isHidden = true addSubview(completedView) @@ -155,7 +218,6 @@ final class DroneDockTaskStatusView: UIView { addSubview(contentStack) contentStack.addArrangedSubview(titleRow) contentStack.addArrangedSubview(messageLabel) - contentStack.addArrangedSubview(countdownLabel) contentStack.addArrangedSubview(deviceLabel) contentStack.addArrangedSubview(actionRow) titleRow.addSubview(iconView) @@ -168,16 +230,12 @@ final class DroneDockTaskStatusView: UIView { messageLabel.numberOfLines = 3 messageLabel.lineBreakMode = .byTruncatingTail messageLabel.accessibilityIdentifier = "drone.task.remote.statusMessage" - countdownLabel.font = .monospacedDigitSystemFont(ofSize: 13, weight: .medium) - countdownLabel.numberOfLines = 1 - countdownLabel.isHidden = true - countdownLabel.accessibilityIdentifier = "drone.task.remote.countdown" deviceLabel.numberOfLines = 1 deviceLabel.lineBreakMode = .byTruncatingTail deviceLabel.accessibilityIdentifier = "drone.task.remote.deviceStatus" actionRow.addSubview(primaryButton) primaryButton.layer.cornerRadius = 9 - primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold) + primaryButton.titleLabel?.font = .monospacedDigitSystemFont(ofSize: 15, weight: .semibold) primaryButton.titleLabel?.lineBreakMode = .byTruncatingTail primaryButton.setTitleColor(.white, for: .normal) primaryButton.setTitleColor(.white.withAlphaComponent(0.9), for: .disabled) @@ -185,6 +243,7 @@ final class DroneDockTaskStatusView: UIView { } private func setupConstraints() { + controlStateView.snp.makeConstraints { $0.edges.equalToSuperview() } shootingView.snp.makeConstraints { $0.edges.equalToSuperview() } completedView.snp.makeConstraints { $0.edges.equalToSuperview() } failureView.snp.makeConstraints { make in make.edges.equalToSuperview() } @@ -203,7 +262,6 @@ final class DroneDockTaskStatusView: UIView { make.trailing.centerY.equalToSuperview() } messageLabel.snp.makeConstraints { make in messageHeight = make.height.equalTo(34).priority(999).constraint } - countdownLabel.snp.makeConstraints { make in make.height.equalTo(ceil(countdownLabel.font.lineHeight)).priority(999) } deviceLabel.snp.makeConstraints { make in deviceHeight = make.height.equalTo(16).priority(999).constraint } actionRow.snp.makeConstraints { make in make.height.equalTo(44) } primaryButton.snp.makeConstraints { make in @@ -214,9 +272,8 @@ final class DroneDockTaskStatusView: UIView { private func updateContentLayout() { guard let presentation, bounds.width > 0, bounds.height > 0 else { return } let isExtreme = bounds.height < 120 - let hasCountdown = countdownSeconds != nil let horizontalInset: CGFloat = isExtreme ? 12 : 16 - let verticalInset: CGFloat = isExtreme ? (hasCountdown ? 4 : 6) : 12 + let verticalInset: CGFloat = isExtreme ? 6 : 12 let width = max(1, bounds.width - horizontalInset * 2) let availableHeight = max(1, bounds.height - verticalInset * 2) let message = DroneDockHomeMetric.usableText(presentation.message) @@ -228,20 +285,18 @@ final class DroneDockTaskStatusView: UIView { width: width - 46, lines: 2)) let naturalMessage = hasMessage ? Self.textHeight(message, font: .systemFont(ofSize: 14), width: width, lines: 3) : 0 let naturalDevice = hasDevice ? UIFont.systemFont(ofSize: 12).lineHeight : 0 - let countdownTextHeight = hasCountdown ? ceil(countdownLabel.font.lineHeight) : 0 - let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0) + (hasCountdown ? 1 : 0)) * 10 - let naturalHeight = naturalTitle + naturalMessage + countdownTextHeight + naturalDevice + 44 + naturalGaps + let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0)) * 10 + let naturalHeight = naturalTitle + naturalMessage + naturalDevice + 44 + naturalGaps effectiveScale = min(1, max(0.8, availableHeight / max(1, naturalHeight))) usesCompactLayout = bounds.height < 190 || naturalHeight * effectiveScale > availableHeight // 先收紧图标和间距;只有不足九成空间时才缩小文字。 let fontScale: CGFloat = effectiveScale >= 0.9 ? 1 : effectiveScale / 0.9 - titleLabel.font = .systemFont(ofSize: isExtreme && hasCountdown ? 17 : max(17, 22 * fontScale), weight: .semibold) + titleLabel.font = .systemFont(ofSize: max(17, 22 * fontScale), weight: .semibold) messageLabel.font = .systemFont(ofSize: max(12, 14 * fontScale)) deviceLabel.font = .systemFont(ofSize: 12) let icon: CGFloat = isExtreme ? 20 : usesCompactLayout ? 24 : 36 * effectiveScale - let gap: CGFloat = isExtreme ? (hasCountdown ? 2 : 4) - : hasCountdown && usesCompactLayout ? 6 : max(4, 10 * effectiveScale) + let gap: CGFloat = isExtreme ? 4 : max(4, 10 * effectiveScale) let titleGap: CGFloat = usesCompactLayout ? 8 : 10 * effectiveScale titleLabel.numberOfLines = usesCompactLayout ? 1 : 2 messageLabel.numberOfLines = usesCompactLayout ? 2 : 3 @@ -255,8 +310,8 @@ final class DroneDockTaskStatusView: UIView { width: width, lines: messageLineCount) let deviceTextHeight = deviceLabel.isHidden ? 0 : ceil(deviceLabel.font.lineHeight) var contentHeight: CGFloat { - titleHeight + bodyHeight + countdownTextHeight + deviceTextHeight + 44 - + CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1) + (hasCountdown ? 1 : 0)) * gap + titleHeight + bodyHeight + deviceTextHeight + 44 + + CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1)) * gap } while contentHeight > availableHeight && messageLineCount > 1 && !messageLabel.isHidden { messageLineCount -= 1 @@ -301,6 +356,7 @@ final class DroneDockTaskStatusView: UIView { case .postShootUploadFailed: ("exclamationmark.circle.fill", DroneDockStyle.warning) case .paused: ("pause.circle.fill", DroneDockStyle.warning) case .returning: ("arrow.uturn.backward.circle.fill", DroneDockStyle.warning) + case .returned: ("house.circle.fill", DroneDockStyle.warning) case .completed: ("checkmark.circle.fill", DroneDockStyle.success) case .failed: ("xmark.circle.fill", UIColor(hex: 0xD46B62)) case .blocked, .readError: ("exclamationmark.circle.fill", DroneDockStyle.warning) diff --git a/suixinkan/UI/DroneDock/DroneShootingTaskViews.swift b/suixinkan/UI/DroneDock/DroneShootingTaskViews.swift index 16319bf..6fca35b 100644 --- a/suixinkan/UI/DroneDock/DroneShootingTaskViews.swift +++ b/suixinkan/UI/DroneDock/DroneShootingTaskViews.swift @@ -279,6 +279,14 @@ final class DroneShootingTaskSafetyButton: UIButton { private let controlTitleLabel = DroneDockStyle.label(size: 15, weight: .semibold) private let controlSubtitleLabel = DroneDockStyle.label(size: 10) private let controlIconView: UIImageView + private let activityIndicator = UIActivityIndicatorView(style: .medium) + + /// 输出实际呈现的控件状态,供页面按变化记录;不推导业务许可。 + var diagnosticFields: [String: Any] { + ["title": controlTitleLabel.text ?? "", "subtitle": controlSubtitleLabel.text ?? "", + "enabled": isEnabled, "loading": activityIndicator.isAnimating, + "accessibility_value": accessibilityValue ?? ""] + } /// 创建暂停或返航按钮;返回状态只由 ViewModel 决定。 init(symbol: String, color: UIColor, filled: Bool) { @@ -292,6 +300,9 @@ final class DroneShootingTaskSafetyButton: UIButton { controlSubtitleLabel.textColor = filled ? UIColor.white.withAlphaComponent(0.85) : DroneDockStyle.secondary controlIconView.tintColor = filled ? .white : color controlIconView.contentMode = .scaleAspectFit + activityIndicator.color = filled ? .white : color + activityIndicator.hidesWhenStopped = true + activityIndicator.isUserInteractionEnabled = false let titles = UIStackView(arrangedSubviews: [controlTitleLabel, controlSubtitleLabel]) titles.axis = .vertical titles.spacing = 3 @@ -308,6 +319,11 @@ final class DroneShootingTaskSafetyButton: UIButton { make.trailing.lessThanOrEqualToSuperview().offset(-9) } controlIconView.snp.makeConstraints { make in make.size.equalTo(27) } + addSubview(activityIndicator) + activityIndicator.snp.makeConstraints { make in + make.center.equalTo(controlIconView) + make.size.equalTo(27) + } controlTitleLabel.adjustsFontSizeToFitWidth = true controlTitleLabel.minimumScaleFactor = 0.8 controlSubtitleLabel.adjustsFontSizeToFitWidth = true @@ -317,14 +333,18 @@ final class DroneShootingTaskSafetyButton: UIButton { @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } - /// 应用语义明确的按钮标题、辅助说明及防重复点击状态。 - func apply(title: String, subtitle: String, enabled: Bool) { + /// 应用独立操作许可和加载状态;加载时仅替换本按钮图标,不改变布局或其他按钮。 + func apply(title: String, subtitle: String, enabled: Bool, isLoading: Bool = false) { controlTitleLabel.text = title controlSubtitleLabel.text = subtitle - isEnabled = enabled - alpha = enabled ? 1 : 0.42 + isEnabled = enabled && !isLoading + alpha = enabled || isLoading ? 1 : 0.42 + controlIconView.alpha = isLoading ? 0 : 1 + if isLoading { activityIndicator.startAnimating() } + else { activityIndicator.stopAnimating() } + activityIndicator.accessibilityIdentifier = accessibilityIdentifier.map { "\($0).loading" } accessibilityLabel = title - accessibilityValue = subtitle + accessibilityValue = isLoading ? "处理中,\(subtitle)" : subtitle } /// 切换同一位置的暂停/继续或返航/取消图标,不改变按钮布局。 diff --git a/suixinkanTests/APIConsoleFormatTests.swift b/suixinkanTests/APIConsoleFormatTests.swift index 7f339d1..9ef9acb 100644 --- a/suixinkanTests/APIConsoleFormatTests.swift +++ b/suixinkanTests/APIConsoleFormatTests.swift @@ -2,7 +2,7 @@ import Foundation import XCTest @testable import suixinkan -/// 验证控制台只输出路径、入参和返回,保留原始 JSON 类型及长内容。 +/// 验证普通接口保持简洁格式,仅明确标识的任务关键事件可输出诊断字段。 final class APIConsoleFormatTests: XCTestCase { func testReadableJSONContainsOnlyPathParamsAndResponse() throws { let text = APIConsoleFormat.message(path: "/api/app/airport/shooting", params: ["id": "501", "live_battery": "0"], @@ -53,6 +53,41 @@ final class APIConsoleFormatTests: XCTestCase { XCTAssertNil(APIConsoleFormat.render("plain diagnostic")) } + func testExplicitDroneTaskEventPreservesDiagnosticFields() throws { + let fields: [String: Any] = ["diagnostic": "drone_task", "event": "snapshot.applied", + "task_id": 8, "session_id": "SESSION", "sequence": 3, "elapsed_ms": 1250, + "timestamp": "2026-11-04T10:11:12.123+08:00", "phase": "arrived_pending_start", + "can_pause": true, "pending_command": NSNull()] + let rendered = try XCTUnwrap(APIConsoleFormat.render(DroneDockDiagnostics.json(fields))) + let value = try object(rendered) + XCTAssertTrue(NSDictionary(dictionary: value).isEqual(to: fields)) + XCTAssertNil(value["path"]) + XCTAssertNil(value["response"]) + } + + func testUnrelatedOrIncompleteTaskMarkersDoNotOpenDiagnosticOutput() { + let fields: [[String: Any]] = [ + ["event": "snapshot.applied", "task_id": 8], + ["diagnostic": "rtc", "event": "snapshot.applied", "task_id": 8], + ["diagnostic": "drone_task", "task_id": 8], + ["diagnostic": "drone_task", "event": "", "task_id": 8], + ["diagnostic": "drone_task", "event": " \n\t", "task_id": 8], + ["diagnostic": "drone_task", "event": 123, "task_id": 8] + ] + for value in fields { + XCTAssertNil(APIConsoleFormat.render(DroneDockDiagnostics.json(value))) + } + } + + func testBackendTaskMarkerRemainsInsideOrdinaryAPIResponse() throws { + let body: [String: Any] = ["diagnostic": "drone_task", "event": "backend.event", "code": 100000] + let raw = DroneDockDiagnostics.json(["event": "response.received", "path": "/api/read", + "request_params": ["id": 8], "body": body]) + let value = try object(XCTUnwrap(APIConsoleFormat.render(raw))) + XCTAssertEqual(Set(value.keys), ["path", "params", "response"]) + XCTAssertTrue(NSDictionary(dictionary: try XCTUnwrap(value["response"] as? [String: Any])).isEqual(to: body)) + } + func testLongJSONStringsArraysAndTextAreNotTruncatedOrStringified() throws { let text = String(repeating: "长字段中文😀\n", count: 1000) + "END-OF-BODY" for payload: Any in [["detail": text], [1, 2, 3], NSNull(), "网关异常"] { diff --git a/suixinkanTests/DroneDockArrivalCountdownTests.swift b/suixinkanTests/DroneDockArrivalCountdownTests.swift index 7f0a3b7..5df14c0 100644 --- a/suixinkanTests/DroneDockArrivalCountdownTests.swift +++ b/suixinkanTests/DroneDockArrivalCountdownTests.swift @@ -139,7 +139,7 @@ final class DroneDockArrivalCountdownTests: XCTestCase { let fixture = try makeFixture() await fixture.model.refresh() fixture.clock.advance(by: .seconds(6)) - XCTAssertEqual(fixture.model.applyTaskSnapshot(try snapshot(phase: "paused", version: 2)), .applied) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try snapshot(phase: "manual_paused", version: 2)), .applied) XCTAssertNil(fixture.model.countdownRemainingSeconds) XCTAssertNil(fixture.model.presentation.countdownSeconds) fixture.clock.advance(by: .seconds(5)) @@ -163,15 +163,17 @@ final class DroneDockArrivalCountdownTests: XCTestCase { XCTAssertEqual(fixture.model.countdownRemainingSeconds, 20) } - /// 未允许开拍的“到达”文案、未知阶段与错误任务身份不能创建倒计时。 - func testBlockedUnknownAndMismatchedSnapshotsDoNotStartCountdown() async throws { + /// 明确到达即显示倒计时,开拍门禁独立;未知阶段和错误身份不能显示或创建新倒计时。 + func testDeniedStartGateKeepsArrivalCountdownButUnknownAndMismatchedStatesDoNot() async throws { let fixture = try makeFixture(response: snapshot(phase: "going_to_spot")) await fixture.model.refresh() XCTAssertNil(fixture.model.countdownRemainingSeconds) var denied = payload(version: 2) denied["execute_gate"] = ["can_execute": false, "primary_action": "blocked"] XCTAssertEqual(fixture.model.applyTaskSnapshot(try DroneDockShootingTaskTestData.decode(denied)), .applied) - XCTAssertNil(fixture.model.countdownRemainingSeconds) + XCTAssertEqual(fixture.model.presentation.phase, .ready) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 30) + XCTAssertFalse(fixture.model.canStartShooting) XCTAssertEqual(fixture.model.applyTaskSnapshot(try snapshot(phase: "future_phase", version: 3)), .applied) XCTAssertNil(fixture.model.countdownRemainingSeconds) var wrong = payload(version: 4) @@ -216,7 +218,14 @@ final class DroneDockArrivalCountdownTests: XCTestCase { value["order_flight_task"] = ["id": 501, "status": 20, "order_number": "TEST-TASK-PAGE-001", "scenic_id": 128] value["ui"] = ["phase": phase, "title": "本地模拟:任务阶段", "message": "未连接真实无人机"] value["execute_gate"] = ["can_execute": phase == "arrived_pending_start", "primary_action": phase == "arrived_pending_start" ? "start_shoot" : "blocked"] - if let batch { value["execution_batch"] = batch } + if let batch { + value["execution_batch"] = batch + value["flight_control"] = DroneDockShootingTaskTestData.flightControl( + state: phase == "manual_paused" ? "paused" : "executing", batch: batch, + canPause: phase != "manual_paused", canResume: phase == "manual_paused", + resumePhase: phase == "manual_paused" || phase == "arrived_pending_start" ? "arrived_pending_start" : nil, + pauseReason: phase == "manual_paused" ? "manual" : phase == "arrived_pending_start" ? "arrival_wait" : nil) + } if let version { value["state_version"] = version } value["snapshot_kind"] = "full" return value diff --git a/suixinkanTests/DroneDockArrivalCountdownViewTests.swift b/suixinkanTests/DroneDockArrivalCountdownViewTests.swift index 68c3677..e76b9f8 100644 --- a/suixinkanTests/DroneDockArrivalCountdownViewTests.swift +++ b/suixinkanTests/DroneDockArrivalCountdownViewTests.swift @@ -6,33 +6,37 @@ import XCTest @MainActor final class DroneDockArrivalCountdownViewTests: XCTestCase { /// 每秒只更新显示,到零不额外读取或开拍;后端明确拍摄中后才切换阶段。 - func testCountdownOnlyUpdatesLabelAndWaitsForBackendShooting() async throws { + func testCountdownOnlyUpdatesStartButtonAndWaitsForBackendShooting() async throws { let fixture = try makeFixture() defer { fixture.close() } try await settle(fixture.window) { fixture.pulse.pendingCount == 1 } - let label = try countdownLabel(in: fixture.controller.view) - XCTAssertEqual(label.text, "自动开拍倒计时:30 秒") let action = try XCTUnwrap(find(in: fixture.controller.view, id: "drone.task.remote.primary") as? UIButton) + XCTAssertNil(find(in: fixture.controller.view, id: "drone.task.remote.countdown")) + XCTAssertEqual(action.title(for: .normal), "开始拍摄(30s)") XCTAssertTrue(action.isEnabled) let initialFrame = action.convert(action.bounds, to: fixture.controller.view) - try await capture(fixture.window, action: action, name: "App本地到达倒计时30秒(隔离替身)") + try await capture(fixture.window, action: action, expectedTitle: "开始拍摄(30s)", name: "App本地到达倒计时30秒(隔离替身)") fixture.clock.advance(seconds: 1) fixture.pulse.fire() - try await settle(fixture.window) { label.text == "自动开拍倒计时:29 秒" && fixture.pulse.pendingCount == 1 } + try await settle(fixture.window) { action.title(for: .normal) == "开始拍摄(29s)" && fixture.pulse.pendingCount == 1 } + XCTAssertTrue(find(in: fixture.controller.view, id: "drone.task.remote.primary") === action) XCTAssertEqual(action.convert(action.bounds, to: fixture.controller.view), initialFrame) fixture.clock.advance(seconds: 29.5) fixture.pulse.fire() - try await settle(fixture.window) { label.text == "自动开拍倒计时:0 秒" && fixture.pulse.pendingCount == 0 } + try await settle(fixture.window) { action.title(for: .normal) == "开始拍摄(0s)" && fixture.pulse.pendingCount == 0 } + XCTAssertTrue(find(in: fixture.controller.view, id: "drone.task.remote.primary") === action) + XCTAssertEqual(action.convert(action.bounds, to: fixture.controller.view), initialFrame) XCTAssertEqual(fixture.model.presentation.phase, .ready) XCTAssertEqual(fixture.service.requests.count, 1) XCTAssertEqual(fixture.start.count, 0, "本地倒数到零不能下发开拍") XCTAssertTrue(action.isEnabled, "秒数不会改变后端开拍门禁") - try await capture(fixture.window, action: action, name: "App本地倒计时0秒仍等待后端(隔离替身)") + try await capture(fixture.window, action: action, expectedTitle: "开始拍摄(0s)", name: "App本地倒计时0秒仍等待后端(隔离替身)") fixture.service.result = .success(try snapshot(phase: "shooting", version: 2)) let item = try XCTUnwrap(fixture.controller.navigationItem.rightBarButtonItem) _ = UIApplication.shared.sendAction(try XCTUnwrap(item.action), to: item.target, from: item, for: nil) - try await settle(fixture.window) { fixture.model.presentation.phase == .shooting && label.isHidden } - XCTAssertNil(label.text) + try await settle(fixture.window) { fixture.model.presentation.phase == .shooting } + XCTAssertNil(find(in: fixture.controller.view, id: "drone.task.remote.countdown")) + XCTAssertFalse(action.currentTitle?.contains("s)") == true, "后端拍摄中必须清除旧倒计时文案") XCTAssertNil(fixture.model.countdownRemainingSeconds) XCTAssertEqual(fixture.service.requests.count, 2) XCTAssertEqual(fixture.start.count, 0) @@ -45,15 +49,18 @@ final class DroneDockArrivalCountdownViewTests: XCTestCase { let fixture = try makeFixture() defer { fixture.close() } try await settle(fixture.window) { fixture.pulse.pendingCount == 1 } - let label = try countdownLabel(in: fixture.controller.view) + let action = try XCTUnwrap(find(in: fixture.controller.view, id: "drone.task.remote.primary") as? UIButton) if elapsed > 0 { fixture.clock.advance(seconds: elapsed) fixture.pulse.fire() - try await settle(fixture.window) { label.text == "自动开拍倒计时:\(30 - Int(elapsed)) 秒" } + try await settle(fixture.window) { action.title(for: .normal) == "开始拍摄(\(30 - Int(elapsed))s)" } } - let action = try XCTUnwrap(find(in: fixture.controller.view, id: "drone.task.remote.primary") as? UIButton) - XCTAssertEqual(action.title(for: .normal), "开始拍摄") + XCTAssertEqual(action.title(for: .normal), "开始拍摄(\(30 - Int(elapsed))s)") + XCTAssertNil(find(in: fixture.controller.view, id: "drone.task.remote.countdown")) XCTAssertTrue(action.isEnabled) + let center = action.convert(CGPoint(x: action.bounds.midX, y: action.bounds.midY), to: fixture.controller.view) + let hit = fixture.controller.view.hitTest(center, with: nil) + XCTAssertTrue(hit === action || hit?.isDescendant(of: action) == true) XCTAssertEqual(fixture.start.count, 0) action.sendActions(for: .touchUpInside) action.sendActions(for: .touchUpInside) @@ -69,19 +76,23 @@ final class DroneDockArrivalCountdownViewTests: XCTestCase { let fixture = try makeFixture() defer { fixture.close() } try await settle(fixture.window) { fixture.pulse.pendingCount == 1 } - let label = try countdownLabel(in: fixture.controller.view) + let action = try XCTUnwrap(find(in: fixture.controller.view, id: "drone.task.remote.primary") as? UIButton) + let initialFrame = action.convert(action.bounds, to: fixture.controller.view) fixture.clock.advance(seconds: 8) NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil) try await settle(fixture.window) { fixture.pulse.pendingCount == 0 } XCTAssertEqual(fixture.model.countdownRemainingSeconds, 22) fixture.clock.advance(seconds: 12) NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil) - try await settle(fixture.window) { fixture.service.requests.count == 2 && label.text == "自动开拍倒计时:10 秒" && fixture.pulse.pendingCount == 1 } + try await settle(fixture.window) { fixture.service.requests.count == 2 && action.title(for: .normal) == "开始拍摄(10s)" && fixture.pulse.pendingCount == 1 } fixture.controller.viewWillDisappear(false) try await settle(fixture.window) { fixture.pulse.pendingCount == 0 } fixture.clock.advance(seconds: 15) fixture.controller.viewDidAppear(false) - try await settle(fixture.window) { fixture.service.requests.count == 3 && label.text == "自动开拍倒计时:0 秒" } + try await settle(fixture.window) { fixture.service.requests.count == 3 && action.title(for: .normal) == "开始拍摄(0s)" } + XCTAssertTrue(find(in: fixture.controller.view, id: "drone.task.remote.primary") === action) + XCTAssertEqual(action.convert(action.bounds, to: fixture.controller.view), initialFrame) + XCTAssertNil(find(in: fixture.controller.view, id: "drone.task.remote.countdown")) XCTAssertEqual(fixture.pulse.pendingCount, 0) XCTAssertEqual(fixture.start.count, 0) XCTAssertEqual(fixture.model.presentation.phase, .ready) @@ -111,16 +122,14 @@ final class DroneDockArrivalCountdownViewTests: XCTestCase { try DroneDockShootingTaskTestData.response(changes: [ "task": ["id": 501, "status": 20], "order_flight_task": ["id": 501, "status": 20], "execution_batch": 100, "state_version": version, "snapshot_kind": "full", + "flight_control": DroneDockShootingTaskTestData.flightControl(batch: 100, resumePhase: phase, + pauseReason: phase == "arrived_pending_start" ? "arrival_wait" : nil), "ui": ["phase": phase, "title": phase == "shooting" ? "正在拍摄" : "无人机已到达", "message": "本地模拟:未连接真实设备"], "execute_gate": ["can_execute": phase == "arrived_pending_start", "primary_action": "start_shoot"] ]) } - private func countdownLabel(in root: UIView) throws -> UILabel { - try XCTUnwrap(find(in: root, id: "drone.task.remote.countdown") as? UILabel) - } - private func find(in root: UIView, id: String) -> UIView? { if root.accessibilityIdentifier == id { return root } return root.subviews.lazy.compactMap { self.find(in: $0, id: id) }.first @@ -137,10 +146,14 @@ final class DroneDockArrivalCountdownViewTests: XCTestCase { throw NSError(domain: "CountdownPage", code: 1) } - private func capture(_ window: UIWindow, action: UIButton, name: String) async throws { + private func capture(_ window: UIWindow, action: UIButton, expectedTitle: String, name: String) async throws { try await Task.sleep(for: .milliseconds(300)) window.layoutIfNeeded() - XCTAssertEqual(action.titleLabel?.text, "开始拍摄", "数字变化后按钮实际文字仍保持手动开拍") + let label = try XCTUnwrap(action.titleLabel) + XCTAssertEqual(label.text, expectedTitle, "按钮实际渲染文字包含完整剩余秒数") + let textSize = (expectedTitle as NSString).size(withAttributes: [.font: label.font as Any]) + XCTAssertGreaterThanOrEqual(label.bounds.width + 1, ceil(textSize.width), "按钮标题不能裁切秒数") + XCTAssertGreaterThanOrEqual(action.bounds.height, 44) let attachment = XCTAttachment(image: UIGraphicsImageRenderer(bounds: window.bounds).image { _ in window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) }) diff --git a/suixinkanTests/DroneDockCommandAPITests.swift b/suixinkanTests/DroneDockCommandAPITests.swift index dbfb3a6..fc1ffce 100644 --- a/suixinkanTests/DroneDockCommandAPITests.swift +++ b/suixinkanTests/DroneDockCommandAPITests.swift @@ -6,12 +6,12 @@ import XCTest @MainActor final class DroneDockCommandAPITests: XCTestCase { /// 四种操作都只发一次带鉴权 POST,任务身份使用 id,不传飞机或机场标识。 - func testEachCommandSendsOnlyTaskIDAndCommand() async throws { + func testEachCommandSendsTaskIDCommandAndIdempotencyKey() async throws { for command in DroneDockSafetyCommand.allCases { let session = MockURLSession(responses: [try envelope(data: payload(command: command))]) let client = APIClient(environment: .testing, session: session) client.bindAuthTokenProvider { "command-test-token" } - let response = try await DroneDockCommandAPI(client: client).sendCommand(taskID: 501, command: command) + let response = try await DroneDockCommandAPI(client: client).sendCommand(taskID: 501, command: command, clientRequestID: "local-command-request") XCTAssertEqual(session.requests.count, 1) let request = try XCTUnwrap(session.requests.first) @@ -20,12 +20,21 @@ final class DroneDockCommandAPITests: XCTestCase { XCTAssertNil(request.url?.query) XCTAssertEqual(request.value(forHTTPHeaderField: "token"), "command-test-token") let body = try XCTUnwrap(JSONSerialization.jsonObject(with: XCTUnwrap(request.httpBody)) as? [String: Any]) - XCTAssertEqual(Set(body.keys), ["id", "command"]) + XCTAssertEqual(Set(body.keys), ["id", "command", "client_request_id"]) + XCTAssertEqual(body["client_request_id"] as? String, "local-command-request") XCTAssertEqual(body["id"] as? Int, 501) XCTAssertEqual(body["command"] as? String, command.rawValue) XCTAssertEqual(response.orderFlightTaskID, 501) XCTAssertEqual(response.command, command.rawValue) + XCTAssertEqual(response.commandID, "local-command-1") + XCTAssertEqual(response.clientRequestID, "local-command-request") + XCTAssertEqual(response.pendingCommand?.commandID, response.commandID) + XCTAssertEqual(response.pendingCommand?.status, "pending") XCTAssertEqual(response.airportSN, "LOCAL-MOCK-AIRPORT-501") + XCTAssertEqual(response.accepted, true) + XCTAssertEqual(response.deviceConfirmed, false) + XCTAssertEqual(response.executionBatch, 100) + XCTAssertEqual(response.stateVersion, 8) XCTAssertEqual(response.metrics.map(\.key), ["battery", "satellite"]) } } @@ -36,11 +45,15 @@ final class DroneDockCommandAPITests: XCTestCase { let api = DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) for taskID in [0, -1] { do { - _ = try await api.sendCommand(taskID: taskID, command: .pause) + _ = try await api.sendCommand(taskID: taskID, command: .pause, clientRequestID: "local-command-request") XCTFail("无效任务 ID 不应提交") } catch let APIError.networkFailed(message) { XCTAssertFalse(message.isEmpty) } } - let pending = Task { @MainActor in try await api.sendCommand(taskID: 501, command: .returnHome) } + do { + _ = try await api.sendCommand(taskID: 501, command: .pause, clientRequestID: "") + XCTFail("缺少幂等键的设备指令不应提交") + } catch let APIError.networkFailed(message) { XCTAssertFalse(message.isEmpty) } + let pending = Task { @MainActor in try await api.sendCommand(taskID: 501, command: .returnHome, clientRequestID: "local-command-request") } pending.cancel() do { _ = try await pending.value @@ -56,7 +69,7 @@ final class DroneDockCommandAPITests: XCTestCase { message: "模拟:任务未锁定飞机,请先召唤无人机")]) do { _ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) - .sendCommand(taskID: 501, command: .pause) + .sendCommand(taskID: 501, command: .pause, clientRequestID: "local-command-request") XCTFail("拒绝不能转换为成功") } catch let APIError.serverCode(code, message) { XCTAssertEqual(code, 100099) @@ -71,7 +84,7 @@ final class DroneDockCommandAPITests: XCTestCase { let session = MockURLSession(results: [.failure(URLError(.timedOut))]) do { _ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) - .sendCommand(taskID: 501, command: .returnHome) + .sendCommand(taskID: 501, command: .returnHome, clientRequestID: "local-command-request") XCTFail("超时不能伪造成功") } catch let APIError.networkFailed(message) { XCTAssertFalse(message.isEmpty) } XCTAssertEqual(session.requests.count, 1) @@ -82,7 +95,7 @@ final class DroneDockCommandAPITests: XCTestCase { let session = MockURLSession(responses: [try envelope(data: payload())], statusCode: 503) do { _ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) - .sendCommand(taskID: 501, command: .pause) + .sendCommand(taskID: 501, command: .pause, clientRequestID: "local-command-request") XCTFail("HTTP 失败不能算成功") } catch let APIError.httpStatus(code, _) { XCTAssertEqual(code, 503) } XCTAssertEqual(session.requests.count, 1) @@ -94,13 +107,14 @@ final class DroneDockCommandAPITests: XCTestCase { ["order_flight_task_id": 502], ["order_flight_task_id": 0], ["order_flight_task_id": -1], ["order_flight_task_id": "501"], ["order_flight_task_id": true], ["order_flight_task_id": NSNull()], - ["command": "return_home"], ["command": "unknown"], ["command": NSNull()] + ["command": "return_home"], ["command": "unknown"], ["command": NSNull()], + ["client_request_id": "another-request"], ["command_id": ""], ["command_id": NSNull()] ] for change in changes { let session = MockURLSession(responses: [try envelope(data: payload().merging(change) { _, new in new })]) do { _ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) - .sendCommand(taskID: 501, command: .pause) + .sendCommand(taskID: 501, command: .pause, clientRequestID: "local-command-request") XCTFail("错误任务或指令回显应拒绝") } catch let APIError.decodeFailed(message) { XCTAssertFalse(message.isEmpty) } XCTAssertEqual(session.requests.count, 1) @@ -110,12 +124,13 @@ final class DroneDockCommandAPITests: XCTestCase { /// 空响应或缺少必需回显不能生成成功回执。 func testMissingDataAndEchoAreRejected() async throws { let data: [Any] = [NSNull(), [:] as [String: Any], [] as [Any], - ["order_flight_task_id": 501], ["command": "flighttask_pause"]] + ["order_flight_task_id": 501], ["command": "flighttask_pause"], + ["order_flight_task_id": 501, "command": "flighttask_pause"]] for value in data { let session = MockURLSession(responses: [try envelope(data: value)]) do { _ = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) - .sendCommand(taskID: 501, command: .pause) + .sendCommand(taskID: 501, command: .pause, clientRequestID: "local-command-request") XCTFail("缺失回显不能算成功") } catch let error as APIError { switch error { @@ -137,7 +152,7 @@ final class DroneDockCommandAPITests: XCTestCase { data["future"] = ["text": "001", "count": 0, "empty": NSNull()] as [String: Any] let session = MockURLSession(responses: [try envelope(data: data)]) let response = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) - .sendCommand(taskID: 501, command: .pause) + .sendCommand(taskID: 501, command: .pause, clientRequestID: "local-command-request") let original = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: JSONSerialization.data(withJSONObject: data)) let displayed = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: Data(response.dataJSON.utf8)) @@ -150,11 +165,17 @@ final class DroneDockCommandAPITests: XCTestCase { /// 缺少非身份展示字段仍保留未知值,不阻断已经核对身份的回执。 func testOptionalDisplayFieldsRemainUnknownWhenMissing() async throws { let session = MockURLSession(responses: [try envelope(data: ["order_flight_task_id": 501, - "command": "flighttask_pause"])]) + "command": "flighttask_pause", "command_id": "local-command-1"])]) let response = try await DroneDockCommandAPI(client: APIClient(environment: .testing, session: session)) - .sendCommand(taskID: 501, command: .pause) + .sendCommand(taskID: 501, command: .pause, clientRequestID: "local-command-request") XCTAssertNil(response.airportSN) XCTAssertNil(response.djiStatus) + XCTAssertNil(response.accepted) + XCTAssertNil(response.deviceConfirmed) + XCTAssertNil(response.executionBatch) + XCTAssertNil(response.flightControl) + XCTAssertNil(response.clientRequestID) + XCTAssertNil(response.pendingCommand) XCTAssertTrue(response.metrics.isEmpty) } @@ -165,7 +186,7 @@ final class DroneDockCommandAPITests: XCTestCase { let api = DroneDockCommandAPI(client: APIClient(environment: environment, session: session)) for command in DroneDockSafetyCommand.allCases { do { - _ = try await api.sendCommand(taskID: 501, command: command) + _ = try await api.sendCommand(taskID: 501, command: command, clientRequestID: "local-command-request") XCTFail("新增 API 不得绕过禁飞保护") } catch is DeviceCommandDebugBlockedError {} } @@ -188,6 +209,10 @@ final class DroneDockCommandAPITests: XCTestCase { private func payload(command: DroneDockSafetyCommand = .pause) -> [String: Any] { ["order_flight_task_id": 501, "command": command.rawValue, "airport_sn": "LOCAL-MOCK-AIRPORT-501", + "accepted": true, "device_confirmed": false, "execution_batch": 100, "state_version": 8, + "command_id": "local-command-1", "client_request_id": "local-command-request", + "pending_command": ["command_id": "local-command-1", "client_request_id": "local-command-request", + "command": command.rawValue, "status": "pending"], "dji_status": "paused", "metrics": [["key": "battery", "value": "95%"], ["key": "satellite", "value": "36颗"]]] } diff --git a/suixinkanTests/DroneDockCommandProgressTests.swift b/suixinkanTests/DroneDockCommandProgressTests.swift new file mode 100644 index 0000000..9e827cc --- /dev/null +++ b/suixinkanTests/DroneDockCommandProgressTests.swift @@ -0,0 +1,384 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 指令进度只更新对应按钮;所有请求、延迟和回执均由内存替身产生。 +@MainActor +final class DroneDockCommandProgressTests: XCTestCase { + /// 第二个按钮立即进入等待,HTTP 串行发出,但无需等第一条设备指令确认。 + func testIndependentButtonsQueueHTTPInOrderWithoutWaitingForDeviceConfirmation() async throws { + let fixture = try CommandProgressFixture() + defer { fixture.service.cancelAll() } + await fixture.model.refresh() + fixture.service.holdsCommands = true + let pause = Task { await fixture.model.sendCommand(.pause) } + try await wait { fixture.service.requests.count == 1 } + XCTAssertTrue(fixture.model.isCommandLoading(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + let returning = Task { await fixture.model.sendCommand(.returnHome) } + try await wait { fixture.model.isCommandLoading(.returnHome) } + XCTAssertEqual(fixture.service.requests.map(\.command), [.pause]) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + try fixture.service.resolve(0, changes: ["state_version": 2]) + try await wait { fixture.service.requests.count == 2 } + XCTAssertEqual(fixture.service.requests.map(\.command), [.pause, .returnHome]) + XCTAssertTrue(fixture.model.isCommandLoading(.pause), "第一条仍在等待设备确认,第二条已经可以提交") + try fixture.service.resolve(1, changes: ["state_version": 3]) + await pause.value + await returning.value + XCTAssertEqual(fixture.service.maximumConcurrentCommands, 1) + XCTAssertEqual(Set(fixture.service.requests.map(\.clientRequestID)).count, 2) + XCTAssertFalse(fixture.model.isCommandLoading(.pause), "后受理的返航取代旧暂停意图") + XCTAssertTrue(fixture.model.isCommandLoading(.returnHome)) + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + XCTAssertFalse(fixture.model.canSendCommand(.returnHome)) + XCTAssertEqual(fixture.model.presentation.phase, .shooting, "受理回执不替代完整业务快照") + } + + /// 排队期间已收到本批次回巢证据,尚未发出的暂停不能继续沿用点击时的飞行许可。 + func testQueuedPauseIsNotSentAfterReturned() async throws { + let fixture = try CommandProgressFixture() + defer { fixture.service.cancelAll() } + await fixture.model.refresh() + fixture.service.holdsCommands = true + let returning = Task { await fixture.model.sendCommand(.returnHome) } + try await wait { fixture.service.requests.count == 1 } + let pause = Task { await fixture.model.sendCommand(.pause) } + try await wait { fixture.model.isCommandLoading(.pause) } + fixture.service.value = try DroneDockShootingTaskTestData.response(changes: [ + "order_flight_task_id": 501, "execution_batch": 9001, "state_version": 3, + "task": ["id": 501, "status": 40, "result_code": "return_home"], + "order_flight_task": ["id": 501, "status": 40, "result_code": "return_home"], + "current_plane": ["id": 58, "sn_number": "LOCAL-PROGRESS-058", "work_status": 1], + "flight_control": DroneDockShootingTaskTestData.flightControl(state: "returned", batch: 9001, + canPause: false, canResume: false, canReturn: false, resumePhase: "returning", + returnReason: "manual", droneInDock: "inside", isAirborne: false), + "ui": ["phase": "failed_restartable"]]) + XCTAssertEqual(fixture.model.applyTaskSnapshot(fixture.service.value), .applied) + try fixture.service.resolve(0) + await returning.value + await pause.value + XCTAssertEqual(fixture.service.requests.map(\.command), [.returnHome]) + XCTAssertFalse(fixture.model.isCommandLoading(.pause)) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertEqual(fixture.model.flightControlState, .returned) + } + + /// 权限撤销后,队列中尚未发出的另一安全指令必须取消,不能继续使用旧快照权限。 + func testQueuedCommandIsNotSentAfterAccessDenied() async throws { + let fixture = try CommandProgressFixture() + defer { fixture.service.cancelAll() } + await fixture.model.refresh() + fixture.service.holdsCommands = true + let pause = Task { await fixture.model.sendCommand(.pause) } + try await wait { fixture.service.requests.count == 1 } + let returning = Task { await fixture.model.sendCommand(.returnHome) } + try await wait { fixture.model.isCommandLoading(.returnHome) } + fixture.model.stopReading(message: "当前账号无权限操作该任务") + try fixture.service.resolve(0) + await pause.value + await returning.value + XCTAssertEqual(fixture.service.requests.map(\.command), [.pause]) + XCTAssertFalse(fixture.model.isCommandLoading(.returnHome)) + XCTAssertFalse(fixture.model.canSendCommand(.returnHome)) + XCTAssertNotNil(fixture.model.readAccessError) + } + + /// 回执已报告更高版本时,迟到的较低版本完整快照不能回退状态或确认按钮。 + func testAcceptedReceiptVersionFloorRejectsOlderFullSnapshots() async throws { + let fixture = try CommandProgressFixture() + await fixture.model.refresh() + fixture.service.receiptChanges = ["state_version": 5] + await fixture.model.sendCommand(.pause) + let request = try XCTUnwrap(fixture.service.requests.first) + let old = try CommandProgressFixture.snapshot(version: 4, state: "paused", + progress: request.progress(status: "succeeded")) + XCTAssertEqual(fixture.model.applyTaskSnapshot(old), .outdated) + XCTAssertEqual(fixture.model.response?.stateVersion, 1) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + XCTAssertTrue(fixture.model.isCommandLoading(.pause)) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 5, + progress: request.progress(status: "pending"))), .applied) + XCTAssertTrue(fixture.model.isCommandLoading(.pause)) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 6, state: "paused", + progress: request.progress(status: "succeeded"))), .applied) + XCTAssertFalse(fixture.model.isCommandLoading(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.resume)) + } + + /// succeeded、failed 和 superseded 都结束对应动画,不触发另一条设备指令。 + func testMatchingTerminalProgressStopsOnlyItsButtonLoading() async throws { + for status in ["succeeded", "failed", "superseded"] { + let fixture = try CommandProgressFixture() + await fixture.model.refresh() + await fixture.model.sendCommand(.pause) + XCTAssertTrue(fixture.model.isCommandLoading(.pause)) + let request = try XCTUnwrap(fixture.service.requests.first) + fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 3, + state: status == "succeeded" ? "paused" : "executing", + progress: request.progress(status: status))) + XCTAssertFalse(fixture.model.isCommandLoading(.pause), status) + XCTAssertFalse(fixture.model.isCommandLoading(.returnHome), status) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome), status) + XCTAssertEqual(fixture.service.requests.count, 1) + if status == "failed" { + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + XCTAssertNotNil(fixture.model.commandErrorMessage(for: .pause)) + XCTAssertNil(fixture.model.commandErrorMessage(for: .returnHome)) + } + if status == "superseded" { XCTAssertTrue(fixture.model.canSendCommand(.pause)) } + } + } + + /// 指令或请求标识不匹配的终态不能停止本按钮等待,普通新版本也不能冒充确认。 + func testUnrelatedProgressCannotFinishCurrentOperation() async throws { + let fixture = try CommandProgressFixture() + await fixture.model.refresh() + await fixture.model.sendCommand(.pause) + let request = try XCTUnwrap(fixture.service.requests.first) + for (offset, changes) in [ + ["command_id": "another-command"], + ["client_request_id": "another-request"], + ["command": DroneDockSafetyCommand.returnHome.rawValue] + ].enumerated() { + let unrelated = request.progress(status: "succeeded").merging(changes) { _, new in new } + fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: offset + 3, progress: unrelated)) + XCTAssertTrue(fixture.model.isCommandLoading(.pause)) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + } + fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 6, state: "paused", + progress: request.progress(status: "succeeded"))) + XCTAssertFalse(fixture.model.isCommandLoading(.pause)) + XCTAssertEqual(fixture.service.requests.count, 1) + } + + /// 缺省 pending 的设备确认回执可停动画,旧权限快照仍不能让同一按钮重复提交。 + func testDeviceConfirmedStopsSpinnerButNeedsFreshStateBeforeSameActionCanRepeat() async throws { + let fixture = try CommandProgressFixture() + await fixture.model.refresh() + fixture.service.receiptChanges = ["pending_command": NSNull(), "device_confirmed": true, "state_version": 2] + await fixture.model.sendCommand(.pause) + XCTAssertFalse(fixture.model.isCommandLoading(.pause)) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + await fixture.model.sendCommand(.pause) + XCTAssertEqual(fixture.service.requests.count, 1) + fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 2, state: "paused")) + XCTAssertTrue(fixture.model.canSendCommand(.resume)) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 3)) + XCTAssertTrue(fixture.model.canSendCommand(.pause), "完整状态已经完成暂停和恢复后才允许新的暂停操作") + } + + /// 重新进入时仅从服务器 pending 锁住对应动作,不显示中央受理阶段。 + func testRemotePendingLocksOnlyMatchingButtonAndClearsOnExplicitFailure() async throws { + let fixture = try CommandProgressFixture() + let request = CommandProgressRequest(taskID: 501, command: .pause, clientRequestID: "remote-request", batch: 9001) + fixture.service.value = try CommandProgressFixture.snapshot(progress: request.progress(status: "pending")) + await fixture.model.refresh() + XCTAssertTrue(fixture.model.isCommandLoading(.pause)) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(version: 2, + progress: request.progress(status: "failed"))) + XCTAssertFalse(fixture.model.isCommandLoading(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.service.requests.isEmpty) + } + + /// 结果未知只锁住该动作;重复刷新不重发,另一安全按钮仍保留明确授权。 + func testUnknownResultLocksOnlyItsActionWithoutAutomaticallyResending() async throws { + for error in [APIError.networkFailed("本地超时"), APIError.decodeFailed("本地错误回执")] { + let fixture = try CommandProgressFixture() + await fixture.model.refresh() + fixture.service.commandError = error + await fixture.model.sendCommand(.pause) + XCTAssertTrue(fixture.model.isCommandOutcomeUnknown(.pause)) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + XCTAssertFalse(fixture.model.isCommandOutcomeUnknown(.returnHome)) + XCTAssertNil(fixture.model.commandErrorMessage(for: .returnHome)) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + await fixture.model.refresh() + await fixture.model.sendCommand(.pause) + XCTAssertEqual(fixture.service.requests.count, 1) + } + } + + /// 明确拒绝和本地拦截不是未知结果,同一按钮仅由再次点击触发重试。 + func testKnownFailureStopsLoadingAndLeavesOtherActionUntouched() async throws { + for error: Error in [APIError.serverCode(100099, "本地拒绝"), DeviceCommandDebugBlockedError()] { + let fixture = try CommandProgressFixture() + await fixture.model.refresh() + fixture.service.commandError = error + await fixture.model.sendCommand(.pause) + XCTAssertFalse(fixture.model.isCommandLoading(.pause)) + XCTAssertFalse(fixture.model.isCommandOutcomeUnknown(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + XCTAssertNil(fixture.model.commandErrorMessage(for: .returnHome)) + XCTAssertEqual(fixture.service.requests.count, 1) + XCTAssertEqual(fixture.service.readCount, 1) + } + } + + /// 传输故意忽略取消,旧批次成功或失败均不能在新批次重建按钮等待或错误。 + func testNewBatchRejectsLateOldReceiptAndFailure() async throws { + for succeeds in [true, false] { + let fixture = try CommandProgressFixture() + defer { fixture.service.cancelAll() } + await fixture.model.refresh() + fixture.service.holdsCommands = true + let operation = Task { await fixture.model.sendCommand(.pause) } + try await wait { fixture.service.requests.count == 1 } + fixture.model.applyTaskSnapshot(try CommandProgressFixture.snapshot(batch: 9002, state: "starting")) + if succeeds { try fixture.service.resolve(0) } + else { fixture.service.fail(0, error: APIError.networkFailed("迟到的旧批次失败")) } + await operation.value + XCTAssertEqual(fixture.model.response?.executionBatch, 9002) + XCTAssertEqual(fixture.model.presentation.phase, .navigating) + XCTAssertFalse(fixture.model.isCommandLoading(.pause)) + XCTAssertFalse(fixture.model.commandOutcomeUnknown) + XCTAssertNil(fixture.model.commandResponse) + XCTAssertNil(fixture.model.commandErrorMessage) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + XCTAssertEqual(fixture.service.requests.count, 1) + } + } + + /// 仅等待内存任务调度,不接触网络或设备。 + private func wait(_ condition: () -> Bool) async throws { + for _ in 0..<200 { + if condition() { return } + try await Task.sleep(for: .milliseconds(10)) + } + XCTFail("隔离指令任务未进入预期状态") + throw CommandProgressTestError.timedOut + } +} + +/// 仅用于及时退出未完成的内存调度等待,避免测试继续挂起。 +private enum CommandProgressTestError: Error { case timedOut } + +/// 记录一个逻辑请求,服务端 ID 与客户端幂等键分别建模。 +private struct CommandProgressRequest { + let taskID: Int + let command: DroneDockSafetyCommand + let clientRequestID: String + let batch: Int64 + var commandID: String { "server-\(clientRequestID)" } + + /// 构造 HTTP/WS 共用的同一条指令进度。 + func progress(status: String) -> [String: Any] { + ["command_id": commandID, "client_request_id": clientRequestID, + "command": command.rawValue, "status": status, + "message": status == "failed" ? "本地设备执行失败" : ""] + } + + /// 合成受理回执,不将受理作为设备已经执行的证据。 + func receipt(changes: [String: Any] = [:]) throws -> DroneDockCommandResponse { + let data: [String: Any] = [ + "order_flight_task_id": taskID, "execution_batch": batch, "state_version": 2, + "plane_id": 58, "airport_sn": "LOCAL-PROGRESS-058", + "accepted": true, "device_confirmed": false, "command": command.rawValue, + "command_id": commandID, "client_request_id": clientRequestID, + "pending_command": progress(status: "pending")] + return try JSONDecoder().decode(DroneDockCommandResponse.self, + from: JSONSerialization.data(withJSONObject: data.merging(changes) { _, new in new })) + } +} + +/// 当前任务与服务完整隔离,快照默认有已确认的飞行状态和两项安全许可。 +@MainActor +private struct CommandProgressFixture { + let service: CommandProgressService + let model: DroneDockShootingTaskViewModel + + /// 注入只读与指令内存替身,不提供任何真实传输能力。 + init() throws { + service = CommandProgressService(value: try Self.snapshot()) + let context = DroneDockShootingTaskTestData.context() + model = DroneDockShootingTaskViewModel(context: context, taskID: 501, + order: try DroneDockShootingTaskTestData.order(), service: service, commandService: service, + currentContext: { context }) + } + + /// 提供当前批次完整状态,进度放在合同规定的 flight_control.pending_command 下。 + static func snapshot(version: Int = 1, batch: Int = 9001, state: String = "executing", + progress: [String: Any]? = nil) throws -> DroneDockShootingResponse { + let starting = state == "starting" + let paused = state == "paused" + return try DroneDockShootingTaskTestData.response(changes: [ + "order_flight_task_id": 501, "execution_batch": batch, "state_version": version, "snapshot_kind": "full", + "task": ["id": 501, "status": 20], "order_flight_task": ["id": 501, "status": 20], + "current_plane": ["id": 58, "sn_number": "LOCAL-PROGRESS-058", "work_status": 2], + "flight_control": DroneDockShootingTaskTestData.flightControl(state: state, batch: batch, + canPause: !paused && !starting, canResume: paused, canReturn: true, + resumePhase: starting ? "going_to_spot" : "shooting", + droneInDock: starting ? "inside" : "outside", isAirborne: !starting, + pauseReason: paused ? "manual" : nil, pendingCommand: progress), + "ui": ["phase": starting ? "going_to_spot" : paused ? "manual_paused" : "shooting"], + "execute_gate": ["can_execute": false, "primary_action": "blocked"]]) + } +} + +/// 可挂起且故意忽略取消的指令服务,用于验证 FIFO 与迟到响应;从不转发网络。 +@MainActor +private final class CommandProgressService: DroneDockShootingServing, DroneDockCommandSending { + var value: DroneDockShootingResponse + var holdsCommands = false + var receiptChanges: [String: Any] = [:] + var commandError: Error? + private(set) var requests: [CommandProgressRequest] = [] + private(set) var readCount = 0 + private(set) var maximumConcurrentCommands = 0 + private var activeCommands = 0 + private var continuations: [String: CheckedContinuation] = [:] + + /// 使用显式内存快照初始化测试读取。 + init(value: DroneDockShootingResponse) { self.value = value } + + /// 只读返回同任务配置快照,实时采集参数必须关闭。 + func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse { + XCTAssertEqual(taskID, 501) + XCTAssertFalse(liveBattery) + readCount += 1 + return value + } + + /// 保存幂等请求并可选择挂起,允许测试控制回执顺序。 + func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse { + let request = CommandProgressRequest(taskID: taskID, command: command, + clientRequestID: clientRequestID, batch: value.executionBatch ?? 9001) + requests.append(request) + activeCommands += 1 + maximumConcurrentCommands = max(maximumConcurrentCommands, activeCommands) + defer { activeCommands -= 1 } + if holdsCommands { + return try await withCheckedThrowingContinuation { continuations[clientRequestID] = $0 } + } + if let commandError { throw commandError } + return try request.receipt(changes: receiptChanges) + } + + /// 将指定请求完成为合成回执,保持同请求身份。 + func resolve(_ index: Int, changes: [String: Any] = [:]) throws { + let request = requests[index] + let result = try request.receipt(changes: changes) + continuations.removeValue(forKey: request.clientRequestID)?.resume(returning: result) + } + + /// 将指定请求完成为错误,即使其调用任务已经取消。 + func fail(_ index: Int, error: Error) { + continuations.removeValue(forKey: requests[index].clientRequestID)?.resume(throwing: error) + } + + /// 失败退出时释放所有测试 continuation,避免影响后续用例。 + func cancelAll() { + let pending = Array(continuations.values) + continuations.removeAll() + for continuation in pending { continuation.resume(throwing: CancellationError()) } + } +} diff --git a/suixinkanTests/DroneDockCommandViewModelTests.swift b/suixinkanTests/DroneDockCommandViewModelTests.swift index a10f18e..1b18b95 100644 --- a/suixinkanTests/DroneDockCommandViewModelTests.swift +++ b/suixinkanTests/DroneDockCommandViewModelTests.swift @@ -16,12 +16,12 @@ final class DroneDockCommandViewModelTests: XCTestCase { XCTAssertTrue(fixture.write.requests.isEmpty) } - /// 仅使用当前快照的已知指令,去重后保留顺序,开拍门禁为 false 不影响安全动作。 - func testExplicitCommandWhitelistDoesNotUseStartGate() async throws { + /// 新版权限来自 flight_control,旧指令列表的顺序和文案不改变本地安全动作。 + func testFlightControlPermissionsDoNotUseStartGateOrLegacyCommands() async throws { let fixture = try CommandTaskFixture() fixture.read.result = .success(try CommandTaskData.snapshot(commands: ["unknown_command", "return_home", "flighttask_pause", "flighttask_pause"])) await fixture.model.refresh() - XCTAssertEqual(fixture.model.availableSafetyCommands, [.returnHome, .pause]) + XCTAssertEqual(Set(fixture.model.availableSafetyCommands), Set([.returnHome, .pause])) XCTAssertEqual(fixture.model.response?.executeGate?.canExecute, false) XCTAssertTrue(fixture.model.canSendCommand(.pause)) XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) @@ -33,7 +33,7 @@ final class DroneDockCommandViewModelTests: XCTestCase { /// 缺少明确任务身份、锁定飞机或当前指令时,不将其它状态字段推导为许可。 func testIncompleteSnapshotCannotSendCommands() async throws { for snapshot in [ - try CommandTaskData.snapshot(commands: []), + try CommandTaskData.snapshot(includeFlightControl: false), try CommandTaskData.snapshot(lockedPlane: false), try CommandTaskData.snapshot(includeTaskIdentity: false) ] { @@ -51,14 +51,14 @@ final class DroneDockCommandViewModelTests: XCTestCase { let fixture = try CommandTaskFixture() await fixture.model.refresh() let previous = fixture.model.response - let paused = try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"]) + let paused = try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"], version: 2) fixture.write.onRequest = { fixture.read.result = .success(paused) } var observedReceiptBeforeRefresh = false await fixture.model.sendCommand(.pause) { if fixture.model.commandResponse != nil && fixture.model.response == previous { observedReceiptBeforeRefresh = true - XCTAssertTrue(fixture.model.isSendingCommand) - XCTAssertEqual(fixture.model.activeCommand, .pause) + XCTAssertTrue(fixture.model.isCommandLoading(.pause)) + XCTAssertFalse(fixture.model.isSendingCommand) XCTAssertFalse(fixture.model.presentation.isActionEnabled) } } @@ -89,34 +89,31 @@ final class DroneDockCommandViewModelTests: XCTestCase { XCTAssertFalse(fixture.model.commandOutcomeUnknown) } - /// 多条指令均已受理而状态尚未追上时,后一条受理不能解除前一条的防重锁。 - func testStaleSnapshotRetainsEveryAcceptedCommandLock() async throws { + /// 暂停等待确认仅锁住暂停,仍可提交后端允许的返航,且不覆盖中央业务阶段。 + func testAcceptedPauseDoesNotBlockIndependentReturnCommand() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() await fixture.model.sendCommand(.pause) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) await fixture.model.sendCommand(.returnHome) - XCTAssertFalse(fixture.model.canSendCommand(.pause)) XCTAssertFalse(fixture.model.canSendCommand(.returnHome)) - await fixture.model.sendCommand(.pause) await fixture.model.sendCommand(.returnHome) - fixture.model.invalidate(preservingSnapshot: true) - await fixture.model.refresh() - XCTAssertFalse(fixture.model.canSendCommand(.pause)) - XCTAssertFalse(fixture.model.canSendCommand(.returnHome)) XCTAssertEqual(fixture.write.requests.map(\.command), [.pause, .returnHome]) - XCTAssertEqual(fixture.read.requests, [501, 501, 501, 501]) + XCTAssertEqual(Set(fixture.write.requests.map(\.clientRequestID)).count, 2) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) } /// 暂停、恢复再暂停使用新的权限快照,可按用户操作继续调试同一任务。 func testPauseResumeCycleAcceptsFreshCommandAvailability() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() - fixture.read.result = .success(try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"])) + fixture.read.result = .success(try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"], version: 2)) await fixture.model.sendCommand(.pause) - fixture.read.result = .success(try CommandTaskData.snapshot()) + fixture.read.result = .success(try CommandTaskData.snapshot(version: 3)) await fixture.model.sendCommand(.resume) - fixture.read.result = .success(try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"])) + fixture.read.result = .success(try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"], version: 4)) await fixture.model.sendCommand(.pause) XCTAssertEqual(fixture.write.requests.map(\.command), [.pause, .resume, .pause]) XCTAssertEqual(fixture.read.requests, [501, 501, 501, 501]) @@ -143,8 +140,8 @@ final class DroneDockCommandViewModelTests: XCTestCase { XCTAssertNotNil(fixture.model.commandResponse) } - /// 网络或解析失败不能确定是否已执行,刷新、重进均不能自动解锁重发。 - func testUnknownOutcomeLocksCommandsAndStartAcrossRefresh() async throws { + /// 网络或解析失败仅锁定结果未知的动作及开拍,另一安全动作仍可依据可信权限执行。 + func testUnknownOutcomeLocksSameCommandAndStartAcrossRefresh() async throws { for error in [APIError.networkFailed("模拟超时"), APIError.httpStatus(500, "模拟异常"), APIError.decodeFailed("模拟回执无法解析")] { let fixture = try CommandTaskFixture() fixture.read.result = .success(try CommandTaskData.snapshot(phase: "arrived_pending_start")) @@ -156,12 +153,13 @@ final class DroneDockCommandViewModelTests: XCTestCase { XCTAssertTrue(fixture.model.commandOutcomeUnknown) XCTAssertFalse(fixture.model.canStartShooting) XCTAssertEqual(fixture.model.response, previous) - XCTAssertTrue(fixture.model.presentation.message.contains("安全指令结果待核对")) - XCTAssertEqual(fixture.model.presentation.action, .refresh) - XCTAssertTrue(fixture.model.presentation.isActionEnabled) + XCTAssertEqual(fixture.model.presentation.phase, .ready) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) fixture.model.invalidate(preservingSnapshot: true) await fixture.model.refresh() - for command in DroneDockSafetyCommand.allCases { await fixture.model.sendCommand(command) } + await fixture.model.sendCommand(.pause) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) await fixture.model.startShooting() XCTAssertEqual(fixture.write.requests.count, 1) XCTAssertTrue(fixture.start.requests.isEmpty) @@ -181,8 +179,8 @@ final class DroneDockCommandViewModelTests: XCTestCase { XCTAssertEqual(fixture.read.requests.count, 1) } - /// 指令在途时,连点、开拍和手动读取均不能插入并发请求。 - func testPendingCommandRejectsDoubleTapStartAndRefresh() async throws { + /// 指令在途时拒绝同按钮连点与开拍,但不无条件禁用另一安全按钮。 + func testPendingCommandRejectsDoubleTapAndStartWithoutBlockingReturn() async throws { let fixture = try CommandTaskFixture() fixture.read.result = .success(try CommandTaskData.snapshot(phase: "arrived_pending_start")) await fixture.model.refresh() @@ -195,9 +193,8 @@ final class DroneDockCommandViewModelTests: XCTestCase { XCTAssertTrue(fixture.model.isSendingCommand) XCTAssertEqual(fixture.model.response, previous) await fixture.model.sendCommand(.pause) - await fixture.model.sendCommand(.returnHome) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) await fixture.model.startShooting() - await fixture.model.refresh() XCTAssertEqual(fixture.write.requests.count, 1) XCTAssertTrue(fixture.start.requests.isEmpty) XCTAssertEqual(fixture.read.requests.count, 1) @@ -288,24 +285,23 @@ final class DroneDockCommandViewModelTests: XCTestCase { } } - /// 返航可终结任务但仍提供取消返航;取消后不自动恢复任务或开始拍摄。 - func testFailedTaskCanCancelReturnOnlyWhenExplicitlyOffered() async throws { + /// 新版返航权限不会借旧 commands 开放取消返航,拍摄中断不能自动恢复。 + func testReturningDoesNotPermitLegacyCancelReturnCommand() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() - fixture.read.result = .success(try CommandTaskData.snapshot(phase: "returning", commands: ["return_home_cancel"], taskStatus: 40)) + fixture.read.result = .success(try CommandTaskData.snapshot(phase: "returning", commands: ["return_home_cancel"], taskStatus: 40, version: 2)) await fixture.model.sendCommand(.returnHome) - XCTAssertEqual(fixture.model.presentation.phase, .failed) - XCTAssertTrue(fixture.model.canSendCommand(.cancelReturn)) + XCTAssertEqual(fixture.model.presentation.phase, .returning) + XCTAssertFalse(fixture.model.canSendCommand(.cancelReturn)) XCTAssertFalse(fixture.model.canSendCommand(.resume)) - fixture.read.result = .success(try CommandTaskData.snapshot(phase: "failed", commands: [], taskStatus: 40)) await fixture.model.sendCommand(.cancelReturn) - XCTAssertEqual(fixture.write.requests.map(\.command), [.returnHome, .cancelReturn]) - XCTAssertEqual(fixture.model.presentation.phase, .failed) + XCTAssertEqual(fixture.write.requests.map(\.command), [.returnHome]) + XCTAssertEqual(fixture.model.presentation.phase, .returning) XCTAssertFalse(fixture.model.canStartShooting) - XCTAssertTrue(fixture.model.availableSafetyCommands.isEmpty) + XCTAssertEqual(fixture.model.availableSafetyCommands, [.pause]) } - /// 已接受后读取失败保留旧快照,需新权限快照才能继续控制。 + /// 已接受后读取失败保留旧快照与本动作等待,另一安全动作仍使用已确认的许可。 func testAcceptedCommandWithFailedReadKeepsSnapshotAndReceipt() async throws { let fixture = try CommandTaskFixture() await fixture.model.refresh() @@ -316,8 +312,8 @@ final class DroneDockCommandViewModelTests: XCTestCase { XCTAssertEqual(fixture.model.response, previous) XCTAssertFalse(fixture.model.commandOutcomeUnknown) XCTAssertFalse(fixture.model.canSendCommand(.pause)) - XCTAssertFalse(fixture.model.canSendCommand(.returnHome)) - fixture.read.result = .success(try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"])) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + fixture.read.result = .success(try CommandTaskData.snapshot(phase: "paused", commands: ["flighttask_recovery", "return_home"], version: 2)) await fixture.model.refresh() XCTAssertTrue(fixture.model.canSendCommand(.resume)) } @@ -382,18 +378,18 @@ private final class CommandTaskWriteService: DroneDockCommandSending { var result: Result? var onRequest: (() -> Void)? var suspend = false - private(set) var requests: [(taskID: Int, command: DroneDockSafetyCommand)] = [] + private(set) var requests: [(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String)] = [] private var continuation: CheckedContinuation? - func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse { - requests.append((taskID, command)) + func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse { + requests.append((taskID, command, clientRequestID)) onRequest?() if suspend { return try await withCheckedThrowingContinuation { continuation = $0 } } - return try result?.get() ?? CommandTaskData.receipt(command: command) + return try result?.get() ?? CommandTaskData.receipt(command: command, clientRequestID: clientRequestID) } func finish() { - let receipt = result ?? Result { try CommandTaskData.receipt(command: requests.last?.command ?? .pause) } + let receipt = result ?? Result { try CommandTaskData.receipt(command: requests.last?.command ?? .pause, clientRequestID: requests.last?.clientRequestID) } continuation?.resume(with: receipt) continuation = nil } @@ -424,22 +420,42 @@ private final class CommandTaskStartService: DroneDockStartShooting { private enum CommandTaskData { static func snapshot(phase: String = "shooting", commands: [String] = ["flighttask_pause", "return_home"], taskStatus: Int = 20, lockedPlane: Bool = true, - includeTaskIdentity: Bool = true) throws -> DroneDockShootingResponse { + includeTaskIdentity: Bool = true, includeFlightControl: Bool = true, + version: Int = 1) throws -> DroneDockShootingResponse { var task: [String: Any] = ["status": taskStatus] if includeTaskIdentity { task["id"] = 501 } + let paused = phase == "paused" + let returning = phase == "returning" + if returning { task["result_code"] = "return_home" } + let control = DroneDockShootingTaskTestData.flightControl( + state: paused ? "paused" : returning ? "returning" : "executing", + canPause: !paused, canResume: paused, canReturn: !returning, + resumePhase: paused ? "shooting" : returning ? "returning" : nil, + returnReason: returning ? "manual" : nil, isAirborne: true, + pauseReason: paused ? "manual" : phase == "arrived_pending_start" ? "arrival_wait" : nil) return try DroneDockShootingTaskTestData.response(changes: [ + "execution_batch": 100, "state_version": version, "snapshot_kind": "full", + "flight_control": includeFlightControl ? control : NSNull(), "order_flight_task": task, "task": task, "current_plane": ["id": lockedPlane ? 58 : 0, "sn_number": "LOCAL-COMMAND-PLANE-058"], "execute_gate": ["can_execute": phase == "arrived_pending_start", "primary_action": phase == "arrived_pending_start" ? "start_shoot" : phase], - "ui": ["phase": phase, "title": "模拟安全指令阶段", "message": "本地模拟,未发送设备指令", + "ui": ["phase": paused ? "manual_paused" : returning ? "returning_home" : phase, "title": "模拟安全指令阶段", "message": "本地模拟,未发送设备指令", "commands": commands.map { ["command": $0] }] ]) } - static func receipt(command: DroneDockSafetyCommand, taskID: Int = 501) throws -> DroneDockCommandResponse { + static func receipt(command: DroneDockSafetyCommand, taskID: Int = 501, + clientRequestID: String? = nil) throws -> DroneDockCommandResponse { + let commandID = "local-\(command.rawValue)-\(clientRequestID ?? "fixture")" let payload: [String: Any] = ["order_flight_task_id": taskID, "command": command.rawValue, - "airport_sn": "LOCAL-COMMAND-DOCK-058", "dji_status": NSNull(), "metrics": []] + "accepted": true, "device_confirmed": false, "execution_batch": 100, + "command_id": commandID, "client_request_id": clientRequestID as Any? ?? NSNull(), + "pending_command": ["command_id": commandID, + "client_request_id": clientRequestID as Any? ?? NSNull(), + "command": command.rawValue, "status": "pending"], + "airport_sn": "LOCAL-COMMAND-PLANE-058", "plane_id": 58, + "dji_status": NSNull(), "metrics": []] return try JSONDecoder().decode(DroneDockCommandResponse.self, from: JSONSerialization.data(withJSONObject: payload)) } diff --git a/suixinkanTests/DroneDockCommandViewTests.swift b/suixinkanTests/DroneDockCommandViewTests.swift index a7ed757..69c6754 100644 --- a/suixinkanTests/DroneDockCommandViewTests.swift +++ b/suixinkanTests/DroneDockCommandViewTests.swift @@ -25,21 +25,28 @@ final class DroneDockCommandViewTests: XCTestCase { pause.sendActions(for: .touchUpInside) pause.sendActions(for: .touchUpInside) XCTAssertFalse(pause.isEnabled) - XCTAssertFalse(returnHome.isEnabled) + XCTAssertTrue(returnHome.isEnabled) XCTAssertEqual(model.presentation.title, oldTitle) XCTAssertEqual(find(controller.view, suffix: "metric.battery")?.accessibilityValue, oldBattery) try await settle(window) { model.canSendCommand(.resume) && !model.isSendingCommand - && (pause.accessibilityLabel?.contains("继续") == true) + && pause.accessibilityLabel == "已暂停" } XCTAssertEqual(model.presentation.phase, .paused) + XCTAssertFalse(pause.isEnabled) + XCTAssertEqual(pause.accessibilityValue, "悬停待命") + XCTAssertEqual(returnHome.accessibilityLabel, "立即返航") + XCTAssertTrue(returnHome.isEnabled) XCTAssertEqual(model.commandResponse?.command, "flighttask_pause") assertFrames(controller, suffixes: fixedIDs, frames: frames) capture(window, name: "安全控制-暂停成功-本地模拟") - pause.sendActions(for: .touchUpInside) - pause.sendActions(for: .touchUpInside) + let resume = try button(controller, suffix: "primary") + XCTAssertEqual(resume.configuration?.title, "继续任务") + XCTAssertTrue(resume.isEnabled) + resume.sendActions(for: .touchUpInside) + resume.sendActions(for: .touchUpInside) try await settle(window) { model.canSendCommand(.pause) && !model.isSendingCommand && (pause.accessibilityLabel?.contains("暂停") == true) @@ -47,7 +54,7 @@ final class DroneDockCommandViewTests: XCTestCase { XCTAssertEqual(model.presentation.phase, .shooting) XCTAssertEqual(model.commandResponse?.command, "flighttask_recovery") assertFrames(controller, suffixes: fixedIDs, frames: frames) - capture(window, name: "安全控制-继续拍摄-本地模拟") + capture(window, name: "安全控制-继续任务-本地模拟") let transcript = try await records(controller, window: window) let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) @@ -58,7 +65,11 @@ final class DroneDockCommandViewTests: XCTestCase { let bodies = posts.compactMap { $0["request_body"] as? [String: Any] } XCTAssertEqual(bodies.compactMap { $0["id"] as? Int }, [901, 901]) XCTAssertEqual(bodies.compactMap { $0["command"] as? String }, ["flighttask_pause", "flighttask_recovery"]) - for body in bodies { XCTAssertEqual(Set(body.keys), ["id", "command"]) } + for body in bodies { + XCTAssertEqual(Set(body.keys), ["id", "command", "client_request_id"]) + XCTAssertFalse(try XCTUnwrap(body["client_request_id"] as? String).isEmpty) + } + XCTAssertEqual(Set(bodies.compactMap { $0["client_request_id"] as? String }).count, 2) } /// 返航必须先显示模拟确认,关闭确认不会产生任何指令请求。 @@ -113,8 +124,8 @@ final class DroneDockCommandViewTests: XCTestCase { XCTAssertEqual(transcript["network_sent"] as? Bool, false) } - /// 超时保留旧数据并锁定所有安全动作,手动读取及回执查看仍可使用,不能自动重发。 - func testTimeoutLocksSafetyButtonsWhileReadRefreshAndReceiptsRemainAvailable() async throws { + /// 超时保留旧数据且仅锁定结果未知的暂停动作,另一安全按钮和只读刷新继续可用。 + func testTimeoutLocksOnlyAffectedSafetyButtonWhileReadRefreshRemainsAvailable() async throws { let controller = try makeController(result: "timeout") let window = makeWindow(controller) defer { close(window) } @@ -127,7 +138,7 @@ final class DroneDockCommandViewTests: XCTestCase { try await settle(window) { model.commandOutcomeUnknown && !model.isSendingCommand } XCTAssertEqual(model.response, original) XCTAssertFalse(pause.isEnabled) - XCTAssertFalse(returnHome.isEnabled) + XCTAssertTrue(returnHome.isEnabled) XCTAssertFalse(model.canStartShooting) XCTAssertFalse(model.canSendCommand(.pause)) let refresh = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first { @@ -138,7 +149,7 @@ final class DroneDockCommandViewTests: XCTestCase { try await settle(window) { !model.isLoading && refresh.isEnabled } XCTAssertTrue(model.commandOutcomeUnknown) XCTAssertFalse(pause.isEnabled) - XCTAssertFalse(returnHome.isEnabled) + XCTAssertTrue(returnHome.isEnabled) capture(window, name: "安全控制-结果待核对-本地模拟") let transcript = try await records(controller, window: window) let entries = try XCTUnwrap(transcript["records"] as? [[String: Any]]) @@ -151,6 +162,12 @@ final class DroneDockCommandViewTests: XCTestCase { func testReadOnlyEntryKeepsSafetyButtonsDisabledWhenSnapshotOffersCommands() async throws { let context = DroneDockShootingTaskTestData.context() let response = try DroneDockShootingTaskTestData.response(changes: [ + "order_flight_task": ["id": 501, "status": 20, "wayline_task_id": 9001], + "task": ["id": 501, "status": 20, "wayline_task_id": 9001], + "execution_batch": 9001, "state_version": 1, + "flight_control": ["state": "executing", "execution_batch": 9001, + "is_airborne": true, + "drone_in_dock": "outside", "can_pause": true, "can_resume": false, "can_return_home": true], "ui": ["phase": "shooting", "title": "拍摄中", "commands": [ ["command": "flighttask_pause", "label": "紧急暂停"], ["command": "return_home", "label": "立即返航"] diff --git a/suixinkanTests/DroneDockFlightControlTests.swift b/suixinkanTests/DroneDockFlightControlTests.swift new file mode 100644 index 0000000..fb91323 --- /dev/null +++ b/suixinkanTests/DroneDockFlightControlTests.swift @@ -0,0 +1,468 @@ +import XCTest +@testable import suixinkan + +/// 新设备状态合同的隔离回归,覆盖拍摄结果与物理返航分离、批次和受理确认保护。 +@MainActor +final class DroneDockFlightControlTests: XCTestCase { + /// 起飞准备仍在巢内,既不能当作未知,也不能冒充本批次已返航。 + func testStartingInsideShowsTravelAndKeepsExplicitReturnPermission() async throws { + let fixture = try FlightControlFixture(state: "starting") + await fixture.model.refresh() + XCTAssertEqual(fixture.model.flightControlState, .starting) + XCTAssertEqual(fixture.model.presentation.phase, .navigating) + XCTAssertEqual(fixture.model.presentation.title, "无人机正在赶来") + XCTAssertEqual(fixture.model.response?.flightControl?.isAirborne, false) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome), "合同允许起飞准备阶段取消本次出发") + XCTAssertFalse(fixture.model.canResummon) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertFalse(fixture.model.isRecordingFinished) + XCTAssertNil(fixture.model.countdownRemainingSeconds) + } + + /// 首点自动悬停保留待开拍和本地倒计时,原始 DJI paused 不等于用户紧急暂停。 + func testArrivalWaitShowsReadyCountdownAndIndependentSafetyActions() async throws { + let fixture = try FlightControlFixture() + var control = DroneDockShootingTaskTestData.flightControl(batch: 9001, + resumePhase: "arrived_pending_start", pauseReason: "arrival_wait") + control["dji_task_status"] = "paused" + fixture.service.value = try FlightControlFixture.snapshot(state: "executing", phase: "arrived_pending_start", + changes: ["flight_control": control]) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.flightControlState, .executing) + XCTAssertEqual(fixture.model.presentation.phase, .ready) + XCTAssertEqual(fixture.model.presentation.title, "无人机已到达") + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 30) + XCTAssertTrue(fixture.model.canStartShooting) + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + XCTAssertFalse(fixture.model.canSendCommand(.resume)) + XCTAssertTrue(fixture.service.commands.isEmpty) + XCTAssertEqual(fixture.service.startCount, 0) + } + + /// 待开拍时手动暂停后继续只恢复等待,倒计时沿用本批次期限,不自动开拍。 + func testManualPauseFromArrivalResumesReadyWithoutRestartingCountdownOrStartingShoot() async throws { + let clock = DroneDockCountdownTestClock() + let fixture = try FlightControlFixture(countdownNow: { clock.now() }) + fixture.service.value = try FlightControlFixture.snapshot(state: "executing", phase: "arrived_pending_start") + await fixture.model.refresh() + clock.advance(by: .seconds(12)) + fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "paused", version: 2, + resumePhase: "arrived_pending_start")) + XCTAssertEqual(fixture.model.presentation.phase, .paused) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertNil(fixture.model.countdownRemainingSeconds) + XCTAssertTrue(fixture.model.canSendCommand(.resume)) + clock.advance(by: .seconds(5)) + fixture.service.nextSnapshot = try FlightControlFixture.snapshot(state: "executing", version: 3, + phase: "arrived_pending_start") + await fixture.model.sendCommand(.resume) + XCTAssertEqual(fixture.service.commands, [.resume]) + XCTAssertEqual(fixture.service.startCount, 0) + XCTAssertEqual(fixture.model.presentation.phase, .ready) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 13) + XCTAssertTrue(fixture.model.canStartShooting) + } + + /// 起飞遥测三态仅供展示;执行、暂停和返航的安全操作均以明确 can_* 为准。 + func testExplicitSafetyPermissionsAreIndependentOfAirborneTelemetry() async throws { + let states: [(String, Set)] = [ + ("executing", [.pause, .returnHome]), ("paused", [.resume, .returnHome]), ("returning", [.pause])] + for (state, allowed) in states { + for airborne: Bool? in [true, false, nil] { + let fixture = try FlightControlFixture() + let control = DroneDockShootingTaskTestData.flightControl(state: state, batch: 9001, + canPause: allowed.contains(.pause), canResume: allowed.contains(.resume), + canReturn: allowed.contains(.returnHome), resumePhase: "shooting", + droneInDock: "outside", isAirborne: airborne, pauseReason: state == "paused" ? "manual" : nil) + fixture.service.value = try FlightControlFixture.snapshot(state: state, changes: ["flight_control": control]) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.response?.flightControl?.isAirborne, airborne) + XCTAssertNotEqual(fixture.model.flightControlState, .unknown) + for command in DroneDockSafetyCommand.allCases { + XCTAssertEqual(fixture.model.canSendCommand(command), allowed.contains(command), "\(state): \(command)") + } + XCTAssertFalse(fixture.model.canResummon) + XCTAssertTrue(fixture.service.commands.isEmpty) + } + } + } + + /// 有效遥测和已知飞行态都不能补造缺失或明确禁止的安全许可。 + func testMissingOrFalseSafetyPermissionsRemainDeniedWithValidTelemetry() async throws { + for permission: Any in [NSNull(), false] { + let fixture = try FlightControlFixture() + var control = DroneDockShootingTaskTestData.flightControl(batch: 9001) + for field in ["can_pause", "can_resume", "can_return_home"] { control[field] = permission } + fixture.service.value = try FlightControlFixture.snapshot(state: "executing", changes: ["flight_control": control]) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.response?.flightControl?.isAirborne, true) + XCTAssertTrue(fixture.model.availableSafetyCommands.isEmpty) + for command in DroneDockSafetyCommand.allCases { XCTAssertFalse(fixture.model.canSendCommand(command)) } + } + } + + /// 业务失败或素材完成不代表飞机已落地,安全动作独立服从本批次飞控许可。 + func testBusinessFailureAndCompletionDoNotBlockAuthorizedSafetyActions() async throws { + for (status, phase, wayline) in [(40, "failed_restartable", 91), (30, "completed", 50), + (25, "post_shoot_uploading", 30), (40, "post_shoot_upload_failed", 39)] { + let fixture = try FlightControlFixture() + let task: [String: Any] = ["id": 501, "status": status, "wayline_status": wayline] + fixture.service.value = try FlightControlFixture.snapshot(state: "executing", phase: phase, + changes: ["task": task, "order_flight_task": task]) + await fixture.model.refresh() + XCTAssertTrue(fixture.model.canSendCommand(.pause), phase) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome), phase) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertFalse(fixture.model.canResummon) + } + } + + /// 同批次读数缺失时保留最近指标并标记过期,新批次清空旧读数和旧控制态。 + func testRetainedStaleMetricsStayWithinCurrentExecutionBatch() async throws { + let fixture = try FlightControlFixture() + fixture.service.value = try FlightControlFixture.snapshot(state: "executing", changes: [ + "metrics": [["key": "battery", "value": "76%"], ["key": "wind_speed", "value": "2m/s"]], + "metrics_stale": false]) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.telemetry.batteryText, "76%") + XCTAssertFalse(fixture.model.isTelemetryStale) + fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "paused", version: 2, + changes: ["metrics": [], "metrics_stale": true])) + XCTAssertEqual(fixture.model.telemetry.batteryText, "76%") + XCTAssertEqual(fixture.model.telemetry.windText, "2m/s") + XCTAssertTrue(fixture.model.isTelemetryStale) + XCTAssertTrue(fixture.model.canSendCommand(.resume), "指标过期不覆盖独立飞控许可") + fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "starting", batch: 9002, + changes: ["metrics": [], "metrics_stale": true])) + XCTAssertEqual(fixture.model.telemetry.batteryText, "—") + XCTAssertEqual(fixture.model.telemetry.windText, "—") + XCTAssertEqual(fixture.model.presentation.phase, .navigating) + XCTAssertFalse(fixture.model.canSendCommand(.resume)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "paused", version: 99)), .outdated) + XCTAssertEqual(fixture.model.response?.executionBatch, 9002) + XCTAssertEqual(fixture.model.telemetry.batteryText, "—") + } + + func testPausedUsesLocalCopyAndResumePermissionInsteadOfStartGateOrCommandLabels() async throws { + let fixture = try FlightControlFixture(state: "paused") + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .paused) + XCTAssertEqual(fixture.model.presentation.title, "无人机已暂停") + XCTAssertEqual(fixture.model.presentation.actionTitle, "继续任务") + XCTAssertTrue(fixture.model.presentation.isActionEnabled) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.resume)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + fixture.service.nextSnapshot = try FlightControlFixture.snapshot(state: "executing", version: 2) + await fixture.model.sendCommand(.resume) + XCTAssertEqual(fixture.service.commands, [.resume]) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + XCTAssertNil(fixture.model.pendingCommand) + } + + func testMissingUnknownMismatchedAndContradictoryControlCannotEnableAnyDeviceAction() async throws { + let controls: [Any] = [NSNull(), [:], ["state": "future", "execution_batch": 9001], + ["state": "executing", "execution_batch": 9002, "can_pause": true], + ["state": "paused", "execution_batch": 9001, "resume_phase": "shooting", "drone_in_dock": "inside", "can_resume": true], + ["state": "returned", "execution_batch": 9001, "drone_in_dock": "outside"], + ["state": "returned", "execution_batch": 9001]] + for control in controls { + let fixture = try FlightControlFixture() + fixture.service.value = try FlightControlFixture.snapshot(state: "executing", phase: "arrived_pending_start", + changes: ["flight_control": control, "execute_gate": ["can_execute": true, "primary_action": "start_shoot"], + "restart_gate": ["can_restart": true]]) + await fixture.model.refresh() + for command in DroneDockSafetyCommand.allCases { XCTAssertFalse(fixture.model.canSendCommand(command)) } + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertFalse(fixture.model.canResummon) + } + } + + func testManualReturnKeepsFailureResultAndRequiresInsideAndRestartGate() async throws { + let fixture = try FlightControlFixture(state: "returning", reason: "manual") + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .returning) + XCTAssertEqual(fixture.model.presentation.title, "无人机正在返航") + XCTAssertEqual(fixture.model.presentation.actionTitle, "拍摄已中断") + XCTAssertFalse(fixture.model.presentation.isActionEnabled) + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + XCTAssertFalse(fixture.model.canSendCommand(.returnHome)) + XCTAssertFalse(fixture.model.canResummon) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + for gate in [false, true] { + fixture.service.value = try FlightControlFixture.snapshot(state: "returned", reason: "manual", version: gate ? 3 : 2, + changes: ["restart_gate": ["can_restart": gate]]) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .returned) + XCTAssertEqual(fixture.model.response?.task?.status, 40) + XCTAssertEqual(fixture.model.canResummon, gate) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + XCTAssertTrue(fixture.model.availableSafetyCommands.isEmpty) + } + } + + func testIdleAndFailureCannotProveReturnEvenIfBackendRestartGateIsTrue() async throws { + for state in ["returning", "unknown"] { + let fixture = try FlightControlFixture(state: state, reason: "manual") + fixture.service.value = try FlightControlFixture.snapshot(state: state, reason: "manual", + changes: ["restart_gate": ["can_restart": true]]) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.canResummon) + XCTAssertNotEqual(fixture.model.presentation.phase, .returned) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + } + } + + func testPausedReturnResumesReturningAndNeverStartsShooting() async throws { + let fixture = try FlightControlFixture(state: "paused", reason: "manual") + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .paused) + XCTAssertTrue(fixture.model.presentation.message.contains("恢复返航")) + XCTAssertTrue(fixture.model.canSendCommand(.resume)) + XCTAssertFalse(fixture.model.canSendCommand(.returnHome)) + fixture.service.nextSnapshot = try FlightControlFixture.snapshot(state: "returning", reason: "manual", version: 2) + await fixture.model.sendCommand(.resume) + XCTAssertEqual(fixture.service.commands, [.resume]) + XCTAssertEqual(fixture.service.startCount, 0) + XCTAssertEqual(fixture.model.presentation.phase, .returning) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + } + + func testNormalRecordingCompletionStaysDistinctFromInterruptedReturnIncludingPausedReturn() async throws { + for state in ["returning", "returned", "unknown", "paused"] { + let fixture = try FlightControlFixture(state: state, reason: "normal_complete") + await fixture.model.refresh() + XCTAssertEqual(fixture.model.response?.task?.status, 25) + XCTAssertTrue(fixture.model.isRecordingFinished) + XCTAssertEqual(fixture.model.presentation.phase, state == "paused" ? .paused : .postShootUploading) + XCTAssertFalse(fixture.model.canResummon) + if state == "paused" { XCTAssertTrue(fixture.model.canSendCommand(.resume)) } + } + } + + /// 未知业务枚举不能开放开拍,也不能抹掉独立且可信的安全控制权限。 + func testUnknownBusinessStatusKeepsAuthorizedSafetyActionsWithoutEnablingStart() async throws { + let fixture = try FlightControlFixture() + fixture.service.value = try FlightControlFixture.snapshot(state: "executing", phase: "arrived_pending_start", changes: [ + "task": ["id": 501, "status": 99], "order_flight_task": ["id": 501, "status": 99]]) + await fixture.model.refresh() + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + XCTAssertFalse(fixture.model.canSendCommand(.resume)) + XCTAssertFalse(fixture.model.canSendCommand(.cancelReturn)) + XCTAssertFalse(fixture.model.canStartShooting) + } + + /// 身份和版本是所有控制的前提,已知业务状态额外约束开拍而非安全指令。 + func testStartRequiresResponseIdentityAndVersionWithKnownTaskState() async throws { + let cases: [(changes: [String: Any], canReturn: Bool)] = [ + (["order_flight_task_id": NSNull(), "task": ["status": 20], "order_flight_task": ["status": 20]], false), + (["state_version": NSNull()], false), + (["task": ["id": 501, "status": 99], "order_flight_task": ["id": 501, "status": 99]], true) + ] + for (changes, canReturn) in cases { + let fixture = try FlightControlFixture() + let gates: [String: Any] = ["execute_gate": ["can_execute": true, "primary_action": "start_shoot"]] + fixture.service.value = try FlightControlFixture.snapshot(state: "executing", phase: "arrived_pending_start", + changes: gates.merging(changes) { _, new in new }) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertEqual(fixture.model.canSendCommand(.returnHome), canReturn) + } + } + + func testAcceptedReceiptWaitsForNewMatchingFullSnapshot() async throws { + let fixture = try FlightControlFixture() + await fixture.model.refresh() + fixture.service.receiptChanges = ["device_confirmed": false, "state_version": 3] + await fixture.model.sendCommand(.pause) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + XCTAssertEqual(fixture.model.presentation.title, "无人机正在拍摄中") + XCTAssertTrue(fixture.model.isCommandLoading(.pause)) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "paused", version: 1)), .outdated) + XCTAssertNotNil(fixture.model.pendingCommand) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "paused", version: 2)), .outdated) + XCTAssertNotNil(fixture.model.pendingCommand, "不能早于指令回执对应版本") + fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "unknown", version: 3)) + XCTAssertNotNil(fixture.model.pendingCommand, "新版本本身不是执行确认") + fixture.model.applyTaskSnapshot(try FlightControlFixture.snapshot(state: "paused", version: 4)) + XCTAssertNil(fixture.model.pendingCommand) + XCTAssertEqual(fixture.model.presentation.phase, .paused) + XCTAssertTrue(fixture.model.canSendCommand(.resume)) + } + + func testFullSnapshotArrivingBeforeReceiptCanConfirmSameOperation() async throws { + let fixture = try FlightControlFixture() + await fixture.model.refresh() + fixture.service.onCommand = { + fixture.model.applyTaskSnapshot(try! FlightControlFixture.snapshot(state: "paused", version: 2)) + } + fixture.service.receiptChanges = ["state_version": 2] + await fixture.model.sendCommand(.pause) + XCTAssertNil(fixture.model.pendingCommand) + XCTAssertEqual(fixture.model.presentation.phase, .paused) + } + + func testWrongReceiptIdentityOrMissingAcceptanceKeepsUnknownOutcomeLock() async throws { + for changes: [String: Any] in [ + ["execution_batch": 9002], ["plane_id": 99], ["airport_sn": "OTHER"], ["accepted": NSNull()], + ["flight_control": ["execution_batch": 9002]] + ] { + let fixture = try FlightControlFixture() + await fixture.model.refresh() + fixture.service.receiptChanges = changes + await fixture.model.sendCommand(.pause) + XCTAssertTrue(fixture.model.commandOutcomeUnknown) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertNil(fixture.model.commandResponse) + } + } + + func testExplicitRejectedReceiptAllowsUserRetryWithoutPretendingAccepted() async throws { + let fixture = try FlightControlFixture() + await fixture.model.refresh() + fixture.service.receiptChanges = ["accepted": false] + await fixture.model.sendCommand(.pause) + XCTAssertFalse(fixture.model.commandOutcomeUnknown) + XCTAssertNil(fixture.model.pendingCommand) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + } + + func testNewBatchDiscardsPendingCommandAndLateOldReceipt() async throws { + let fixture = try FlightControlFixture() + await fixture.model.refresh() + fixture.service.onCommand = { + fixture.model.applyTaskSnapshot(try! FlightControlFixture.snapshot(state: "executing", batch: 9002)) + } + await fixture.model.sendCommand(.pause) + XCTAssertNil(fixture.model.pendingCommand) + XCTAssertNil(fixture.model.commandResponse) + XCTAssertFalse(fixture.model.commandOutcomeUnknown) + XCTAssertEqual(fixture.model.response?.executionBatch, 9002) + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + } + + func testNewBatchIgnoresLateFailureOfOldCommand() async throws { + let fixture = try FlightControlFixture() + await fixture.model.refresh() + fixture.service.commandError = APIError.networkFailed("旧批次指令网络失败") + fixture.service.onCommand = { + fixture.model.applyTaskSnapshot(try! FlightControlFixture.snapshot(state: "executing", batch: 9002)) + } + await fixture.model.sendCommand(.pause) + XCTAssertNil(fixture.model.pendingCommand) + XCTAssertFalse(fixture.model.commandOutcomeUnknown) + XCTAssertEqual(fixture.model.response?.executionBatch, 9002) + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + } + + func testConflictingReturnResultCannotDeclareCompletionOrEnableResummon() async throws { + let fixture = try FlightControlFixture() + let task: [String: Any] = ["id": 501, "status": 40, "result_code": "return_home"] + fixture.service.value = try FlightControlFixture.snapshot(state: "returned", reason: "normal_complete", + changes: ["task": task, "order_flight_task": task]) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .unknown) + XCTAssertFalse(fixture.model.canResummon) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + XCTAssertFalse(fixture.model.isRecordingFinished) + } + + func testAbnormalReturnNeverUsesStaleCompletionPhaseToStopLive() async throws { + let fixture = try FlightControlFixture(state: "returning", reason: "abnormal") + fixture.service.value = try FlightControlFixture.snapshot(state: "returning", reason: "abnormal", phase: "post_shoot_uploading") + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .returning) + XCTAssertFalse(fixture.model.isRecordingFinished) + XCTAssertFalse(fixture.model.shouldStopLiveReception) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + } +} + +/// 每份匿名快照明确区分设备飞行态与拍摄结果,所有操作只在内存记录。 +@MainActor +private struct FlightControlFixture { + let service: FlightControlService + let model: DroneDockShootingTaskViewModel + + init(state: String = "executing", reason: String? = nil, + countdownNow: @escaping @Sendable () -> ContinuousClock.Instant = { ContinuousClock.now }) throws { + service = FlightControlService(value: try Self.snapshot(state: state, reason: reason)) + let context = DroneDockShootingTaskTestData.context() + model = DroneDockShootingTaskViewModel(context: context, taskID: 501, order: try DroneDockShootingTaskTestData.order(), + service: service, startService: service, commandService: service, resummonService: service, + countdownNow: countdownNow, currentContext: { context }) + } + + static func snapshot(state: String, reason: String? = nil, version: Int = 1, batch: Int = 9001, + phase: String? = nil, resumePhase: String? = nil, + changes: [String: Any] = [:]) throws -> DroneDockShootingResponse { + let interrupted = reason == "manual" || reason == "abnormal" + let normal = reason == "normal_complete" + let status = interrupted ? 40 : normal ? 25 : 20 + let businessPhase = phase ?? (state == "starting" ? "going_to_spot" : state == "paused" ? "manual_paused" + : normal ? "post_shoot_uploading" : interrupted ? "returning_home" : "shooting") + let resume = resumePhase ?? (reason != nil ? "returning" : businessPhase == "arrived_pending_start" ? "arrived_pending_start" + : state == "starting" ? "going_to_spot" : "shooting") + let control = DroneDockShootingTaskTestData.flightControl(state: state, batch: batch, + canPause: state == "executing" || state == "returning", canResume: state == "paused", + canReturn: state == "starting" || state == "executing" || (state == "paused" && resume != "returning"), + resumePhase: resume, returnReason: reason, + droneInDock: state == "unknown" ? nil : state == "returned" || state == "starting" ? "inside" : "outside", + isAirborne: state == "unknown" ? nil : state != "returned" && state != "starting", + pauseReason: state == "paused" ? "manual" : businessPhase == "arrived_pending_start" ? "arrival_wait" : nil) + let task: [String: Any] = ["id": 501, "status": status, "wayline_status": normal ? 24 : interrupted ? 91 : 20, + "result_code": interrupted ? "return_home" : ""] + let value: [String: Any] = [ + "order_flight_task_id": 501, "execution_batch": batch, "state_version": version, "snapshot_kind": "full", + "task": task, "order_flight_task": task, + "current_plane": ["id": 58, "sn_number": "LOCAL-FLIGHT-058", "work_status": 1, "online_status": 1], + "restart_gate": ["can_restart": true], + "execute_gate": ["can_execute": businessPhase == "arrived_pending_start", + "primary_action": businessPhase == "arrived_pending_start" ? "start_shoot" : "blocked"], + "ui": ["phase": businessPhase, + "title": "错误接口标题", "message": "错误接口提示", "commands": [["command": "return_home_cancel"]]], + "flight_control": control] + return try DroneDockShootingTaskTestData.decode(value.merging(changes) { _, new in new }) + } +} + +/// 不访问网络的同任务读取、控制和重召唤替身。 +@MainActor +private final class FlightControlService: DroneDockShootingServing, DroneDockCommandSending, DroneDockStartShooting, DroneDockResummonServing { + var value: DroneDockShootingResponse + var nextSnapshot: DroneDockShootingResponse? + var receiptChanges: [String: Any] = [:] + var onCommand: (() -> Void)? + var commandError: Error? + var commands: [DroneDockSafetyCommand] = [] + var startCount = 0 + + init(value: DroneDockShootingResponse) { self.value = value } + func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse { value } + func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse { + commands.append(command) + let batch = value.executionBatch ?? 9001 + onCommand?() + if let commandError { throw commandError } + if let nextSnapshot { value = nextSnapshot } + let receipt: [String: Any] = ["order_flight_task_id": taskID, "command": command.rawValue, + "execution_batch": batch, "accepted": true, "device_confirmed": false, + "command_id": "local-flight-\(clientRequestID)", "client_request_id": clientRequestID, + "plane_id": 58, "airport_sn": "LOCAL-FLIGHT-058"] + return try JSONDecoder().decode(DroneDockCommandResponse.self, + from: JSONSerialization.data(withJSONObject: receipt.merging(receiptChanges) { _, new in new })) + } + func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse { + startCount += 1 + throw APIError.networkFailed("本地测试不应触发开拍") + } + func resummon(taskID: Int) async throws -> DroneDockShootResponse { throw APIError.networkFailed("本地测试不触发重召唤") } +} diff --git a/suixinkanTests/DroneDockMaterialsViewTests.swift b/suixinkanTests/DroneDockMaterialsViewTests.swift index 952e1ac..6446b44 100644 --- a/suixinkanTests/DroneDockMaterialsViewTests.swift +++ b/suixinkanTests/DroneDockMaterialsViewTests.swift @@ -8,43 +8,77 @@ final class DroneDockMaterialsViewTests: XCTestCase { private weak var previousKeyWindow: UIWindow? private let number = "TEST-MATERIAL-ORDER" - /// 查看已有任务沿用服务端 task_id,整个入口没有任务创建或召唤请求。 - func testViewRecordedTaskOpensSameIDWithoutCreatingOrSummoning() async throws { - var opened: [Int] = [] - let destination = UIViewController() - let (controller, session) = try makeController([detail(), taskList([task(51)])], taskFactory: { id, order, context in - opened.append(id) - XCTAssertEqual(order.orderNumber, self.number) - XCTAssertEqual(context.scenicID, 128) - return destination - }) + /// 有任务的素材库仅保留刷新入口,不再从导航栏打开拍摄任务。 + func testNavigationOnlyShowsRefreshForExistingTasks() async throws { + let (controller, session) = try makeController([detail(), taskList([task(51)])]) let window = show(controller) defer { close(window) } try await settle(window) { controller.viewModel.total == 1 } - let button = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first { - $0.accessibilityIdentifier == "drone.materials.remote.viewTasks" - }) - XCTAssertTrue(button.isEnabled) - UIApplication.shared.sendAction(try XCTUnwrap(button.action), to: button.target, from: button, for: nil) - try await settle(window) { controller.navigationController?.topViewController === destination } - XCTAssertEqual(opened, [51]) + XCTAssertEqual(controller.navigationItem.rightBarButtonItems?.map(\.accessibilityIdentifier), ["drone.materials.remote.refresh"]) + XCTAssertTrue(controller.navigationItem.rightBarButtonItem?.isEnabled == true) + XCTAssertTrue(controller.navigationController?.topViewController === controller) XCTAssertEqual(session.requests.count, 2) XCTAssertTrue(session.requests.allSatisfy { $0.httpMethod == "GET" }) } - /// 空任务列表保持入口不可用,不通过创建任务补齐条件。 - func testViewTaskEntryIsDisabledForEmptyOrder() async throws { + /// 空任务列表同样不显示查看任务,不通过创建任务补齐条件。 + func testNavigationOnlyShowsRefreshForEmptyOrder() async throws { let (controller, session) = try makeController([detail(), taskList([])]) let window = show(controller) defer { close(window) } try await settle(window) { controller.viewModel.total == 0 } - let button = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first { - $0.accessibilityIdentifier == "drone.materials.remote.viewTasks" - }) - XCTAssertFalse(button.isEnabled) + XCTAssertEqual(controller.navigationItem.rightBarButtonItems?.map(\.accessibilityIdentifier), ["drone.materials.remote.refresh"]) XCTAssertEqual(session.requests.count, 2) } + /// 长点位在与云端上传一致的最大宽度内完整换行,筛选仍使用原点位 ID。 + func testLongPointFilterWrapsAndRemainsSelectableWithoutOverlappingSummary() async throws { + let name = "测试景区东南观景平台通往山顶步道的全景航拍游客打卡点—LongScenicViewpointName" + let (controller, session) = try makeController([ + detail(pointNames: [name, "短点位"]), taskList([task(51)]), taskList([task(51)])]) + let window = show(controller) + defer { close(window) } + try await settle(window) { controller.viewModel.total == 1 } + let list = try collection(controller) + let card = try XCTUnwrap(find(list, id: "drone.materials.filter.201") as? UICollectionViewCell) + let label = try XCTUnwrap(card.contentView.subviews.first as? UILabel) + let all = try XCTUnwrap(find(list, id: "drone.materials.filter.all") as? UICollectionViewCell) + let summary = try XCTUnwrap(find(list, id: "drone.materials.remote.summary") as? UICollectionViewCell) + XCTAssertEqual(label.text, name) + XCTAssertEqual(label.numberOfLines, 0) + XCTAssertEqual(label.lineBreakMode, .byWordWrapping) + XCTAssertLessThanOrEqual(card.bounds.width, min(200, list.bounds.width - 32)) + XCTAssertGreaterThan(card.bounds.height, 40) + XCTAssertGreaterThanOrEqual(label.bounds.height + 1, + label.sizeThatFits(CGSize(width: label.bounds.width, height: .greatestFiniteMagnitude)).height) + XCTAssertLessThan(all.bounds.width, card.bounds.width) + XCTAssertLessThanOrEqual(card.convert(card.bounds, to: list).maxY, + summary.convert(summary.bounds, to: list).minY) + try selectFilter(201, list: list) + try await settle(window) { controller.viewModel.selectedSpotID == 201 && session.requests.count == 3 } + XCTAssertEqual(query(try XCTUnwrap(session.requests.last))["scenic_spot_id"], "201") + capture(window, name: "订单素材库-点位名称完整换行") + } + + /// 小宽度下卡片高度容纳完整名称,复用到原有单行调用时恢复默认样式。 + func testFilterWrappingFitsNarrowWidthsAndPreservesSharedDefault() throws { + let title = "佛顶塔七楼西南角观景平台超长名称的游客航拍打卡点" + for maximumWidth: CGFloat in [160, 200] { + let size = DroneMaterialFilterCell.wrappedSize(title: title, maximumWidth: maximumWidth) + let cell = DroneMaterialFilterCell(frame: CGRect(origin: .zero, size: size)) + cell.apply(title: title, id: "201", selected: false, locked: false, wrapsTitle: true) + cell.layoutIfNeeded() + let label = try XCTUnwrap(cell.contentView.subviews.first as? UILabel) + XCTAssertLessThanOrEqual(cell.bounds.width, maximumWidth) + XCTAssertGreaterThan(cell.bounds.height, 40) + XCTAssertGreaterThanOrEqual(label.bounds.height + 1, + label.sizeThatFits(CGSize(width: label.bounds.width, height: .greatestFiniteMagnitude)).height) + cell.apply(title: "短点位", id: "202", selected: true, locked: false) + XCTAssertEqual(label.numberOfLines, 1) + XCTAssertEqual(label.lineBreakMode, .byTruncatingTail) + } + } + /// 下载只覆盖已选就绪原素材,图片及视频正确保存,既有成片不进入批次。 func testSelectionControlsDownloadReadyRawFilesAndSaveCorrectMediaTypes() async throws { var record = task(1, status: 30) @@ -534,8 +568,7 @@ final class DroneDockMaterialsViewTests: XCTestCase { private func makeController(_ responses: [Data], deliveryFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil, previewFactory: ((URL, Bool, String) -> UIViewController)? = nil, - downloadModel: DroneDockMaterialDownloadViewModel? = nil, - taskFactory: ((Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) throws -> (DroneDockMaterialsViewController, MockURLSession) { + downloadModel: DroneDockMaterialDownloadViewModel? = nil) throws -> (DroneDockMaterialsViewController, MockURLSession) { let context = DroneDockHomeContext(userID: "materials-ui-user", accountType: "store_user", scenicID: 128, scenicName: "测试景区", storeID: 37, photographerName: "测试工作人员", token: "materials-ui-token") let session = MockURLSession(responses: responses) @@ -546,14 +579,15 @@ final class DroneDockMaterialsViewTests: XCTestCase { return (DroneDockMaterialsViewController(viewModel: model, deliveryControllerFactory: deliveryFactory, thumbnailProvider: { _, _ in nil }, mediaPreviewControllerFactory: previewFactory, - downloadViewModel: downloadModel, taskControllerFactory: taskFactory), session) + downloadViewModel: downloadModel), session) } - private func detail(used: Int = 1, canUpload: Bool = false) throws -> Data { + private func detail(used: Int = 1, canUpload: Bool = false, + pointNames: [String] = ["测试点位一", "测试点位二"]) throws -> Data { try envelope(["order_number": number, "user_phone": "130****0001", "project_name": "测试航拍套餐", "order_status": 20, "can_upload_film": canUpload, "shoot_count": 5, "shot_count": used, "remaining_count": 5 - used, "shoot_status": "processing", - "spot": [["scenic_spot_id": 201, "scenic_spot_name": "测试点位一"], ["scenic_spot_id": 202, "scenic_spot_name": "测试点位二"]]]) + "spot": pointNames.enumerated().map { ["scenic_spot_id": 201 + $0.offset, "scenic_spot_name": $0.element] }]) } private func taskList(_ tasks: [[String: Any]]) throws -> Data { diff --git a/suixinkanTests/DroneDockResummonLiveViewTests.swift b/suixinkanTests/DroneDockResummonLiveViewTests.swift index 6646127..6307380 100644 --- a/suixinkanTests/DroneDockResummonLiveViewTests.swift +++ b/suixinkanTests/DroneDockResummonLiveViewTests.swift @@ -18,6 +18,7 @@ final class DroneDockResummonLiveViewTests: XCTestCase { let fixedIDs = ["top", "stateContainer", "safety"] let frames = try fixedIDs.map { try XCTUnwrap(find(controller.view, suffix: $0)).frame } let oldTitle = model.presentation.title + let oldBatch = try XCTUnwrap(model.response?.executionBatch) let oldBattery = find(controller.view, suffix: "metric.battery")?.accessibilityValue let button = try XCTUnwrap(find(controller.view, suffix: "failureRetry") as? UIButton) capture(window, name: "重新召唤-失败任务-本地模拟") @@ -28,8 +29,10 @@ final class DroneDockResummonLiveViewTests: XCTestCase { XCTAssertEqual(model.presentation.title, oldTitle) XCTAssertEqual(find(controller.view, suffix: "metric.battery")?.accessibilityValue, oldBattery) try await settle(window) { - model.hasSubmittedResummon && !model.isResummoning && model.presentation.phase == .ready + (model.response?.executionBatch ?? 0) > oldBatch + && !model.isResummoning && model.presentation.phase == .ready } + XCTAssertFalse(model.hasSubmittedResummon, "新的执行批次应清除上一批次的重召唤锁") XCTAssertFalse(model.canResummon) XCTAssertTrue(model.canStartShooting) for (suffix, frame) in zip(fixedIDs, frames) { @@ -149,7 +152,8 @@ final class DroneDockResummonLiveViewTests: XCTestCase { XCTAssertEqual(controller.liveViewModel.state, .unavailable("暂未提供图传播放参数")) XCTAssertNil(controller.liveViewModel.playbackURL) XCTAssertEqual((find(controller.view, suffix: "live.status") as? UILabel)?.text, "暂未提供图传播放参数") - XCTAssertTrue(try XCTUnwrap(find(controller.view, suffix: "live.source")).isHidden) + XCTAssertTrue(try XCTUnwrap(find(controller.view, suffix: "live.badge")).isHidden, + "实时标识整体隐藏后,内部文案标签不需要单独隐藏") let feed = try XCTUnwrap(find(controller.view, suffix: "feedPlaceholder")) XCTAssertNil(feed.layer.sublayers?.compactMap { $0 as? AVPlayerLayer }.first?.player) capture(window, name: "图传-缺少播放参数") diff --git a/suixinkanTests/DroneDockResummonViewModelTests.swift b/suixinkanTests/DroneDockResummonViewModelTests.swift index a01972a..8aae38f 100644 --- a/suixinkanTests/DroneDockResummonViewModelTests.swift +++ b/suixinkanTests/DroneDockResummonViewModelTests.swift @@ -20,6 +20,8 @@ final class DroneDockResummonViewModelTests: XCTestCase { let samples = [ try ResummonData.snapshot(phase: "shooting", status: 20), try ResummonData.snapshot(phase: "returning"), + try ResummonData.snapshot(canRestart: false), + try ResummonData.snapshot(includeFlightControl: false), try ResummonData.snapshot(plane: ["id": 58, "online_status": 2]), try ResummonData.snapshot(plane: ["id": 0]), try DroneDockShootingTaskTestData.response(changes: ["task": ["status": 40], "order_flight_task": ["status": 40]]) @@ -39,7 +41,7 @@ final class DroneDockResummonViewModelTests: XCTestCase { let fixture = try ResummonFixture() await fixture.model.refresh() let previous = fixture.model.response - let next = try ResummonData.snapshot(phase: "arrived_pending_start", status: 20) + let next = try ResummonData.snapshot(phase: "arrived_pending_start", status: 20, batch: 101) fixture.write.onRequest = { fixture.read.result = .success(next) } var sawReceiptWithOldSnapshot = false await fixture.model.resummon { @@ -55,7 +57,7 @@ final class DroneDockResummonViewModelTests: XCTestCase { XCTAssertEqual(fixture.model.response, next) XCTAssertEqual(fixture.model.presentation.phase, .ready) XCTAssertTrue(fixture.model.canStartShooting) - XCTAssertTrue(fixture.model.hasSubmittedResummon) + XCTAssertFalse(fixture.model.hasSubmittedResummon, "新执行批次清理上一批次的重召唤锁") XCTAssertFalse(fixture.model.isResummoning) } @@ -104,7 +106,7 @@ final class DroneDockResummonViewModelTests: XCTestCase { XCTAssertTrue(fixture.model.statusMessage.contains("重新召唤结果待核对")) XCTAssertEqual(fixture.model.presentation.action, .refresh) fixture.model.invalidate(preservingSnapshot: true) - fixture.read.result = .success(try ResummonData.snapshot(phase: "arrived_pending_start", status: 20)) + fixture.read.result = .success(try ResummonData.snapshot(phase: "arrived_pending_start", status: 20, version: 2)) await fixture.model.refresh() XCTAssertFalse(fixture.model.canStartShooting) XCTAssertFalse(fixture.model.canSendCommand(.pause)) @@ -227,10 +229,10 @@ final class DroneDockResummonViewModelTests: XCTestCase { await fixture.model.refresh() await fixture.model.startShooting() XCTAssertTrue(fixture.model.hasSubmittedStart) - fixture.read.result = .success(try ResummonData.snapshot()) + fixture.read.result = .success(try ResummonData.snapshot(version: 2)) await fixture.model.refresh() XCTAssertTrue(fixture.model.canResummon) - let nextReady = try ResummonData.snapshot(phase: "arrived_pending_start", status: 20) + let nextReady = try ResummonData.snapshot(phase: "arrived_pending_start", status: 20, batch: 101) fixture.write.onRequest = { fixture.read.result = .success(nextReady) } await fixture.model.resummon() XCTAssertFalse(fixture.model.hasSubmittedStart) @@ -308,7 +310,7 @@ private final class ResummonOtherActions: DroneDockStartShooting, DroneDockComma } /// 记录安全指令,不向设备发送请求。 - func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse { + func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse { commandCount += 1 throw APIError.serverCode(100099, "测试指令未启用") } @@ -318,8 +320,21 @@ private final class ResummonOtherActions: DroneDockStartShooting, DroneDockComma private enum ResummonData { /// 构造失败或后续阶段快照,供验证受理回执不会覆盖真实状态。 static func snapshot(phase: String = "failed", status: Int = 40, - plane: [String: Any] = ["id": 58, "online_status": 1, "work_status": 1]) throws -> DroneDockShootingResponse { - try DroneDockShootingTaskTestData.response(changes: [ + plane: [String: Any] = ["id": 58, "online_status": 1, "work_status": 1], + canRestart: Bool = true, includeFlightControl: Bool = true, + batch: Int = 100, version: Int = 1) throws -> DroneDockShootingResponse { + let returning = phase == "returning" + let starting = phase == "going_to_spot" + let returned = status == 40 && !returning + let control = DroneDockShootingTaskTestData.flightControl( + state: returned ? "returned" : returning ? "returning" : starting ? "starting" : "executing", batch: batch, + canPause: status == 20 && !starting, canResume: false, canReturn: status == 20, + returnReason: returning ? "manual" : nil, droneInDock: returned || starting ? "inside" : "outside", + isAirborne: !returned && !starting, pauseReason: phase == "arrived_pending_start" ? "arrival_wait" : nil) + return try DroneDockShootingTaskTestData.response(changes: [ + "execution_batch": batch, "state_version": version, "snapshot_kind": "full", + "flight_control": includeFlightControl ? control : NSNull(), + "restart_gate": ["can_restart": canRestart, "code": canRestart ? "ok" : "blocked"], "order_flight_task": ["id": 501, "status": status], "task": ["id": 501, "status": status], "current_plane": plane, "execute_gate": ["can_execute": phase == "arrived_pending_start", "primary_action": "start_shoot"], diff --git a/suixinkanTests/DroneDockShootingRealtimeTests.swift b/suixinkanTests/DroneDockShootingRealtimeTests.swift index 1567a8f..c9065f2 100644 --- a/suixinkanTests/DroneDockShootingRealtimeTests.swift +++ b/suixinkanTests/DroneDockShootingRealtimeTests.swift @@ -42,6 +42,148 @@ final class DroneDockShootingRealtimeTests: XCTestCase { XCTAssertThrowsError(try DroneDockShootingSocketMessage.decode(RealtimeTestData.push(missing))) } + /// 新版订阅失败不含任务 ID,仍须按 type/subscribed 与错误码立即识别。 + func testSubscriptionFailureAckDoesNotRequireTaskIdentity() throws { + for (code, message) in [(100098, "票据已过期"), (100099, "任务不存在")] { + let result = try DroneDockShootingSocketMessage.decode(RealtimeTestData.subscriptionFailure(code, message)) + guard case .subscriptionRejected(let actualCode, let actualMessage) = result else { + return XCTFail("310 失败回执不能等待任务 ID 或成功快照") + } + XCTAssertEqual(actualCode, code) + XCTAssertEqual(actualMessage, message) + } + } + + /// 下行就绪和订阅入站回执只提供诊断,不能冒充正式订阅结果或吞掉错误码。 + func testReadyAndReceivedAreDiagnosticMessagesOnly() throws { + for ack in ["ready", "received"] { + guard case .unrelated = try DroneDockShootingSocketMessage.decode(RealtimeTestData.transportAck(ack)) else { + return XCTFail("\(ack) 不代表订阅成功") + } + let decorated = try JSONSerialization.data(withJSONObject: ["code": 100000, "data": [ + "ack": ack, "type": 310, "subscribed": true, "has_snapshot": true, "order_flight_task_id": 501, + "action": "app_airport_shooting_updated", "params": RealtimeTestData.payload() + ]]) + guard case .unrelated = try DroneDockShootingSocketMessage.decode(decorated) else { + return XCTFail("诊断 ack 误带订阅或快照字段仍不能推进状态") + } + for code in [100098, 100099] { + guard case .rejected(let actualCode, _) = try DroneDockShootingSocketMessage.decode( + RealtimeTestData.transportAck(ack, code: code)) else { + return XCTFail("诊断 ack 字段不能掩盖失败业务码") + } + XCTAssertEqual(actualCode, code) + } + } + } + + /// 明确的 310 拒绝停止 HTTP 与 WS,不依赖中文文案白名单。 + func testSubscriptionFailureCodeStopsReadingRegardlessOfMessage() async throws { + for message in ["任务不存在", "数据不存在", "Permission denied"] { + let harness = RealtimeHarness() + let model = try model() + await model.refresh() + harness.session.onConnectionState = { state in + if case .denied(let reason) = state { model.stopReading(message: reason) } + } + harness.session.start() + await settle { harness.sockets.count == 1 && harness.sockets[0].sent.count == 1 } + harness.sockets[0].emit(try RealtimeTestData.transportAck("ready")) + harness.sockets[0].emit(try RealtimeTestData.transportAck("received")) + harness.sockets[0].emit(try RealtimeTestData.subscriptionFailure(100099, message)) + await settle { harness.session.state == .denied(message) } + XCTAssertFalse(model.canContinuePolling) + XCTAssertFalse(model.presentation.isActionEnabled) + XCTAssertNotNil(model.response, "无权限后保留已有只读画面") + XCTAssertFalse(harness.clock.has(1), "明确拒绝不安排重连") + harness.session.stop() + harness.session.start() + await Task.yield() + XCTAssertEqual(harness.tickets.count, 1) + XCTAssertEqual(harness.sockets[0].closeCount, 1) + } + } + + /// 新版无 ID 的票据失败只换票重连,不停止任务读取或误判 App 登录失效。 + func testExpiredSubscriptionFailureAckRenewsTicket() async throws { + let harness = RealtimeHarness() + harness.session.start() + defer { harness.session.stop() } + await settle { harness.sockets.count == 1 && harness.sockets[0].sent.count == 1 } + harness.sockets[0].emit(try RealtimeTestData.transportAck("ready")) + harness.sockets[0].emit(try RealtimeTestData.transportAck("received")) + harness.sockets[0].emit(try RealtimeTestData.subscriptionFailure(100098, "票据已过期")) + await settle { harness.clock.has(1) } + guard case .fallback = harness.session.state else { return XCTFail("换票期间应保留 HTTP 兜底") } + harness.clock.fire(seconds: 1) + await settle { harness.sockets.count == 2 && harness.sockets[1].sent.count == 1 } + XCTAssertEqual(harness.tickets.count, 2) + XCTAssertTrue(harness.sockets[1].sent[0].contains("MOCK-TICKET-2")) + } + + /// 非订阅失败的通用业务错误仍走临时兜底,不能仅凭 100099 永久锁定任务。 + func testGenericBusinessErrorDoesNotBecomeSubscriptionDenial() async throws { + let harness = RealtimeHarness() + harness.session.start() + defer { harness.session.stop() } + await settle { harness.sockets.count == 1 && harness.sockets[0].sent.count == 1 } + harness.sockets[0].emit(try RealtimeTestData.rejection(100099, "暂时不可用")) + await settle { harness.clock.has(1) } + guard case .fallback = harness.session.state else { return XCTFail("通用错误应保留重试") } + } + + /// 311 仅用于取消订阅;带完整参数的旧 type 外壳也不能冒充任务推送。 + func testUnsubscribeTypeCannotBeDecodedAsShootingUpdate() throws { + let unsubscribe = try XCTUnwrap(JSONSerialization.jsonObject( + with: Data(DroneDockShootingSocketMessage.unsubscribe(taskID: 501).utf8)) as? [String: Any]) + XCTAssertEqual(unsubscribe["type"] as? Int, 311) + XCTAssertEqual((unsubscribe["params"] as? [String: Any])?["id"] as? Int, 501) + XCTAssertNil((unsubscribe["params"] as? [String: Any])?["socket_token"]) + + let oldEnvelope = try JSONSerialization.data(withJSONObject: [ + "code": 100000, + "data": ["type": 311, "params": RealtimeTestData.payload()] + ]) + guard case .unrelated = try DroneDockShootingSocketMessage.decode(oldEnvelope) else { + return XCTFail("只有 app_airport_shooting_updated action 才是设备状态推送") + } + } + + /// 新飞控状态及素材上传中任务通过既有 action 完整传递,与 HTTP 使用同一解码合同。 + func testFlightControlUpdatesUseActionEnvelopeWithoutChangingUIPhase() throws { + for (index, state) in ["starting", "paused", "executing", "returning", "returned", "unknown"].enumerated() { + var payload = RealtimeTestData.payload(version: index + 10) + payload["ui"] = ["phase": "shooting"] + payload["flight_control"] = [ + "state": state, "execution_batch": 100, + "drone_in_dock": state == "returned" || state == "starting" ? "inside" : "outside", + "is_airborne": state == "unknown" ? NSNull() : (state != "returned" && state != "starting") as Any, + "pause_reason": state == "paused" ? "manual" : NSNull(), + "pending_command": NSNull(), + "can_pause": state == "executing" || state == "returning", "can_resume": state == "paused", + "can_return_home": state == "paused" || state == "executing" + ] + let httpSnapshot = try DroneDockShootingTaskTestData.decode(payload) + guard case .snapshot(let pushedSnapshot) = try DroneDockShootingSocketMessage.decode(RealtimeTestData.push(payload)) else { + return XCTFail("完整飞控状态必须通过既有 action 解析") + } + XCTAssertEqual(pushedSnapshot, httpSnapshot) + XCTAssertEqual(pushedSnapshot.flightControl?.state, state) + XCTAssertEqual(pushedSnapshot.flightControl?.executionBatch, 100) + XCTAssertEqual(pushedSnapshot.ui?.phase, "shooting", "Socket 不自行重写设备状态对应的 UI 阶段") + } + + var uploading = RealtimeTestData.mediaStagePayload(wayline: 30, version: 20) + uploading["task"] = ["id": 501, "status": 25, "wayline_status": 30] + uploading["order_flight_task"] = ["id": 501, "status": 25] + guard case .snapshot(let snapshot) = try DroneDockShootingSocketMessage.decode(RealtimeTestData.push(uploading)) else { + return XCTFail("素材上传中的任务仍须接收完整推送") + } + XCTAssertEqual(snapshot.task?.status, 25) + XCTAssertEqual(snapshot.orderFlightTask?.status, 25) + XCTAssertEqual(snapshot.ui?.phase, "post_shoot_uploading") + } + func testConnectionAndAckAloneDoNotStopHTTPAndSilenceWithPongIsHealthy() async throws { let harness = RealtimeHarness() let model = try model() @@ -102,6 +244,95 @@ final class DroneDockShootingRealtimeTests: XCTestCase { XCTAssertEqual(harness.sockets.count, 1) } + /// ready/received 无论乱序、重复或出现在 Opened 前后,都不能发 310 或跳过正式 ack 加完整快照。 + func testDiagnosticAcksKeepSubscriptionAndSnapshotRequirements() async throws { + let harness = RealtimeHarness() + harness.automaticallyOpen = false + var acceptedSnapshots = 0 + var states: [DroneDockShootingRealtimeSession.State] = [] + harness.session.onSnapshot = { _ in acceptedSnapshots += 1; return .applied } + harness.session.onConnectionState = { states.append($0) } + harness.session.start() + defer { harness.session.stop() } + await settle { harness.sockets.count == 1 && harness.clock.has(12) } + let socket = harness.sockets[0] + for ack in ["received", "ready", "ready"] { socket.emit(try RealtimeTestData.transportAck(ack)) } + await settle { socket.receiveCount >= 4 } + XCTAssertTrue(socket.sent.isEmpty) + XCTAssertFalse(harness.clock.has(20)) + XCTAssertEqual(harness.session.state, .connecting) + + socket.emit(Data("Opened".utf8)) + for ack in ["received", "received", "ready"] { socket.emit(try RealtimeTestData.transportAck(ack)) } + socket.emit(Data("Opened".utf8)) + await settle { socket.receiveCount >= 9 } + XCTAssertEqual(socket.sent.count, 1, "只有首次 Opened 触发文本订阅") + XCTAssertEqual(socket.closeCount, 0) + XCTAssertEqual(harness.clock.waitCount(seconds: 12), 1, "诊断帧不能重设计时期限") + XCTAssertEqual(acceptedSnapshots, 0) + XCTAssertFalse(states.contains(.live)) + + socket.emit(try RealtimeTestData.ack()) + socket.emit(try RealtimeTestData.transportAck("received")) + await settle { socket.receiveCount >= 11 } + XCTAssertFalse(states.contains(.live), "正式 ack 之后仍需完整快照") + XCTAssertTrue(harness.clock.has(12)) + socket.emit(try RealtimeTestData.push(RealtimeTestData.payload())) + await settle { harness.session.state == .live && !harness.clock.has(12) } + XCTAssertEqual(acceptedSnapshots, 1) + + socket.emit(try RealtimeTestData.transportAck("ready")) + socket.emit(try RealtimeTestData.transportAck("received")) + await settle { socket.receiveCount >= 14 } + XCTAssertEqual(harness.session.state, .live) + XCTAssertEqual(socket.sent.count, 1) + XCTAssertEqual(harness.tickets.count, 1) + XCTAssertEqual(harness.clock.waitCount(seconds: 12), 1) + } + + /// 诊断帧持续到达但没有正式订阅结果时,仍使用连接开始的十二秒期限。 + func testDiagnosticAcksDoNotExtendDeadlineWithOrWithoutOpened() async throws { + for receivesOpened in [false, true] { + let harness = RealtimeHarness() + harness.automaticallyOpen = false + harness.session.start() + defer { harness.session.stop() } + await settle { harness.sockets.count == 1 && harness.clock.has(12) } + let socket = harness.sockets[0] + if receivesOpened { socket.emit(Data("Opened".utf8)) } + for ack in ["ready", "received", "received", "ready"] { + socket.emit(try RealtimeTestData.transportAck(ack)) + } + await settle { socket.receiveCount >= (receivesOpened ? 6 : 5) } + XCTAssertEqual(socket.sent.count, receivesOpened ? 1 : 0) + XCTAssertEqual(harness.session.state, .connecting) + XCTAssertTrue(harness.clock.has(12)) + XCTAssertEqual(harness.clock.waitCount(seconds: 12), 1) + harness.clock.fire(seconds: 12) + await settle { harness.clock.has(1) } + XCTAssertEqual(socket.closeCount, 1) + guard case .fallback = harness.session.state else { return XCTFail("无正式结果必须保留 HTTP 兜底") } + } + } + + /// 已入站不等于订阅已通过,缺少正式 ack 的完整快照也不能关闭 HTTP 兜底。 + func testReceivedAckCannotAuthorizeSnapshotBeforeFormalSubscription() async throws { + let harness = RealtimeHarness() + var acceptedSnapshots = 0 + harness.session.onSnapshot = { _ in acceptedSnapshots += 1; return .applied } + harness.session.start() + defer { harness.session.stop() } + await settle { harness.sockets.first?.sent.count == 1 } + let socket = try XCTUnwrap(harness.sockets.first) + socket.emit(try RealtimeTestData.transportAck("ready")) + socket.emit(try RealtimeTestData.transportAck("received")) + socket.emit(try RealtimeTestData.push(RealtimeTestData.payload())) + await settle { harness.clock.has(1) } + XCTAssertEqual(acceptedSnapshots, 0) + XCTAssertEqual(socket.closeCount, 1) + guard case .fallback = harness.session.state else { return XCTFail("入站回执不能替代订阅授权") } + } + /// 只有欢迎消息而没有订阅结果时仍按原期限超时,不能误判为实时连接正常。 func testOpenedWithoutAckStillTimesOut() async throws { let harness = RealtimeHarness() @@ -351,8 +582,11 @@ final class DroneDockShootingRealtimeTests: XCTestCase { empty["metrics"] = [] empty["metrics_stale"] = true XCTAssertEqual(model.applyTaskSnapshot(try DroneDockShootingTaskTestData.decode(empty)), .applied) - XCTAssertEqual(model.telemetry.batteryText, "—", "完整包不与旧 metrics 合并") + XCTAssertEqual(model.telemetry.batteryText, "0%", "同批次保留最近读数并明确显示过期") XCTAssertTrue(model.isTelemetryStale) + XCTAssertTrue(model.response?.metrics.isEmpty == true, "原始完整快照不合并旧 metrics") + let raw = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(try XCTUnwrap(model.dataJSON).utf8)) as? [String: Any]) + XCTAssertEqual((raw["metrics"] as? [Any])?.count, 0, "展示层缓存不能改写返回 JSON") } func testDelayedHTTPDoesNotOverwriteNewerPushOrIntroduceStaleError() async throws { @@ -438,7 +672,17 @@ enum RealtimeTestData { try JSONSerialization.data(withJSONObject: ["code": 100000, "msg": "OK", "data": ["action": "app_airport_shooting_updated", "params": payload]]) } static func ack(hasSnapshot: Bool = true) throws -> Data { - try JSONSerialization.data(withJSONObject: ["code": 100000, "data": ["subscribed": true, "order_flight_task_id": 501, "has_snapshot": hasSnapshot]]) + try JSONSerialization.data(withJSONObject: ["code": 100000, "data": ["type": 310, "ack": "subscribe", "subscribed": true, "order_flight_task_id": 501, "has_snapshot": hasSnapshot]]) + } + /// 文档仅约定 ack 字段,ready 不附任务身份,received 可带已入站的 type。 + static func transportAck(_ ack: String, code: Int = 100000) throws -> Data { + var body: [String: Any] = ["ack": ack] + if ack == "received" { body["type"] = 310 } + return try JSONSerialization.data(withJSONObject: ["code": code, "data": body]) + } + static func subscriptionFailure(_ code: Int, _ message: String) throws -> Data { + try JSONSerialization.data(withJSONObject: ["code": code, "msg": message, + "data": ["type": 310, "ack": "subscribe", "subscribed": false]]) } static func rejection(_ code: Int, _ message: String) throws -> Data { try JSONSerialization.data(withJSONObject: ["code": code, "msg": message, "data": []]) @@ -500,9 +744,11 @@ final class RealtimeTestSocket: DroneDockShootingSocketTransport { @MainActor final class RealtimeTestClock { private var pending: [(UUID, UInt64, CheckedContinuation)] = [] + private var waitCounts: [UInt64: Int] = [:] func wait(_ nanos: UInt64) async throws { let id = UUID() try Task.checkCancellation() + waitCounts[nanos, default: 0] += 1 try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { pending.append((id, nanos, $0)) } } onCancel: { @@ -512,6 +758,8 @@ final class RealtimeTestClock { } } } + /// 统计累计安排次数,区分保留原期限与取消后重新计时。 + func waitCount(seconds: UInt64) -> Int { waitCounts[seconds * 1_000_000_000, default: 0] } func has(_ seconds: UInt64) -> Bool { pending.contains { $0.1 == seconds * 1_000_000_000 } } func fire(seconds: UInt64) { guard let index = pending.firstIndex(where: { $0.1 == seconds * 1_000_000_000 }) else { return } diff --git a/suixinkanTests/DroneDockShootingTaskTestSupport.swift b/suixinkanTests/DroneDockShootingTaskTestSupport.swift index 8e86148..73fa67a 100644 --- a/suixinkanTests/DroneDockShootingTaskTestSupport.swift +++ b/suixinkanTests/DroneDockShootingTaskTestSupport.swift @@ -38,6 +38,22 @@ enum DroneDockShootingTaskTestData { try decode(payload().merging(changes) { _, new in new }) } + /// 新版飞控合同的显式测试数据;调用方自行选择阶段及权限,缺失场景不自动补齐。 + static func flightControl(state: String = "executing", batch: Int = 100, + canPause: Bool = true, canResume: Bool = false, canReturn: Bool = true, + resumePhase: String? = nil, returnReason: String? = nil, + droneInDock: String? = "outside", isAirborne: Bool? = true, + pauseReason: String? = nil, pendingCommand: [String: Any]? = nil) -> [String: Any] { + ["state": state, "execution_batch": batch, "can_pause": canPause, + "can_resume": canResume, "can_return_home": canReturn, + "resume_phase": resumePhase as Any? ?? NSNull(), + "return_reason": returnReason as Any? ?? NSNull(), + "drone_in_dock": droneInDock as Any? ?? NSNull(), + "is_airborne": isAirborne as Any? ?? NSNull(), + "pause_reason": pauseReason as Any? ?? NSNull(), + "pending_command": pendingCommand as Any? ?? NSNull()] + } + /// 从任意匿名 data 对象构造真实 DTO。 static func decode(_ payload: [String: Any]) throws -> DroneDockShootingResponse { try JSONDecoder().decode(DroneDockShootingResponse.self, from: JSONSerialization.data(withJSONObject: payload)) diff --git a/suixinkanTests/DroneDockShootingTaskViewModelTests.swift b/suixinkanTests/DroneDockShootingTaskViewModelTests.swift index f423980..e4cc8d3 100644 --- a/suixinkanTests/DroneDockShootingTaskViewModelTests.swift +++ b/suixinkanTests/DroneDockShootingTaskViewModelTests.swift @@ -20,6 +20,10 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase { XCTAssertTrue(fixture.model.isLoading) XCTAssertEqual(fixture.model.presentation.title, "无人机正在赶来") service.resolve(0, with: .success(try DroneDockShootingTaskTestData.response(changes: [ + "execution_batch": 100, "state_version": 1, + "flight_control": DroneDockShootingTaskTestData.flightControl( + resumePhase: "arrived_pending_start", pauseReason: "arrival_wait"), + "order_flight_task": ["id": 501, "status": 20], "task": ["id": 501, "status": 20], "ui": ["phase": "arrived_pending_start", "title": "无人机已到达"], "execute_gate": ["can_execute": true, "primary_action": "start_shoot"] ]))) @@ -103,7 +107,8 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase { XCTAssertEqual(fixture.model.applyTaskSnapshot(try DroneDockShootingTaskTestData.decode( RealtimeTestData.mediaStagePayload(wayline: 50, version: 11))), .applied) XCTAssertEqual(fixture.model.presentation.phase, .completed) - XCTAssertEqual(fixture.model.presentation.title, "素材已就绪") + XCTAssertEqual(fixture.model.presentation.title, "拍摄已完成") + XCTAssertEqual(fixture.model.presentation.message, "素材已就绪,可前往素材库查看。") XCTAssertEqual(fixture.model.presentation.action, .materials) XCTAssertTrue(fixture.model.presentation.isActionEnabled) XCTAssertEqual(fixture.model.applyTaskSnapshot(try DroneDockShootingTaskTestData.decode( @@ -170,14 +175,14 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase { XCTAssertFalse(fixture.model.isLoading) } - /// 展示当前 shooting 文案,GET 成功不替换阻止状态,也不以原订单套餐掩盖后端差异。 - func testDisplayUsesServerTaskStatePackageAndZeroTelemetry() async throws { + /// 阶段标题由本地定义,套餐和读数保留接口原值,GET 成功不替换阻止状态。 + func testDisplayUsesLocalTaskStateAndServerPackageAndZeroTelemetry() async throws { let fixture = try ShootingTaskFixture() await fixture.model.refresh() XCTAssertEqual(fixture.model.title, "测试点位 · 测试航线") XCTAssertEqual(fixture.model.subtitle, "测试游客 · 接口返回单次套餐") - XCTAssertEqual(fixture.model.statusTitle, "任务尚未关联航线") - XCTAssertEqual(fixture.model.statusMessage, "测试阶段说明") + XCTAssertEqual(fixture.model.statusTitle, "当前任务暂不可执行") + XCTAssertEqual(fixture.model.statusMessage, "测试门禁原因") XCTAssertEqual(fixture.model.deviceStatusText, "空闲 · 电量 0%") XCTAssertEqual(fixture.model.response?.executeGate?.canExecute, false) XCTAssertEqual(fixture.model.telemetry.batteryText, "0%") @@ -195,7 +200,7 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase { await fixture.model.refresh() XCTAssertEqual(fixture.model.title, "拍摄任务") XCTAssertEqual(fixture.model.statusTitle, "状态待确认") - XCTAssertEqual(fixture.model.statusMessage, "—") + XCTAssertEqual(fixture.model.statusMessage, "暂无法确认任务状态,请刷新后重试。") XCTAssertEqual(fixture.model.deviceStatusText, "—") XCTAssertEqual(fixture.model.telemetry, DroneDockShootingTelemetry(batteryText: "—", temperatureText: "—", windText: "—", rainText: "—", signalText: "—", satelliteText: "—")) @@ -234,8 +239,8 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase { XCTAssertTrue(fixture.model.isLoading) XCTAssertEqual(fixture.model.dataJSON, previousJSON) XCTAssertEqual(fixture.model.title, "测试点位 · 测试航线") - XCTAssertEqual(fixture.model.statusTitle, "任务尚未关联航线") - XCTAssertEqual(fixture.model.statusMessage, "测试阶段说明") + XCTAssertEqual(fixture.model.statusTitle, "当前任务暂不可执行") + XCTAssertEqual(fixture.model.statusMessage, "测试门禁原因") XCTAssertEqual(fixture.model.presentation.phase, .blocked) XCTAssertTrue(fixture.model.presentation.isActionEnabled) XCTAssertEqual(fixture.model.telemetry, previousTelemetry) @@ -295,7 +300,8 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase { await newRequest.value service.resolve(1, with: .success(try DroneDockShootingTaskTestData.response(changes: ["ui": ["title": "后台迟到状态"]]))) await oldRequest.value - XCTAssertEqual(fixture.model.statusTitle, "前台最新状态") + XCTAssertEqual(fixture.model.statusTitle, "状态待确认") + XCTAssertEqual(fixture.model.response?.ui?.title, "前台最新状态") XCTAssertEqual(service.requests, [501, 501, 501]) } @@ -407,7 +413,8 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase { await second.value service.resolve(0, with: .success(try DroneDockShootingTaskTestData.response(changes: ["ui": ["title": "过期状态"]]))) await first.value - XCTAssertEqual(fixture.model.statusTitle, "最新状态") + XCTAssertEqual(fixture.model.statusTitle, "状态待确认") + XCTAssertEqual(fixture.model.response?.ui?.title, "最新状态") XCTAssertEqual(service.requests, [501, 501]) } diff --git a/suixinkanTests/DroneDockSilentRefreshTests.swift b/suixinkanTests/DroneDockSilentRefreshTests.swift index 113677f..b7eef21 100644 --- a/suixinkanTests/DroneDockSilentRefreshTests.swift +++ b/suixinkanTests/DroneDockSilentRefreshTests.swift @@ -102,7 +102,7 @@ private final class SilentRefreshService: DroneDockShootingServing, DroneDockSta """.utf8)) } - func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse { + func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse { XCTFail("本测试不提交安全指令") throw CancellationError() } @@ -111,6 +111,10 @@ private final class SilentRefreshService: DroneDockShootingServing, DroneDockSta static func snapshot(shooting: Bool) throws -> DroneDockShootingResponse { try DroneDockShootingTaskTestData.response(changes: [ + "execution_batch": 100, "state_version": shooting ? 2 : 1, + "flight_control": DroneDockShootingTaskTestData.flightControl( + resumePhase: shooting ? "shooting" : "arrived_pending_start", + pauseReason: shooting ? nil : "arrival_wait"), "order_flight_task": ["id": 501, "order_number": "TEST-TASK-PAGE-001", "scenic_id": 128, "status": 20], "task": ["id": 501, "status": 20], "current_plane": ["id": 58], "execute_gate": ["can_execute": !shooting, "primary_action": shooting ? "shooting" : "start_shoot"], diff --git a/suixinkanTests/DroneDockStartShootViewModelTests.swift b/suixinkanTests/DroneDockStartShootViewModelTests.swift index 0f44161..690cc4b 100644 --- a/suixinkanTests/DroneDockStartShootViewModelTests.swift +++ b/suixinkanTests/DroneDockStartShootViewModelTests.swift @@ -28,6 +28,9 @@ final class DroneDockStartShootViewModelTests: XCTestCase { ["ui": ["phase": "shooting"]], ["ui": ["phase": "unknown"]], ["ui": NSNull()], + ["flight_control": NSNull()], + ["flight_control": DroneDockShootingTaskTestData.flightControl(state: "unknown", droneInDock: nil, isAirborne: nil)], + ["flight_control": DroneDockShootingTaskTestData.flightControl(batch: 999)], ["task": ["id": 501, "status": 20, "wayline_status": 91]] ] for change in changes { @@ -319,6 +322,8 @@ private final class StartTaskWriteService: DroneDockStartShooting { private enum StartTaskData { static func ready(changes: [String: Any] = [:]) throws -> DroneDockShootingResponse { try DroneDockShootingTaskTestData.response(changes: [ + "execution_batch": 100, "state_version": 1, "snapshot_kind": "full", + "flight_control": DroneDockShootingTaskTestData.flightControl(resumePhase: "arrived_pending_start", pauseReason: "arrival_wait"), "order_flight_task": ["id": 501, "order_number": "TEST-TASK-PAGE-001", "scenic_id": 128, "status": 20], "task": ["id": 501, "status": 20], "execute_gate": ["can_execute": true, "primary_action": "start_shoot", "primary_action_label": "开始拍摄"], @@ -327,7 +332,7 @@ private enum StartTaskData { } static func shooting() throws -> DroneDockShootingResponse { - try ready(changes: ["ui": ["phase": "shooting", "title": "模拟无人机正在拍摄中", "message": "本地模拟,未下发设备指令"], + try ready(changes: ["state_version": 2, "flight_control": DroneDockShootingTaskTestData.flightControl(), "ui": ["phase": "shooting", "title": "模拟无人机正在拍摄中", "message": "本地模拟,未下发设备指令"], "execute_gate": ["can_execute": false, "primary_action": "shooting"]]) } diff --git a/suixinkanTests/DroneDockStatusContractTests.swift b/suixinkanTests/DroneDockStatusContractTests.swift index a4fd219..fe49789 100644 --- a/suixinkanTests/DroneDockStatusContractTests.swift +++ b/suixinkanTests/DroneDockStatusContractTests.swift @@ -179,6 +179,13 @@ final class DroneDockStatusContractTests: XCTestCase { private func payload(phase: String?, status: Int, wayline: Int, plane: [String: Any] = ["id": 58, "work_status": 1, "online_status": 1]) -> [String: Any] { var value = DroneDockShootingTaskTestData.payload() + value["execution_batch"] = 100 + value["state_version"] = 1 + value["flight_control"] = DroneDockShootingTaskTestData.flightControl( + state: status == 40 ? "returned" : "executing", canPause: status == 20, + canReturn: status == 20, droneInDock: status == 40 ? "inside" : "outside", + isAirborne: status != 40, pauseReason: phase == "arrived_pending_start" ? "arrival_wait" : nil) + value["restart_gate"] = ["can_restart": phase == "failed_restartable"] value["task"] = ["id": 501, "status": status, "wayline_status": wayline] value["order_flight_task"] = ["id": 501, "status": status, "result_message": "本地模拟:素材处理失败"] value["current_plane"] = plane @@ -217,7 +224,7 @@ private final class StatusContractActions: DroneDockStartShooting, DroneDockComm } /// 任何意外的安全指令调用都会留下计数,便于检查门禁。 - func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse { + func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse { commandCount += 1 throw APIError.networkFailed("本地模拟,无真实设备") } diff --git a/suixinkanTests/DroneDockTaskControlStateViewTests.swift b/suixinkanTests/DroneDockTaskControlStateViewTests.swift new file mode 100644 index 0000000..8e64955 --- /dev/null +++ b/suixinkanTests/DroneDockTaskControlStateViewTests.swift @@ -0,0 +1,695 @@ +import UIKit +import XCTest +@testable import suixinkan + +/// 使用内存快照核验暂停、返航和回巢面板,以及中央继续任务的实际指令连接。 +@MainActor +final class DroneDockTaskControlStateViewTests: XCTestCase { + private weak var previousKeyWindow: UIWindow? + + /// 诊断记录实际带秒数的按钮标题,计时更新不会改变其他操作门禁或加载状态。 + func testDiagnosticFieldsReflectCountdownButtonTitleAndKeepControlState() throws { + let view = DroneDockTaskStatusView(frame: CGRect(x: 0, y: 0, width: 375, height: 180)) + view.apply(DroneDockTaskPresentation(phase: .paused, title: "无人机已暂停", message: "当前悬停待命。", + deviceStatus: "", action: .resume, actionTitle: "继续任务", isActionEnabled: true), isPrimaryActionLoading: true) + view.layoutIfNeeded() + XCTAssertEqual(view.diagnosticFields["title"] as? String, "无人机已暂停") + XCTAssertEqual(view.diagnosticFields["action_title"] as? String, "继续任务") + XCTAssertEqual(view.diagnosticFields["action_loading"] as? Bool, true) + XCTAssertEqual(view.diagnosticFields["action_enabled"] as? Bool, false) + + view.apply(DroneDockTaskPresentation(phase: .ready, title: "无人机已到达", message: "确认后开拍", + deviceStatus: "", action: .start, actionTitle: "开始拍摄", isActionEnabled: true, countdownSeconds: 30)) + view.layoutIfNeeded() + var thirty = view.diagnosticFields + XCTAssertEqual(thirty["action_title"] as? String, "开始拍摄(30s)") + XCTAssertEqual(thirty["countdown"] as? String, "running") + XCTAssertFalse(views(in: view).contains { $0.accessibilityIdentifier == "drone.task.remote.countdown" }) + view.updateCountdown(seconds: 29) + var twentyNine = view.diagnosticFields + XCTAssertEqual(twentyNine["action_title"] as? String, "开始拍摄(29s)") + XCTAssertEqual(twentyNine["countdown"] as? String, "running") + thirty.removeValue(forKey: "action_title") + twentyNine.removeValue(forKey: "action_title") + XCTAssertEqual(try JSONSerialization.data(withJSONObject: thirty, options: [.sortedKeys]), + try JSONSerialization.data(withJSONObject: twentyNine, options: [.sortedKeys])) + view.updateCountdown(seconds: 0) + XCTAssertEqual(view.diagnosticFields["action_title"] as? String, "开始拍摄(0s)") + XCTAssertEqual(view.diagnosticFields["countdown"] as? String, "zero") + XCTAssertEqual(view.diagnosticFields["action_enabled"] as? Bool, true) + view.updateCountdown(seconds: nil) + XCTAssertEqual(view.diagnosticFields["action_title"] as? String, "开始拍摄") + XCTAssertEqual(view.diagnosticFields["countdown"] as? String, "hidden") + XCTAssertEqual(view.diagnosticFields["action_enabled"] as? Bool, true) + + let button = DroneShootingTaskSafetyButton(symbol: "pause.circle", color: .orange, filled: true) + button.apply(title: "紧急暂停", subtitle: "悬停待命", enabled: true, isLoading: true) + XCTAssertEqual(button.diagnosticFields["title"] as? String, "紧急暂停") + XCTAssertEqual(button.diagnosticFields["subtitle"] as? String, "悬停待命") + XCTAssertEqual(button.diagnosticFields["loading"] as? Bool, true) + XCTAssertEqual(button.diagnosticFields["enabled"] as? Bool, false) + } + + /// 相同快照重新读取不重复输出 UI 展示;导航来源与真实按钮状态可在统一会话中关联。 + func testTaskPageDiagnosticsShareSessionAndDeduplicateUnchangedRender() async throws { + let logs = ControlStateDiagnosticLog() + let diagnostics = DroneDockTaskDiagnostics(sessionID: "ui-diagnostic-test", sink: { logs.append($0) }) + let service = try ControlStateViewService(state: "paused") + let controller = try makeController(service: service, diagnostics: diagnostics) + controller.recordNavigationEntry(source: "preparation", fields: ["preparation_session_id": "preparation-test"]) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.presentation.phase == .paused } + let pausedRenders = logs.events.filter { ($0["central"] as? [String: Any])?["phase"] as? String == "paused" } + let render = try XCTUnwrap(pausedRenders.last) + XCTAssertEqual(render["session_id"] as? String, "ui-diagnostic-test") + XCTAssertEqual(render["entry_source"] as? String, "preparation") + let safety = try XCTUnwrap(render["safety"] as? [String: Any]) + XCTAssertEqual((safety["pause"] as? [String: Any])?["enabled"] as? Bool, false) + XCTAssertEqual((safety["return_home"] as? [String: Any])?["enabled"] as? Bool, true) + let before = pausedRenders.count + try tapNavigationRefresh(controller) + try await settle(window) { !controller.viewModel.isLoading } + XCTAssertEqual(logs.events.filter { ($0["central"] as? [String: Any])?["phase"] as? String == "paused" }.count, before) + XCTAssertTrue(logs.events.contains { $0["event"] as? String == "navigation.task_entry" + && $0["preparation_session_id"] as? String == "preparation-test" }) + XCTAssertTrue(service.commands.isEmpty) + } + + /// 控制状态保持固定面板和整行按钮,禁用状态不会调用操作,紧凑布局也保留点击尺寸。 + func testControlPanelsUseLocalCopyAndStableActionArea() throws { + let states: [(DroneDockTaskDisplayPhase, String, String, DroneDockTaskDisplayAction, String, Bool)] = [ + (.paused, "无人机已暂停", "当前悬停待命。\n确认安全后,可继续任务或立即返航。", .resume, "继续任务", true), + (.returning, "无人机正在返航", "本次拍摄已中断。\n请留意实时画面与无人机状态。", .none, "拍摄已中断", false), + (.returned, "本次拍摄已中断", "无人机已返回机巢,可在满足条件后重新召唤。", .retry, "重新召唤无人机", true) + ] + for size in [CGSize(width: 320, height: 100), CGSize(width: 375, height: 160), CGSize(width: 414, height: 240)] { + let view = DroneDockTaskStatusView(frame: CGRect(origin: .zero, size: size)) + var calls = 0 + view.onPrimaryAction = { calls += 1 } + for (phase, title, message, action, buttonTitle, enabled) in states { + view.apply(DroneDockTaskPresentation(phase: phase, title: title, message: message, + deviceStatus: "后端设备摘要不应显示", action: action, actionTitle: buttonTitle, isActionEnabled: enabled)) + view.layoutIfNeeded() + let titleLabel = try XCTUnwrap(find(in: view, id: "drone.task.remote.statusTitle") as? UILabel) + let messageLabel = try XCTUnwrap(views(in: view).first { + $0.accessibilityIdentifier == "drone.task.remote.statusMessage" + } as? UILabel) + let button = try XCTUnwrap(find(in: view, id: action == .refresh ? "drone.task.remote.refresh" : "drone.task.remote.primary") as? UIButton) + XCTAssertEqual(titleLabel.text, title) + XCTAssertEqual(messageLabel.text, message) + XCTAssertEqual(messageLabel.isHidden, size.height < 120) + XCTAssertEqual(button.configuration?.title, buttonTitle) + XCTAssertEqual(button.isEnabled, enabled) + XCTAssertGreaterThanOrEqual(button.bounds.height, 44) + XCTAssertEqual(button.bounds.width, size.width - 36, accuracy: 0.5) + XCTAssertTrue(view.bounds.insetBy(dx: -0.5, dy: -0.5).contains(button.convert(button.bounds, to: view))) + XCTAssertFalse(visibleTexts(in: view).contains("后端设备摘要不应显示")) + XCTAssertEqual(views(in: view).filter { $0.accessibilityIdentifier == "drone.task.remote.statusTitle" }.count, 1) + let previous = calls + button.sendActions(for: .touchUpInside) + XCTAssertEqual(calls, previous + (enabled ? 1 : 0)) + } + } + } + + /// 真正渲染到 UILabel 的颜色在加载和紧凑布局切换后仍为白色,不可用时才使用灰色。 + func testResumeButtonRenderedForegroundSurvivesLoadingAndLayoutChanges() async throws { + let host = UIViewController() + let panel = DroneDockTaskControlStateView(frame: CGRect(x: 0, y: 100, width: 375, height: 160)) + host.view.addSubview(panel) + panel.setIdentifiersActive(true) + var calls = 0 + panel.onPrimaryAction = { calls += 1 } + let window = makeWindow(root: host) + defer { close(window) } + + for (enabled, loading) in [(true, false), (false, true), (false, false), (true, false)] { + panel.apply(DroneDockTaskPresentation(phase: .paused, title: "无人机已暂停", message: "当前悬停待命。", + deviceStatus: "", action: .resume, actionTitle: "继续任务", isActionEnabled: enabled), + isPrimaryActionLoading: loading) + for height: CGFloat in [160, 240, 160] { + panel.frame.size.height = height + panel.setNeedsLayout() + try await settle(window) { panel.bounds.height == height } + let primary = try XCTUnwrap(find(in: panel, id: "drone.task.remote.primary") as? UIButton) + try assertRenderedForeground(primary, expected: enabled || loading ? .white : UIColor(hex: 0x929BAE)) + assertColor(try XCTUnwrap(primary.configuration?.background.backgroundColor), + equals: enabled || loading ? DroneDockStyle.primary : UIColor(hex: 0xEDF0F5)) + XCTAssertEqual(primary.titleLabel?.text, "继续任务") + XCTAssertEqual(primary.isEnabled, enabled && !loading) + XCTAssertGreaterThanOrEqual(primary.bounds.height, 44) + let before = calls + primary.sendActions(for: .touchUpInside) + XCTAssertEqual(calls, before + (enabled && !loading ? 1 : 0)) + } + if loading { capture(window, name: "继续任务加载-白字蓝底(隔离模拟)") } + } + } + + /// 暂停时中央继续任务只发送一次 recovery,底部暂停禁用;新的执行快照恢复拍摄中。 + func testPausedPrimaryResumesSameTaskAndKeepsSafetyButtonsFixed() async throws { + let service = try ControlStateViewService(state: "paused") + let controller = try makeController(service: service) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.presentation.phase == .paused } + let pause = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton) + let returnButton = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton) + let primary = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary") as? UIButton) + XCTAssertEqual(pause.accessibilityLabel, "已暂停") + XCTAssertEqual(pause.accessibilityValue, "悬停待命") + XCTAssertFalse(pause.isEnabled) + XCTAssertEqual(returnButton.accessibilityLabel, "立即返航") + XCTAssertTrue(returnButton.isEnabled) + XCTAssertEqual(primary.configuration?.title, "继续任务") + XCTAssertTrue(primary.isEnabled) + capture(window, name: "暂停-继续任务(隔离模拟)") + primary.sendActions(for: .touchUpInside) + primary.sendActions(for: .touchUpInside) + try await settle(window) { service.commands.count == 1 && controller.viewModel.presentation.phase == .shooting } + XCTAssertEqual(service.commands.map(\.taskID), [501]) + XCTAssertEqual(service.commands.map(\.command), [.resume]) + XCTAssertEqual(pause.accessibilityLabel, "紧急暂停") + XCTAssertTrue(pause.isEnabled) + XCTAssertEqual(returnButton.accessibilityLabel, "立即返航") + XCTAssertFalse(visibleTexts(in: controller.view).contains("接口错误按钮名称")) + } + + /// 手动返航不显示拍摄成功,确认回巢后恢复中央重召唤入口并禁用两项安全操作。 + func testManualReturnUpdatesToReturnedAndReopensResummon() async throws { + let service = try ControlStateViewService(state: "returning") + let controller = try makeController(service: service) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.presentation.phase == .returning } + let returnButton = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton) + var primary = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary") as? UIButton) + XCTAssertEqual(returnButton.accessibilityLabel, "返航中") + XCTAssertEqual(returnButton.accessibilityValue, "返回机巢") + XCTAssertFalse(returnButton.isEnabled) + XCTAssertEqual(primary.configuration?.title, "拍摄已中断") + XCTAssertFalse(primary.isEnabled) + XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机正在返航")) + XCTAssertFalse(controller.viewModel.shouldPresentRecordingCompletion) + capture(window, name: "手动返航中(隔离模拟)") + service.response = try ControlStateViewService.snapshot(state: "returned", version: 2) + try tapNavigationRefresh(controller) + try await settle(window) { controller.viewModel.presentation.phase == .returned } + primary = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary") as? UIButton) + XCTAssertEqual(primary.configuration?.title, "重新召唤无人机") + XCTAssertTrue(primary.isEnabled) + XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机已返回机巢,可在满足条件后重新召唤。")) + XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机已返回机巢")) + XCTAssertFalse(visibleTexts(in: controller.view).contains("拍摄已完成")) + XCTAssertFalse(controller.viewModel.shouldPresentRecordingCompletion) + XCTAssertEqual(returnButton.accessibilityLabel, "已返航") + XCTAssertEqual(returnButton.accessibilityValue, "已返回机巢") + XCTAssertFalse(returnButton.isEnabled) + XCTAssertFalse(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton).isEnabled) + XCTAssertTrue(service.commands.isEmpty) + capture(window, name: "已返回机巢-可重召唤(隔离模拟)") + } + + /// 暂停受理后只转动暂停按钮,中央保留拍摄状态、返航可点,直到匹配的设备确认。 + func testAcceptedPauseKeepsBusinessPanelAndReturnEnabledUntilConfirmed() async throws { + let service = try ControlStateViewService(state: "executing") + service.confirmsCommand = false + let controller = try makeController(service: service) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.presentation.phase == .shooting } + let pause = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton) + let returnButton = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton) + pause.sendActions(for: .touchUpInside) + pause.sendActions(for: .touchUpInside) + XCTAssertTrue(returnButton.isEnabled) + try await settle(window) { service.commands.count == 1 && !controller.viewModel.isSendingCommand } + XCTAssertEqual(controller.viewModel.presentation.phase, .shooting) + XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机正在拍摄中")) + XCTAssertFalse(visibleTexts(in: controller.view).contains("指令已受理")) + XCTAssertEqual(pause.accessibilityLabel, "紧急暂停") + XCTAssertEqual(pause.accessibilityValue, "处理中,悬停待命") + XCTAssertFalse(pause.isEnabled) + let spinner = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause.loading") as? UIActivityIndicatorView) + XCTAssertTrue(spinner.isAnimating) + XCTAssertTrue(returnButton.isEnabled) + XCTAssertEqual(returnButton.accessibilityValue, "中断任务") + XCTAssertEqual(service.commands.map(\.command), [.pause]) + service.response = try ControlStateViewService.snapshot(state: "paused", version: 2, + pendingCommand: service.progress(for: 0, status: "succeeded")) + try tapNavigationRefresh(controller) + try await settle(window) { controller.viewModel.presentation.phase == .paused && !controller.viewModel.isCommandLoading(.pause) } + XCTAssertFalse(spinner.isAnimating) + XCTAssertEqual(pause.accessibilityLabel, "已暂停") + XCTAssertEqual(pause.accessibilityValue, "悬停待命") + XCTAssertTrue(returnButton.isEnabled) + } + + /// 设备确认后立即结束按钮动画,即使紧随其后的 shooting 回查仍挂起;旧权限仍不得重复暂停。 + func testConfirmedCommandStopsSpinnerWhileFollowupReadIsPending() async throws { + let service = try ControlStateViewService(state: "executing") + service.holdsReadsAfterCommand = true + let controller = try makeController(service: service) + let window = makeWindow(root: controller) + defer { service.finishReads(); close(window) } + try await settle(window) { controller.viewModel.canSendCommand(.pause) } + let pause = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton) + let returnButton = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton) + pause.sendActions(for: .touchUpInside) + try await settle(window) { service.heldReadCount == 1 && !controller.viewModel.isSendingCommand } + XCTAssertEqual(controller.viewModel.commandResponse?.deviceConfirmed, true) + XCTAssertFalse(controller.viewModel.isCommandLoading(.pause)) + let spinner = try XCTUnwrap(views(in: controller.view).first { + $0.accessibilityIdentifier == "drone.task.remote.pause.loading" + } as? UIActivityIndicatorView) + XCTAssertFalse(spinner.isAnimating) + XCTAssertTrue(spinner.isHidden) + XCTAssertFalse(pause.isEnabled, "设备确认并不允许利用旧权限重复提交") + XCTAssertTrue(returnButton.isEnabled) + XCTAssertEqual(controller.viewModel.presentation.phase, .shooting) + pause.sendActions(for: .touchUpInside) + XCTAssertEqual(service.commands.map(\.command), [.pause]) + service.finishReads() + try await settle(window) { controller.viewModel.presentation.phase == .paused } + XCTAssertFalse(spinner.isAnimating) + } + + /// 继续任务的受理不覆盖暂停面板,仅中央按钮加载;返航入口仍能打开确认提示。 + func testPendingResumeLoadsOnlyPrimaryAndKeepsReturnAvailable() async throws { + let service = try ControlStateViewService(state: "paused") + service.confirmsCommand = false + let controller = try makeController(service: service) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.presentation.phase == .paused } + let primary = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary") as? UIButton) + let returnButton = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton) + primary.sendActions(for: .touchUpInside) + primary.sendActions(for: .touchUpInside) + XCTAssertFalse(primary.isEnabled) + XCTAssertTrue(returnButton.isEnabled) + try await settle(window) { service.commands.count == 1 && !controller.viewModel.isSendingCommand } + XCTAssertEqual(controller.viewModel.presentation.phase, .paused) + XCTAssertEqual(primary.configuration?.title, "继续任务") + XCTAssertTrue(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary.loading") as? UIActivityIndicatorView).isAnimating) + XCTAssertTrue(returnButton.isEnabled) + XCTAssertEqual(service.commands.map(\.command), [.resume]) + service.response = try ControlStateViewService.snapshot(state: "paused", version: 2, + pendingCommand: service.progress(for: 0, status: "pending")) + try tapNavigationRefresh(controller) + try await settle(window) { controller.viewModel.response?.stateVersion == 2 && !controller.viewModel.isLoading } + XCTAssertEqual(controller.viewModel.presentation.phase, .paused) + XCTAssertFalse(primary.isEnabled) + XCTAssertTrue(controller.viewModel.isCommandLoading(.resume)) + try assertRenderedForeground(primary, expected: .white) + XCTAssertTrue(returnButton.isEnabled) + capture(window, name: "恢复受理待设备确认-保持暂停(隔离模拟)") + returnButton.sendActions(for: .touchUpInside) + try await settle(window) { controller.presentedViewController is UIAlertController } + XCTAssertEqual((controller.presentedViewController as? UIAlertController)?.actions.compactMap(\.title), ["取消", "模拟返航"]) + controller.dismiss(animated: false) + try await settle(window) { controller.presentedViewController == nil } + service.response = try ControlStateViewService.snapshot(state: "executing", version: 3, + pendingCommand: service.progress(for: 0, status: "succeeded")) + try tapNavigationRefresh(controller) + try await settle(window) { controller.viewModel.presentation.phase == .shooting && !controller.viewModel.isCommandLoading(.resume) } + XCTAssertFalse(visibleTexts(in: controller.view).contains("指令已受理")) + } + + /// 返航途中高度证据未知时,明确的 can_pause 仍控制暂停入口,不把 null 当作已落地。 + func testReturningWithUnknownAirborneUsesExplicitPausePermission() async throws { + let service = try ControlStateViewService(state: "returning") + service.confirmsCommand = false + service.response = try ControlStateViewService.snapshot(state: "returning", version: 1, airborne: nil) + let controller = try makeController(service: service) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.presentation.phase == .returning } + let pause = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton) + XCTAssertTrue(pause.isEnabled) + XCTAssertFalse(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton).isEnabled) + pause.sendActions(for: .touchUpInside) + try await settle(window) { service.commands.count == 1 && !controller.viewModel.isSendingCommand } + XCTAssertEqual(service.commands.map(\.command), [.pause]) + XCTAssertEqual(controller.viewModel.presentation.phase, .returning) + XCTAssertTrue(controller.viewModel.isCommandLoading(.pause)) + } + + /// 已回巢但机巢未恢复空闲时显示回巢状态并禁用重召唤,空闲快照到达后再开放。 + func testReturnedWaitsForDockIdleBeforeEnablingResummon() async throws { + let service = try ControlStateViewService(state: "returned") + service.response = try ControlStateViewService.snapshot(state: "returned", version: 1, awaitDockIdle: true) + let controller = try makeController(service: service) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.presentation.phase == .returned } + let primary = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary") as? UIButton) + XCTAssertEqual(primary.configuration?.title, "重新召唤无人机") + XCTAssertFalse(primary.isEnabled) + try assertRenderedForeground(primary, expected: UIColor(hex: 0x929BAE)) + XCTAssertFalse(controller.viewModel.shouldPresentRecordingCompletion) + XCTAssertFalse(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton).isEnabled) + service.response = try ControlStateViewService.snapshot(state: "returned", version: 2) + try tapNavigationRefresh(controller) + try await settle(window) { primary.isEnabled } + XCTAssertEqual(controller.viewModel.presentation.phase, .returned) + try assertRenderedForeground(primary, expected: .white) + XCTAssertTrue(service.commands.isEmpty) + } + + /// 后端返航尚在处理中仍允许紧急暂停,不能因为返航按钮加载把另一按钮禁用。 + func testPendingReturnAllowsPauseWithoutReplacingReturningPanel() async throws { + let service = try ControlStateViewService(state: "returning") + service.confirmsCommand = false + service.response = try ControlStateViewService.snapshot(state: "returning", version: 1, pendingCommand: [ + "command_id": "remote-return", "client_request_id": "remote-request", "command": "return_home", "status": "pending"]) + let controller = try makeController(service: service) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.presentation.phase == .returning } + let pause = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton) + let returnButton = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton) + XCTAssertTrue(pause.isEnabled) + XCTAssertFalse(returnButton.isEnabled) + XCTAssertTrue(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return.loading") as? UIActivityIndicatorView).isAnimating) + pause.sendActions(for: .touchUpInside) + try await settle(window) { service.commands.count == 1 && !controller.viewModel.isSendingCommand } + XCTAssertEqual(service.commands.map(\.command), [.pause]) + XCTAssertEqual(controller.viewModel.presentation.phase, .returning) + XCTAssertTrue(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause.loading") as? UIActivityIndicatorView).isAnimating) + XCTAssertFalse(visibleTexts(in: controller.view).contains("指令已受理")) + } + + /// 指令失败或被替代都结束对应按钮的加载,业务面板保留设备已确认的拍摄阶段。 + func testTerminalCommandProgressStopsLoadingWithoutReplacingBusinessPanel() async throws { + for status in ["failed", "superseded"] { + let service = try ControlStateViewService(state: "executing") + service.confirmsCommand = false + let controller = try makeController(service: service) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.canSendCommand(.pause) } + let pause = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause") as? UIButton) + pause.sendActions(for: .touchUpInside) + try await settle(window) { service.commands.count == 1 && !controller.viewModel.isSendingCommand } + let spinner = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.pause.loading") as? UIActivityIndicatorView) + XCTAssertTrue(spinner.isAnimating) + service.response = try ControlStateViewService.snapshot(state: "executing", version: 2, + pendingCommand: service.progress(for: 0, status: status)) + try tapNavigationRefresh(controller) + try await settle(window) { !controller.viewModel.isCommandLoading(.pause) } + XCTAssertFalse(spinner.isAnimating) + XCTAssertTrue(pause.isEnabled) + XCTAssertEqual(controller.viewModel.presentation.phase, .shooting) + XCTAssertTrue(try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton).isEnabled) + } + } + + /// 起飞准备即使在巢也展示前往点位,到点自动悬停展示待开拍而非手动暂停。 + func testStartingAndArrivalWaitUseTheirBusinessPanels() async throws { + for (state, arrivalWait, expected) in [("starting", false, DroneDockTaskDisplayPhase.navigating), + ("executing", true, .ready)] { + let service = try ControlStateViewService(state: state) + service.response = try ControlStateViewService.snapshot(state: state, version: 1, arrivalWait: arrivalWait) + let controller = try makeController(service: service) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.presentation.phase == expected } + XCTAssertFalse(visibleTexts(in: controller.view).contains("无人机已暂停")) + XCTAssertFalse(visibleTexts(in: controller.view).contains("无人机已返回机巢")) + } + } + + /// 中央正常拍完的业务状态不覆盖物理返航、回巢或未知状态,安全控制文案保持设备含义。 + func testCompletedRecordingSafetyButtonsFollowPhysicalFlightState() async throws { + let cases = [("returning", "返航中", "返回机巢"), + ("returned", "已返航", "已返回机巢"), + ("unknown", "立即返航", "暂不可用")] + for (state, title, subtitle) in cases { + let service = try ControlStateViewService(state: state) + service.response = try ControlStateViewService.snapshot(state: state, version: 1, normalCompletion: true) + let controller = try makeController(service: service) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.presentation.phase == .postShootUploading } + let button = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.return") as? UIButton) + XCTAssertEqual(button.accessibilityLabel, title) + XCTAssertEqual(button.accessibilityValue, subtitle) + XCTAssertFalse(button.isEnabled) + XCTAssertTrue(visibleTexts(in: controller.view).contains("拍摄已完成")) + button.sendActions(for: .touchUpInside) + XCTAssertTrue(service.commands.isEmpty) + } + } + + /// 中断返航途中仍可读取图传;首次进入已回巢快照时不请求图传,也不显示拍摄成功。 + func testReturnedSnapshotDoesNotStartLiveWhileReturningStillLoads() async throws { + for state in ["returning", "returned"] { + let service = try ControlStateViewService(state: state) + let liveService = ControlStateLiveService() + let controller = try makeController(service: service, liveService: liveService) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { + controller.viewModel.response != nil && !controller.viewModel.isLoading + && (state == "returned" || liveService.requests == [501]) + } + XCTAssertEqual(liveService.requests, state == "returned" ? [] : [501]) + XCTAssertEqual(controller.viewModel.shouldStopLiveReception, state == "returned") + XCTAssertFalse(controller.viewModel.shouldPresentRecordingCompletion) + XCTAssertFalse(visibleTexts(in: controller.view).contains("拍摄已完成")) + if state == "returned" { + XCTAssertNil(controller.liveViewModel.response) + XCTAssertNil(controller.liveViewModel.playbackSessionID) + XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机已返回机巢")) + XCTAssertTrue(visibleTexts(in: controller.view).contains("拍摄封面 · 实时图传已结束")) + } + } + } + + private func makeController(service: ControlStateViewService, + liveService: (any DroneDockLiveServing)? = nil, + diagnostics: DroneDockTaskDiagnostics = DroneDockTaskDiagnostics()) throws -> DroneDockShootingTaskViewController { + let context = DroneDockShootingTaskTestData.context() + let model = DroneDockShootingTaskViewModel(context: context, taskID: 501, + order: try DroneDockShootingTaskTestData.order(), service: service, + commandService: service, resummonService: service, diagnostics: diagnostics, currentContext: { context }) + let live = DroneDockLiveViewModel(context: context, taskID: 501, service: liveService, currentContext: { context }) + return DroneDockShootingTaskViewController(viewModel: model, liveViewModel: live, + simulationRecordsProvider: { "纯内存替身,未联网" }, + shootingPollDelay: { _ in try await Task.sleep(for: .seconds(60)) }) + } + + private func makeWindow(root: UIViewController) -> UIWindow { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first + previousKeyWindow = scene?.windows.first { $0.isKeyWindow } + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + window.frame = scene?.coordinateSpace.bounds ?? UIScreen.main.bounds + window.overrideUserInterfaceStyle = .light + window.rootViewController = UINavigationController(rootViewController: root) + window.makeKeyAndVisible() + window.layoutIfNeeded() + return window + } + + private func close(_ window: UIWindow) { + window.isHidden = true + window.rootViewController = nil + previousKeyWindow?.makeKeyAndVisible() + } + + private func settle(_ window: UIWindow, until condition: () -> Bool) async throws { + for _ in 0..<160 { + window.layoutIfNeeded() + if condition() { + try await Task.sleep(for: .milliseconds(80)) + window.layoutIfNeeded() + if condition() { return } + } + try await Task.sleep(for: .milliseconds(15)) + } + XCTFail("隔离任务控制页面未达到预期状态") + throw NSError(domain: "DroneDockTaskControlStateViewTests", code: 1) + } + + private func views(in root: UIView) -> [UIView] { [root] + root.subviews.flatMap { views(in: $0) } } + private func hidden(_ view: UIView) -> Bool { view.isHidden || view.alpha < 0.01 || (view.superview.map(hidden) ?? false) } + private func find(in root: UIView, id: String) -> UIView? { + views(in: root).first { $0.accessibilityIdentifier == id && !hidden($0) } + } + private func visibleTexts(in root: UIView) -> [String] { + views(in: root).compactMap { view in + guard let label = view as? UILabel, !hidden(label), !label.bounds.isEmpty else { return nil } + return label.text + } + } + private func assertRenderedForeground(_ button: UIButton, expected: UIColor, + file: StaticString = #filePath, line: UInt = #line) throws { + button.layoutIfNeeded() + let label = try XCTUnwrap(button.titleLabel, file: file, line: line) + XCTAssertFalse(label.bounds.isEmpty, file: file, line: line) + XCTAssertFalse(try XCTUnwrap(label.text, file: file, line: line).isEmpty, file: file, line: line) + let attributedColor = label.attributedText.flatMap { text -> UIColor? in + guard text.length > 0 else { return nil } + return text.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor + } + let actual = try XCTUnwrap(attributedColor ?? label.textColor, file: file, line: line) + assertColor(actual, equals: expected, file: file, line: line) + XCTAssertNotNil(button.configuration?.image, file: file, line: line) + let transform = try XCTUnwrap(button.configuration?.imageColorTransformer, file: file, line: line) + assertColor(transform(.black), equals: expected, file: file, line: line) + } + private func assertColor(_ actual: UIColor, equals expected: UIColor, + file: StaticString = #filePath, line: UInt = #line) { + var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0 + var er: CGFloat = 0, eg: CGFloat = 0, eb: CGFloat = 0, ea: CGFloat = 0 + XCTAssertTrue(actual.getRed(&r, green: &g, blue: &b, alpha: &a), file: file, line: line) + XCTAssertTrue(expected.getRed(&er, green: &eg, blue: &eb, alpha: &ea), file: file, line: line) + for (value, target) in [(r, er), (g, eg), (b, eb), (a, ea)] { + XCTAssertEqual(value, target, accuracy: 0.005, file: file, line: line) + } + } + private func tapNavigationRefresh(_ controller: UIViewController) throws { + let item = try XCTUnwrap(controller.navigationItem.rightBarButtonItems?.first) + let action = try XCTUnwrap(item.action) + _ = UIApplication.shared.sendAction(action, to: item.target, from: item, for: nil) + } + private func capture(_ window: UIWindow, name: String) { + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) } + let attachment = XCTAttachment(image: image) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } +} + +/// 仅把页面诊断 JSON 保存在内存,线程安全且不替换全局控制台。 +private final class ControlStateDiagnosticLog: @unchecked Sendable { + private let lock = NSLock() + private var messages: [String] = [] + + /// 接收一次日志输出,不执行网络或设备操作。 + func append(_ message: String) { + lock.lock() + defer { lock.unlock() } + messages.append(message) + } + + /// 返回调用时的完整 JSON 事件快照。 + var events: [[String: Any]] { + lock.lock() + defer { lock.unlock() } + return messages.compactMap { try? JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any] } + } +} + +/// 只计数并返回内存参数;没有播放地址、RTC 引擎或网络传输能力。 +@MainActor +private final class ControlStateLiveService: DroneDockLiveServing { + private(set) var requests: [Int] = [] + + /// 仅记录同任务的模拟图传读取,不启动设备推流。 + func live(taskID: Int) async throws -> DroneDockLiveResponse { + requests.append(taskID) + return try DroneDockLiveTestData.response() + } +} + +/// 遵守 flight_control 合同的纯内存读写服务,完全不具备网络或设备能力。 +@MainActor +private final class ControlStateViewService: DroneDockShootingServing, DroneDockCommandSending, DroneDockResummonServing { + var response: DroneDockShootingResponse + var confirmsCommand = true + var holdsReadsAfterCommand = false + private(set) var heldReadCount = 0 + private var heldReads: [CheckedContinuation] = [] + private(set) var commands: [(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String)] = [] + + /// 按指定飞控状态初始化同一任务和批次的完整快照。 + init(state: String) throws { response = try Self.snapshot(state: state, version: 1) } + + /// 只读内存快照,不采集设备电量。 + func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse { + guard holdsReadsAfterCommand, !commands.isEmpty else { return response } + heldReadCount += 1 + return await withCheckedContinuation { heldReads.append($0) } + } + + /// 显式释放测试挂起的只读请求,不产生网络或设备操作。 + func finishReads() { + let pending = heldReads + heldReads.removeAll() + pending.forEach { $0.resume(returning: response) } + } + + /// 模拟同任务指令回执;可保持旧快照验证指令受理与设备状态的分离。 + func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse { + commands.append((taskID, command, clientRequestID)) + let progress = progress(for: commands.count - 1, status: confirmsCommand ? "succeeded" : "pending") + if confirmsCommand { + let state = command == .resume ? "executing" : command == .returnHome ? "returning" : "paused" + response = try Self.snapshot(state: state, version: 2, pendingCommand: progress) + } + let payload: [String: Any] = ["accepted": true, "device_confirmed": confirmsCommand, + "acceptance": confirmsCommand ? "device_confirmed" : "accepted", "order_flight_task_id": taskID, + "command_id": progress["command_id"]!, "client_request_id": clientRequestID, "pending_command": progress, + "command": command.rawValue, "execution_batch": 9001, "airport_sn": "LOCAL-CONTROL-058"] + return try JSONDecoder().decode(DroneDockCommandResponse.self, from: JSONSerialization.data(withJSONObject: payload)) + } + + /// 为已提交的指令生成同一身份的后端进度,用于模拟后续完整快照。 + func progress(for index: Int, status: String) -> [String: Any] { + let request = commands[index] + return ["command_id": "local-command-\(index)", "client_request_id": request.clientRequestID, + "command": request.command.rawValue, "status": status] + } + + /// 本组测试只检查重召唤许可,不应触发真实或模拟重召唤请求。 + func resummon(taskID: Int) async throws -> DroneDockShootResponse { + XCTFail("状态展示测试不应触发重召唤") + throw APIError.networkFailed("纯内存替身未配置重召唤") + } + + /// 用明确飞控状态、批次和回巢证据创建完整快照,接口展示文案故意与本地文案不同。 + static func snapshot(state: String, version: Int, normalCompletion: Bool = false, + pendingCommand: [String: Any]? = nil, arrivalWait: Bool = false, + airborne: Bool? = true, awaitDockIdle: Bool = false) throws -> DroneDockShootingResponse { + let interrupted = !normalCompletion && ["returning", "returned"].contains(state) + let returnReason: Any = normalCompletion ? "normal_complete" : (interrupted ? "manual" as Any : NSNull()) + let pauseReason: Any = state == "paused" ? "manual" : (arrivalWait ? "arrival_wait" as Any : NSNull()) + let phase = normalCompletion ? "post_shoot_uploading" + : state == "starting" ? "going_to_spot" + : state == "paused" ? "manual_paused" + : arrivalWait ? "arrived_pending_start" + : state == "returning" ? "returning_home" + : state == "returned" ? "failed_restartable" : "shooting" + let task: [String: Any] = ["id": 501, "status": interrupted ? 40 : 20, + "order_number": "TEST-TASK-PAGE-001", "scenic_id": 128, "plane_id": 58, + "wayline_task_id": 9001, "wayline_status": normalCompletion ? 24 : interrupted ? 91 : 20, + "result_code": interrupted ? "return_home" : "", "airport_sn": "LOCAL-CONTROL-058"] + return try DroneDockShootingTaskTestData.response(changes: [ + "order_flight_task_id": 501, "execution_batch": 9001, "state_version": version, "snapshot_kind": "full", + "order_flight_task": task, "task": task, + "current_plane": ["id": 58, "sn_number": "LOCAL-CONTROL-058", "work_status": state == "returned" && !awaitDockIdle ? 1 : 2, + "online_status": 1, "battery_percent": 90, "can_fly": state == "returned" && !awaitDockIdle], + "execute_gate": ["can_execute": arrivalWait, "primary_action": arrivalWait ? "start_shoot" : "blocked"], + "restart_gate": ["can_restart": state == "returned" && !normalCompletion && !awaitDockIdle, + "code": awaitDockIdle ? "await_dock_idle" : state == "returned" ? "ok" : "await_returned", + "primary_action": state == "returned" ? "restart_shoot" : "blocked"], + "ui": ["phase": phase, + "title": "接口错误标题", "message": "接口错误文案", "commands": [ + ["command": "flighttask_pause", "label": "接口错误按钮名称"], + ["command": "flighttask_recovery", "label": "接口错误按钮名称"], + ["command": "return_home", "label": "接口错误按钮名称"]]], + "flight_control": ["state": state, "resume_phase": interrupted || normalCompletion ? "returning" : arrivalWait ? "arrived_pending_start" : "shooting", + "return_reason": returnReason, "execution_batch": 9001, + "is_airborne": ["returned", "starting"].contains(state) ? false : airborne as Any? ?? NSNull(), "pause_reason": pauseReason, + "pending_command": pendingCommand as Any? ?? NSNull(), + "drone_in_dock": ["returned", "starting"].contains(state) ? "inside" : "outside", + "can_pause": ["executing", "returning"].contains(state), "can_resume": state == "paused", + "can_return_home": !interrupted && !normalCompletion] + ]) + } +} diff --git a/suixinkanTests/DroneDockTaskDiagnosticsTests.swift b/suixinkanTests/DroneDockTaskDiagnosticsTests.swift new file mode 100644 index 0000000..bed48b5 --- /dev/null +++ b/suixinkanTests/DroneDockTaskDiagnosticsTests.swift @@ -0,0 +1,196 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 验证任务关键日志的身份、时间、串行顺序及完整输出,不访问真实网络或控制台。 +final class DroneDockTaskDiagnosticsTests: XCTestCase { + func testMessagePreservesNativeFieldsAndProtectsCorrelationMetadata() throws { + let fields: [String: Any] = [ + "diagnostic": "forged", "event": "forged", "timestamp": "forged", "timezone": "UTC", + "elapsed_ms": -99, "sequence": 99, "session_id": "forged", "task_id": 999, + "app_version": "forged", "app_build": "forged", "configuration": "forged", + "can_pause": true, "batch": 2418, "pending": NSNull(), + "state": ["phase": "arrived_pending_start", "values": [0, 1, 2]] + ] + let text = DroneDockTaskDiagnostics.makeMessage("snapshot.applied", taskID: 8, fields: fields, + sessionID: "SESSION-1", sequence: 2, timestamp: Date(timeIntervalSince1970: 0.125), + elapsedMilliseconds: 1500, + metadata: .init(appVersion: "9.9.1", appBuild: "42", configuration: "Release")) + let value = try object(text) + XCTAssertEqual(value["diagnostic"] as? String, "drone_task") + XCTAssertEqual(value["event"] as? String, "snapshot.applied") + XCTAssertEqual(value["timestamp"] as? String, "1970-01-01T08:00:00.125+08:00") + XCTAssertEqual(value["timezone"] as? String, "Asia/Shanghai") + XCTAssertEqual(value["elapsed_ms"] as? Int, 1500) + XCTAssertEqual(value["sequence"] as? Int, 2) + XCTAssertEqual(value["session_id"] as? String, "SESSION-1") + XCTAssertEqual(value["task_id"] as? Int, 8) + XCTAssertEqual(value["app_version"] as? String, "9.9.1") + XCTAssertEqual(value["app_build"] as? String, "42") + XCTAssertEqual(value["configuration"] as? String, "Release") + XCTAssertEqual(value["can_pause"] as? Bool, true) + XCTAssertEqual(value["batch"] as? Int, 2418) + XCTAssertTrue(value["pending"] is NSNull) + let state = try XCTUnwrap(value["state"] as? [String: Any]) + XCTAssertEqual(state["phase"] as? String, "arrived_pending_start") + XCTAssertEqual(state["values"] as? [Int], [0, 1, 2]) + } + + func testMonotonicElapsedAndSequenceSurviveWallClockMovingBackwards() throws { + let clock = TaskDiagnosticClock(date: Date(timeIntervalSince1970: 100), uptime: 10) + let output = TaskDiagnosticOutput() + let diagnostics = DroneDockTaskDiagnostics(sessionID: "ONE-SESSION", + now: { clock.date }, uptime: { clock.uptime }, sink: { output.append($0) }) + clock.set(date: Date(timeIntervalSince1970: 101), uptime: 11.25) + diagnostics.record("page.visible", taskID: 8) + clock.set(date: Date(timeIntervalSince1970: 90), uptime: 12.5) + diagnostics.record("snapshot.applied", taskID: 8) + + let records = try output.messages.map(object) + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records.compactMap { $0["sequence"] as? Int }, [1, 2]) + XCTAssertEqual(records.compactMap { $0["elapsed_ms"] as? Int }, [1250, 2500]) + XCTAssertEqual(records.compactMap { $0["session_id"] as? String }, ["ONE-SESSION", "ONE-SESSION"]) + XCTAssertEqual(records[0]["timestamp"] as? String, "1970-01-01T08:01:41.000+08:00") + XCTAssertEqual(records[1]["timestamp"] as? String, "1970-01-01T08:01:30.000+08:00") + } + + func testSeparateInstancesUseSeparateSessionsAndRestartSequence() throws { + let firstOutput = TaskDiagnosticOutput() + let secondOutput = TaskDiagnosticOutput() + let first = DroneDockTaskDiagnostics(sink: { firstOutput.append($0) }) + let second = DroneDockTaskDiagnostics(sink: { secondOutput.append($0) }) + first.record("page.visible", taskID: 8) + first.record("page.hidden", taskID: 8) + second.record("page.visible", taskID: 8) + + XCTAssertNotEqual(first.sessionID, second.sessionID) + XCTAssertNotNil(UUID(uuidString: first.sessionID)) + XCTAssertNotNil(UUID(uuidString: second.sessionID)) + XCTAssertEqual(try firstOutput.messages.map(object).compactMap { $0["sequence"] as? Int }, [1, 2]) + let secondRecord = try object(XCTUnwrap(secondOutput.messages.first)) + XCTAssertEqual(secondRecord["sequence"] as? Int, 1) + XCTAssertEqual(secondRecord["session_id"] as? String, second.sessionID) + } + + func testConcurrentRecordsReachSinkInOneCompleteSequence() throws { + let output = TaskDiagnosticOutput() + let diagnostics = DroneDockTaskDiagnostics(sink: { output.append($0) }) + DispatchQueue.concurrentPerform(iterations: 60) { index in + diagnostics.record("callback.received", taskID: 8, fields: ["callback_index": index]) + } + + let records = try output.messages.map(object) + XCTAssertEqual(records.count, 60) + XCTAssertEqual(records.compactMap { $0["sequence"] as? Int }, Array(1...60)) + XCTAssertEqual(Set(records.compactMap { $0["callback_index"] as? Int }), Set(0..<60)) + XCTAssertEqual(Set(records.compactMap { $0["session_id"] as? String }), [diagnostics.sessionID]) + } + + func testDebugAndReleaseMetadataBothProduceRenderableEvents() throws { + for configuration in ["Debug", "Release"] { + let output = TaskDiagnosticOutput() + let diagnostics = DroneDockTaskDiagnostics( + metadata: .init(appVersion: "9.9.1", appBuild: "42", configuration: configuration), + sink: { output.append($0) }) + diagnostics.record("command.result", taskID: 8, fields: ["accepted": true]) + + let raw = try XCTUnwrap(output.messages.first) + let rendered = try XCTUnwrap(APIConsoleFormat.render(raw)) + let value = try object(rendered) + XCTAssertEqual(output.messages.count, 1) + XCTAssertEqual(value["configuration"] as? String, configuration) + XCTAssertEqual(value["accepted"] as? Bool, true) + XCTAssertEqual(value["event"] as? String, "command.result") + } + } + + func testCurrentMetadataReportsActualBuildConfiguration() { + let metadata = DroneDockTaskDiagnosticMetadata.current + #if DEBUG + XCTAssertEqual(metadata.configuration, "Debug") + #else + XCTAssertEqual(metadata.configuration, "Release") + #endif + XCTAssertEqual(metadata.appVersion, + Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown") + XCTAssertEqual(metadata.appBuild, + Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown") + } + + func testLongEventReachesExistingSafeWriterWithoutTruncation() throws { + let output = TaskDiagnosticOutput() + let fallback = TaskDiagnosticOutput() + let writer = APIConsoleOutputWriter(writeStandardOutput: { data in + output.append(String(decoding: data, as: UTF8.self)) + }) + let diagnostics = DroneDockTaskDiagnostics(sink: { raw in + guard let rendered = APIConsoleFormat.render(raw) else { return } + writer.write(rendered, prefersStandardOutput: true) { fallback.append($0) } + }) + let detail = String(repeating: "暂停与返航状态😀\n", count: 1500) + "END-OF-EVENT" + diagnostics.record("snapshot.rejected", taskID: 8, fields: ["detail": detail, "values": [1, 2, 3]]) + + XCTAssertEqual(output.messages.count, 1) + XCTAssertTrue(fallback.messages.isEmpty) + let text = try XCTUnwrap(output.messages.first) + XCTAssertTrue(text.hasSuffix("\n")) + let value = try object(text) + XCTAssertEqual(value["detail"] as? String, detail) + XCTAssertEqual(value["values"] as? [Int], [1, 2, 3]) + XCTAssertEqual(value["diagnostic"] as? String, "drone_task") + } + + private func object(_ text: String) throws -> [String: Any] { + try XCTUnwrap(JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any]) + } +} + +/// 线程安全的内存日志出口,用于观察并发记录的实际到达顺序。 +private final class TaskDiagnosticOutput: @unchecked Sendable { + private let lock = NSLock() + private var storage: [String] = [] + + var messages: [String] { + lock.lock() + defer { lock.unlock() } + return storage + } + + func append(_ message: String) { + lock.lock() + defer { lock.unlock() } + storage.append(message) + } +} + +/// 分离墙钟与单调时钟,模拟用户校时而不改变会话经过时长。 +private final class TaskDiagnosticClock: @unchecked Sendable { + private let lock = NSLock() + private var storedDate: Date + private var storedUptime: TimeInterval + + init(date: Date, uptime: TimeInterval) { + storedDate = date + storedUptime = uptime + } + + var date: Date { + lock.lock() + defer { lock.unlock() } + return storedDate + } + + var uptime: TimeInterval { + lock.lock() + defer { lock.unlock() } + return storedUptime + } + + func set(date: Date, uptime: TimeInterval) { + lock.lock() + defer { lock.unlock() } + storedDate = date + storedUptime = uptime + } +} diff --git a/suixinkanTests/DroneDockTaskFixedLayoutTests.swift b/suixinkanTests/DroneDockTaskFixedLayoutTests.swift index e6cdca5..18a8060 100644 --- a/suixinkanTests/DroneDockTaskFixedLayoutTests.swift +++ b/suixinkanTests/DroneDockTaskFixedLayoutTests.swift @@ -9,7 +9,7 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { private let regularSize = CGSize(width: 402, height: 220) private let phases: [DroneDockTaskDisplayPhase] = [ .loading, .navigating, .ready, .shooting, .postShootUploading, .postShootUploadFailed, .paused, .returning, - .completed, .failed, .blocked, .unknown, .readError + .returned, .completed, .failed, .blocked, .unknown, .readError ] /// 紧凑屏逐一显示全部业务阶段,控件始终留在固定中间区域内。 @@ -36,7 +36,7 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { let note = try XCTUnwrap(find(in: status, suffix: "failureNote") as? UILabel) XCTAssertFalse(isHidden(note)) XCTAssertEqual(note.text, "无人机离线,暂不可召唤") - } else if [.shooting, .postShootUploading, .completed].contains(phase) { + } else if [.shooting, .postShootUploading, .completed, .paused, .returning, .returned].contains(phase) { XCTAssertTrue(isHidden(device)) } else { XCTAssertFalse(isHidden(device)) @@ -147,16 +147,18 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { var actionCalls = 0 status.onPrimaryAction = { actionCalls += 1 } apply(presentation(.ready, countdownSeconds: 12), to: status) - let countdown = try XCTUnwrap(find(in: status, suffix: "countdown") as? UILabel) - XCTAssertFalse(isHidden(countdown)) + let start = try XCTUnwrap(find(in: status, suffix: "primary") as? UIButton) + XCTAssertEqual(start.title(for: .normal), "开始拍摄(12s)") + XCTAssertNil(find(in: status, suffix: "countdown")) apply(presentation(.shooting), to: status) let indicator = try XCTUnwrap(find(in: status, suffix: "shootingIndicator") as? UIButton) XCTAssertFalse(isHidden(indicator)) - XCTAssertTrue(isHidden(countdown)) status.updateCountdown(seconds: 5) layoutHierarchy(status) - XCTAssertTrue(isHidden(countdown)) - XCTAssertNil(countdown.text) + XCTAssertNil(find(in: status, suffix: "countdown")) + XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden") + XCTAssertEqual(status.diagnosticFields["action_title"] as? String, "拍摄中") + XCTAssertFalse(start.currentTitle?.contains("s)") == true) indicator.sendActions(for: .touchUpInside) XCTAssertEqual(actionCalls, 0) apply(presentation(.readError), to: status) @@ -184,15 +186,14 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { for longCopy in [false, true] { let status = makeStatus(size: size) apply(presentation(.ready, longCopy: longCopy, countdownSeconds: 30), to: status) - let countdown = try XCTUnwrap(find(in: status, suffix: "countdown") as? UILabel) let primary = try XCTUnwrap(find(in: status, suffix: "primary") as? UIButton) let title = try XCTUnwrap(find(in: status, suffix: "statusTitle") as? UILabel) let initialTitle = title.text - let initialButtonTitle = primary.title(for: .normal) + let initialFrame = primary.convert(primary.bounds, to: status) var actionCalls = 0 status.onPrimaryAction = { actionCalls += 1 } - XCTAssertEqual(countdown.text, "自动开拍倒计时:30 秒") - XCTAssertFalse(isHidden(countdown)) + XCTAssertNil(find(in: status, suffix: "countdown")) + try assertFullButtonTitle("开始拍摄(30s)", button: primary) XCTAssertFalse(primary.isEnabled) try assertReadableContainedContent(in: status) if !longCopy { capture(status, name: "到达倒计时30秒-\(Int(size.width))x\(Int(size.height))") } @@ -200,10 +201,10 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { for seconds in [29, 12, 1, 0, -1] { status.updateCountdown(seconds: seconds) layoutHierarchy(status) - XCTAssertEqual(countdown.text, "自动开拍倒计时:\(max(0, seconds)) 秒") - XCTAssertFalse(isHidden(countdown)) + XCTAssertNil(find(in: status, suffix: "countdown")) XCTAssertTrue(find(in: status, suffix: "primary") === primary) - XCTAssertEqual(primary.title(for: .normal), initialButtonTitle) + try assertFullButtonTitle("开始拍摄(\(max(0, seconds))s)", button: primary) + assertEqual(primary.convert(primary.bounds, to: status), initialFrame, message: "每秒文字刷新保持完整点击区域") XCTAssertEqual(title.text, initialTitle) XCTAssertFalse(primary.isEnabled, "倒数到零也不能放开开拍动作") XCTAssertEqual(actionCalls, 0, "数字更新不能触发开拍或其他主动作") @@ -213,8 +214,10 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { if !longCopy { capture(status, name: "到达倒计时0秒-仍待接口更新-\(Int(size.width))x\(Int(size.height))") } status.updateCountdown(seconds: nil) layoutHierarchy(status) - XCTAssertTrue(isHidden(countdown)) - XCTAssertNil(countdown.text) + XCTAssertNil(find(in: status, suffix: "countdown")) + try assertFullButtonTitle("开始拍摄", button: primary) + XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden") + assertEqual(primary.convert(primary.bounds, to: status), initialFrame, message: "清除计时不改变按钮布局") XCTAssertEqual(actionCalls, 0) try assertReadableContainedContent(in: status) } @@ -225,20 +228,31 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { func testCountdownOnlyAppearsForReadyAndClearsAfterPhaseChange() throws { let status = makeStatus(size: compactSize) apply(presentation(.ready, countdownSeconds: 30), to: status) - let countdown = try XCTUnwrap(find(in: status, suffix: "countdown") as? UILabel) - XCTAssertFalse(isHidden(countdown)) + XCTAssertEqual(status.diagnosticFields["action_title"] as? String, "开始拍摄(30s)") + XCTAssertNil(find(in: status, suffix: "countdown")) for phase in phases where phase != .ready { apply(presentation(phase, countdownSeconds: 30), to: status) - XCTAssertTrue(isHidden(countdown), "\(phase)") - XCTAssertNil(countdown.text) + XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden", "\(phase)") + XCTAssertFalse((status.diagnosticFields["action_title"] as? String)?.contains("s)") == true) + let actionTitle = status.diagnosticFields["action_title"] as? String status.updateCountdown(seconds: 12) layoutHierarchy(status) - XCTAssertTrue(isHidden(countdown), "迟到计时不得覆盖 \(phase)") - XCTAssertNil(countdown.text) + XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden", "迟到计时不得覆盖 \(phase)") + XCTAssertEqual(status.diagnosticFields["action_title"] as? String, actionTitle) + XCTAssertNil(find(in: status, suffix: "countdown")) } apply(presentation(.ready), to: status) - XCTAssertTrue(isHidden(countdown), "未提供倒计时时保留既有界面") - XCTAssertNil(countdown.text) + XCTAssertEqual(status.diagnosticFields["action_title"] as? String, "开始拍摄") + XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden") + XCTAssertNil(find(in: status, suffix: "countdown")) + + let refresh = DroneDockTaskPresentation(phase: .ready, title: "无人机已到达", message: "核对状态", + deviceStatus: "", action: .refresh, actionTitle: "刷新任务状态", isActionEnabled: true, countdownSeconds: 30) + apply(refresh, to: status) + status.updateCountdown(seconds: 12) + layoutHierarchy(status) + XCTAssertEqual(status.diagnosticFields["action_title"] as? String, "刷新任务状态") + XCTAssertEqual(status.diagnosticFields["countdown"] as? String, "hidden", "ready 的其他动作不能带开拍倒计时") } /// 完成态的说明与标题左对齐,素材按钮全宽;刷新或阶段变化不能绕过操作门禁。 @@ -447,8 +461,9 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { case .shooting: (title, action, actionTitle, enabled) = ("无人机正在拍摄中", .none, "拍摄中", false) case .postShootUploading: (title, action, actionTitle, enabled) = ("拍摄已完成", .materials, "查看素材", true) case .postShootUploadFailed: (title, action, actionTitle, enabled) = ("素材上传失败", .materials, "查看素材", true) - case .paused: (title, action, actionTitle, enabled) = ("拍摄已暂停", .resume, "继续拍摄", false) - case .returning: (title, action, actionTitle, enabled) = ("无人机正在返航", .refresh, "刷新任务状态", true) + case .paused: (title, action, actionTitle, enabled) = ("无人机已暂停", .resume, "继续任务", true) + case .returning: (title, action, actionTitle, enabled) = ("无人机正在返航", .none, "拍摄已中断", false) + case .returned: (title, action, actionTitle, enabled) = ("本次拍摄已中断", .retry, "重新召唤无人机", true) case .completed: (title, action, actionTitle, enabled) = ("本次拍摄已完成", .materials, "查看素材", true) case .failed: (title, action, actionTitle, enabled) = ("任务执行失败", .retry, "重新召唤无人机", false) case .blocked: (title, action, actionTitle, enabled) = ("当前无法继续拍摄", .refresh, "刷新任务状态", true) @@ -521,6 +536,17 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { file: file, line: line) } + /// 同时核对模型标题和 UILabel 的实际内容、文字宽度,避免秒数被尾部裁切。 + private func assertFullButtonTitle(_ expected: String, button: UIButton, + file: StaticString = #filePath, line: UInt = #line) throws { + XCTAssertEqual(button.title(for: .normal), expected, file: file, line: line) + let label = try XCTUnwrap(button.titleLabel, file: file, line: line) + XCTAssertEqual(label.text, expected, file: file, line: line) + let size = (expected as NSString).size(withAttributes: [.font: label.font as Any]) + XCTAssertGreaterThanOrEqual(label.bounds.width + 1, ceil(size.width), "按钮标题不能裁切秒数", file: file, line: line) + XCTAssertGreaterThanOrEqual(button.bounds.height, 44, file: file, line: line) + } + private func assertEqual(_ lhs: CGRect, _ rhs: CGRect, message: String, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(lhs.origin.x, rhs.origin.x, accuracy: 0.5, message, file: file, line: line) diff --git a/suixinkanTests/DroneDockTaskPresentationTests.swift b/suixinkanTests/DroneDockTaskPresentationTests.swift index c47fbde..bb0b2a3 100644 --- a/suixinkanTests/DroneDockTaskPresentationTests.swift +++ b/suixinkanTests/DroneDockTaskPresentationTests.swift @@ -5,11 +5,10 @@ import XCTest /// 验证任务页展示阶段和动作的保守映射;阶段夹具用于显示测试,不代表全部状态已经后端实测。 @MainActor final class DroneDockTaskPresentationTests: XCTestCase { - /// 前往阶段使用产品文案,其余标题和阶段说明保留后端内容,不编造飞行百分比。 - func testExplicitDisplayPhaseFixturesPreserveBackendText() async throws { + /// 状态标题由本地枚举定义,后端标题不覆盖产品文案;设备读数仍保留原值。 + func testExplicitDisplayPhaseFixturesUseLocalTitles() async throws { let phases: [(String, DroneDockTaskDisplayPhase)] = [ - ("going_to_spot", .navigating), ("navigating", .navigating), ("paused", .paused), - ("returning", .returning), ("blocked", .blocked) + ("going_to_spot", .navigating), ("blocked", .blocked) ] for (phase, expected) in phases { let result = try await presentation([ @@ -17,8 +16,7 @@ final class DroneDockTaskPresentationTests: XCTestCase { "current_plane": ["status_text": "服务端设备文案"] ]) XCTAssertEqual(result.phase, expected) - XCTAssertEqual(result.title, expected == .navigating ? "无人机正在赶来" : "服务端阶段标题") - XCTAssertEqual(result.message, "服务端完整阶段说明") + XCTAssertEqual(result.title, expected == .navigating ? "无人机正在赶来" : "当前任务暂不可执行") XCTAssertEqual(result.deviceStatus, "服务端设备文案") XCTAssertEqual(result.action, .refresh) XCTAssertTrue(result.isActionEnabled) @@ -40,9 +38,11 @@ final class DroneDockTaskPresentationTests: XCTestCase { XCTAssertEqual(result.deviceStatus, "拍摄中 · 电量95%") } - /// 后端明确允许开始或恢复时本轮仍禁用,因为尚未对接相应飞控接口。 - func testStartAndResumeRemainDisabledEvenWithPermission() async throws { + /// 只读模型未注入写服务,即使飞控允许也不发送;恢复按钮与开拍门禁互相独立。 + func testStartAndResumeRemainDisabledWithoutWriteServices() async throws { let ready = try await presentation([ + "execution_batch": 100, + "flight_control": DroneDockShootingTaskTestData.flightControl(pauseReason: "arrival_wait"), "ui": ["phase": "arrived_pending_start", "title": "无人机已到达"], "execute_gate": ["can_execute": true, "primary_action": "start_shoot", "primary_action_label": "开始拍摄"] ]) @@ -51,28 +51,49 @@ final class DroneDockTaskPresentationTests: XCTestCase { XCTAssertEqual(ready.actionTitle, "开始拍摄") XCTAssertFalse(ready.isActionEnabled) let paused = try await presentation([ - "ui": ["phase": "paused"], + "execution_batch": 100, + "flight_control": DroneDockShootingTaskTestData.flightControl(state: "paused", canPause: false, canResume: true, resumePhase: "shooting", pauseReason: "manual"), + "ui": ["phase": "manual_paused"], "execute_gate": ["can_execute": true, "primary_action": "flighttask_recovery", "primary_action_label": "继续执行"] ]) XCTAssertEqual(paused.phase, .paused) XCTAssertEqual(paused.action, .resume) - XCTAssertEqual(paused.actionTitle, "继续执行") + XCTAssertEqual(paused.actionTitle, "继续任务") + XCTAssertEqual(paused.title, "无人机已暂停") + XCTAssertEqual(paused.message, "当前悬停待命。\n确认安全后,可继续任务或立即返航。") XCTAssertFalse(paused.isActionEnabled) } - /// 门禁拒绝覆盖到达提示,不出现开始按钮;暂停时门禁拒绝也不出现恢复动作。 - func testDeniedGateNeverProducesStartOrResumeAction() async throws { + /// 开拍门禁独立于明确到达阶段,拒绝时保留到达并说明原因,暂停仍展示继续任务。 + func testDeniedStartGateDoesNotReplacePausedResumeAction() async throws { let denied = try await presentation([ "ui": ["phase": "arrived_pending_start", "title": "无人机已到达 是否开始拍摄?"], "execute_gate": ["can_execute": false, "message": "电量不足", "primary_action": "start_shoot"] ]) - XCTAssertEqual(denied.phase, .blocked) - XCTAssertEqual(denied.title, "暂不可开始拍摄") - XCTAssertEqual(denied.message, "电量不足") - XCTAssertEqual(denied.action, .refresh) - let paused = try await presentation(["ui": ["phase": "paused"], "execute_gate": ["can_execute": false]]) - XCTAssertEqual(paused.action, .refresh) - XCTAssertTrue(paused.isActionEnabled) + XCTAssertEqual(denied.phase, .ready) + XCTAssertEqual(denied.title, "无人机已到达") + XCTAssertTrue(denied.message.contains("电量不足")) + XCTAssertEqual(denied.action, .start) + XCTAssertFalse(denied.isActionEnabled) + let paused = try await presentation([ + "execution_batch": 100, + "flight_control": DroneDockShootingTaskTestData.flightControl(state: "paused", canPause: false, canResume: false, resumePhase: "shooting", pauseReason: "manual"), + "ui": ["phase": "manual_paused"], "execute_gate": ["can_execute": false]]) + XCTAssertEqual(paused.action, .resume) + XCTAssertEqual(paused.actionTitle, "继续任务") + XCTAssertFalse(paused.isActionEnabled) + } + + /// 缺少新版飞控证据的旧暂停/返航别名不能作为已确认设备状态。 + func testLegacyControlAliasesRemainUnknownWithoutFlightControl() async throws { + for phase in ["paused", "returning"] { + let result = try await presentation([ + "ui": ["phase": phase, "title": "旧后端控制标题"], + "execute_gate": ["can_execute": true, "primary_action": "flighttask_recovery"]]) + XCTAssertEqual(result.phase, .unknown) + XCTAssertEqual(result.title, "状态待确认") + XCTAssertEqual(result.action, .refresh) + } } /// 实测任务 6 的结构:航线 91 执行失败优先于订单任务 20 执行中,指令列表不等于可操作。 @@ -91,7 +112,7 @@ final class DroneDockTaskPresentationTests: XCTestCase { XCTAssertEqual(result.action, .retry) XCTAssertEqual(result.actionTitle, "重新召唤无人机") XCTAssertFalse(result.isActionEnabled) - XCTAssertEqual(result.actionNote, "暂不可重新召唤,请返回准备页确认设备状态") + XCTAssertEqual(result.actionNote, "等待设备确认已返回机巢后再重新召唤") } /// 开始拍摄门禁允许也不代表可重新召唤,失败标题与按钮保持产品失败态。 @@ -131,7 +152,7 @@ final class DroneDockTaskPresentationTests: XCTestCase { /// 明确离线或返航才显示对应限制,空闲与未知保持中性,不能冒称已具备重新召唤条件。 func testFailureActionNoteUsesOnlyExplicitDeviceState() async throws { - let neutral = "暂不可重新召唤,请返回准备页确认设备状态" + let neutral = "等待设备确认已返回机巢后再重新召唤" let cases: [([String: Any], String)] = [ (["online_status": 2, "work_status": 0, "work_status_label": "离线"], "无人机离线,暂不可召唤"), (["online_status": 2, "work_status_label": "返航中"], "无人机离线,暂不可召唤"), @@ -153,7 +174,7 @@ final class DroneDockTaskPresentationTests: XCTestCase { XCTAssertNil(normal.actionNote) } - /// 仅明确完成且无活动阶段冲突时开放素材入口;完成后仍返航时继续展示返航。 + /// 素材成功不被正常返航覆盖;拍摄结果和设备执行态保持独立。 func testMaterialsRequiresExplicitUnconflictedCompletion() async throws { for payload: [String: Any] in [ ["task": ["id": 501, "status": 30, "status_label": "拍摄成功"]], @@ -165,9 +186,12 @@ final class DroneDockTaskPresentationTests: XCTestCase { XCTAssertEqual(result.actionTitle, "查看素材") XCTAssertTrue(result.isActionEnabled) } - let returning = try await presentation(["task": ["status": 30], "ui": ["phase": "returning"]]) - XCTAssertEqual(returning.phase, .returning) - XCTAssertEqual(returning.action, .refresh) + let returning = try await presentation([ + "task": ["status": 30], "ui": ["phase": "completed"], "execution_batch": 100, + "flight_control": DroneDockShootingTaskTestData.flightControl(state: "returning", canPause: false, + canReturn: false, returnReason: "normal_complete")]) + XCTAssertEqual(returning.phase, .completed) + XCTAssertEqual(returning.action, .materials) } /// 未知阶段、执行中摘要及矛盾字段不转换成到达、拍摄中或完成。 @@ -178,9 +202,7 @@ final class DroneDockTaskPresentationTests: XCTestCase { ["task": ["status": 20], "order_flight_task": ["status": 30]], ["task": ["status": 20], "ui": ["phase": "completed"]], ["task": ["status": 30], "ui": ["phase": "shooting"]], - ["ui": ["phase": "arrived_pending_start"]], - ["ui": ["phase": "arrived_pending_start"], "execute_gate": ["can_execute": true, "primary_action": "blocked"]], - ["ui": ["phase": "paused"], "execute_gate": ["can_execute": true, "primary_action": "blocked"]] + ["ui": ["phase": "arrived_pending_start"], "execute_gate": ["can_execute": true, "primary_action": "blocked"]] ] for payload in payloads { let result = try await presentation(payload) @@ -191,6 +213,15 @@ final class DroneDockTaskPresentationTests: XCTestCase { } } + /// 明确到达但没有开拍门禁时保留到达展示,不借文案开放开始按钮。 + func testExplicitArrivalWithoutStartGateRemainsReadyButDisabled() async throws { + let result = try await presentation(["ui": ["phase": "arrived_pending_start"]]) + XCTAssertEqual(result.phase, .ready) + XCTAssertEqual(result.title, "无人机已到达") + XCTAssertEqual(result.action, .start) + XCTAssertFalse(result.isActionEnabled) + } + /// 明确失败或取消不受笼统阶段文案覆盖,更不能开放素材完成入口。 func testFailedAndCancelledTaskStatesOverrideOptimisticUI() async throws { let failed = try await presentation(["task": ["status": 40, "status_label": "执行失败"], "ui": ["phase": "completed"]]) diff --git a/suixinkanTests/DroneDockTaskTraceTests.swift b/suixinkanTests/DroneDockTaskTraceTests.swift new file mode 100644 index 0000000..194347a --- /dev/null +++ b/suixinkanTests/DroneDockTaskTraceTests.swift @@ -0,0 +1,358 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 关键日志与真实 ViewModel 判断一起验证;全部读取和指令由纯内存替身完成。 +@MainActor +final class DroneDockTaskTraceTests: XCTestCase { + func testStartingInsideLogsBackendEvidenceAndLocalTravelSeparately() async throws { + let fixture = try DroneTaskTraceFixture(snapshot: Self.snapshot(state: "starting", phase: "going_to_spot")) + await fixture.model.refresh() + + let event = try fixture.output.last("snapshot.applied") + let state = try dictionary(event["state"]) + let backend = try dictionary(state["backend"]) + let local = try dictionary(state["local"]) + let control = try dictionary(backend["flight_control"]) + XCTAssertEqual(event["source"] as? String, "http") + XCTAssertEqual(event["session_id"] as? String, fixture.model.diagnosticSessionID) + XCTAssertEqual(event["task_id"] as? Int, 501) + XCTAssertEqual(event["execution_batch"] as? Int, 9001) + XCTAssertEqual(control["state"] as? String, "starting") + XCTAssertEqual(control["drone_in_dock"] as? String, "inside") + XCTAssertEqual(control["is_airborne"] as? Bool, false) + XCTAssertEqual(local["phase"] as? String, "navigating") + XCTAssertEqual(local["title"] as? String, fixture.model.presentation.title) + XCTAssertEqual(local["pause_allowed"] as? Bool, false) + XCTAssertEqual(local["return_allowed"] as? Bool, true) + XCTAssertTrue(local["countdown_seconds"] is NSNull) + XCTAssertEqual(fixture.model.presentation.phase, .navigating) + XCTAssertEqual(fixture.service.requests.count, 1) + XCTAssertTrue(fixture.commands.requests.isEmpty) + } + + func testArrivalWaitLogsReadyAndStartsCountdownOnceDespiteRawDJIPause() async throws { + let clock = DroneDockCountdownTestClock() + var control = DroneDockShootingTaskTestData.flightControl(batch: 9001, + resumePhase: "arrived_pending_start", pauseReason: "arrival_wait") + control["dji_task_status"] = "paused" + let initial = try Self.snapshot(phase: "arrived_pending_start", changes: ["flight_control": control]) + let fixture = try DroneTaskTraceFixture(snapshot: initial, countdownNow: { clock.now() }) + await fixture.model.refresh() + clock.advance(by: .seconds(9)) + let updated = try Self.snapshot(version: 2, phase: "arrived_pending_start", changes: ["flight_control": control]) + XCTAssertEqual(fixture.model.applyTaskSnapshot(updated, source: .webSocket), .applied) + + let countdownEvents = try fixture.output.events("countdown.started") + XCTAssertEqual(countdownEvents.count, 1) + XCTAssertEqual(countdownEvents.first?["seconds"] as? Int, 30) + XCTAssertEqual(countdownEvents.first?["source"] as? String, "http") + let event = try fixture.output.last("snapshot.applied") + let state = try dictionary(event["state"]) + let backend = try dictionary(state["backend"]) + let loggedControl = try dictionary(backend["flight_control"]) + let local = try dictionary(state["local"]) + XCTAssertEqual(event["source"] as? String, "websocket") + XCTAssertEqual(backend["ui_phase"] as? String, "arrived_pending_start") + XCTAssertEqual(loggedControl["state"] as? String, "executing") + XCTAssertEqual(loggedControl["pause_reason"] as? String, "arrival_wait") + XCTAssertEqual(loggedControl["dji_task_status"] as? String, "paused") + XCTAssertEqual(local["phase"] as? String, "ready") + XCTAssertEqual(local["countdown_seconds"] as? Int, 21) + XCTAssertEqual(local["resume_allowed"] as? Bool, false) + XCTAssertEqual(fixture.model.presentation.phase, .ready) + XCTAssertEqual(fixture.service.requests.count, 1) + XCTAssertTrue(fixture.commands.requests.isEmpty) + } + + func testSnapshotSourcesAndRejectionReasonsPreserveAcceptedSnapshot() async throws { + let fixture = try DroneTaskTraceFixture(snapshot: Self.snapshot()) + await fixture.model.refresh() + let accepted = try Self.snapshot(version: 3) + XCTAssertEqual(fixture.model.applyTaskSnapshot(accepted, source: .webSocket), .applied) + let acceptedJSON = fixture.model.response?.dataJSON + XCTAssertEqual(fixture.model.applyTaskSnapshot(accepted, source: .http), .duplicate) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try Self.snapshot(version: 2), source: .webSocket), .outdated) + let invalid = try Self.snapshot(version: 4, changes: ["order_flight_task_id": 999]) + XCTAssertEqual(fixture.model.applyTaskSnapshot(invalid), .invalid) + + let applied = try fixture.output.events("snapshot.applied") + XCTAssertEqual(applied.compactMap { $0["source"] as? String }, ["http", "websocket"]) + let ignored = try fixture.output.events("snapshot.ignored") + XCTAssertEqual(ignored.compactMap { $0["source"] as? String }, ["http", "websocket", "unspecified"]) + XCTAssertEqual(ignored.compactMap { $0["result"] as? String }, ["duplicate", "outdated", "invalid"]) + XCTAssertEqual(ignored.compactMap { $0["reason"] as? String }, [ + "same_batch_and_version", "older_batch_or_version", "task_order_or_scenic_mismatch"]) + let rejectedIdentity = try dictionary(try XCTUnwrap(ignored.last)["incoming"]) + XCTAssertEqual(rejectedIdentity["order_flight_task_id"] as? Int, 999) + XCTAssertEqual(fixture.model.response?.dataJSON, acceptedJSON) + XCTAssertEqual(fixture.model.response?.stateVersion, 3) + XCTAssertEqual(fixture.service.requests.count, 1) + XCTAssertTrue(fixture.commands.requests.isEmpty) + } + + func testCommandEventsCorrelateOneRequestThroughReceiptAndSnapshotWithoutExtraCalls() async throws { + let fixture = try DroneTaskTraceFixture(snapshot: Self.snapshot()) + await fixture.model.refresh() + await fixture.model.sendCommand(.pause) + let request = try XCTUnwrap(fixture.commands.requests.first) + XCTAssertTrue(fixture.model.isCommandLoading(.pause)) + let progress: [String: Any] = ["command": DroneDockSafetyCommand.pause.rawValue, + "command_id": "TRACE-COMMAND-1", "client_request_id": request.clientRequestID, + "status": "succeeded", "message": ""] + let control = DroneDockShootingTaskTestData.flightControl(state: "paused", batch: 9001, + canPause: false, canResume: true, resumePhase: "shooting", pauseReason: "manual", pendingCommand: progress) + let confirmed = try Self.snapshot(version: 3, state: "paused", phase: "manual_paused", + changes: ["flight_control": control]) + XCTAssertEqual(fixture.model.applyTaskSnapshot(confirmed, source: .webSocket), .applied) + + let events = try fixture.output.all().filter { ($0["event"] as? String)?.hasPrefix("command.") == true } + XCTAssertEqual(events.compactMap { $0["event"] as? String }, [ + "command.requested", "command.queued", "command.sending", "command.receipt_received", + "command.receipt_applied", "command.progress_changed", "command.snapshot_confirmed"]) + let correlated = Array(events.dropFirst()) + XCTAssertEqual(Set(correlated.compactMap { $0["client_request_id"] as? String }), [request.clientRequestID]) + XCTAssertEqual(Set(correlated.compactMap { $0["submitted_batch"] as? Int }), [9001]) + XCTAssertEqual(Set(events.compactMap { $0["session_id"] as? String }), [fixture.model.diagnosticSessionID]) + let receipt = try fixture.output.last("command.receipt_received") + XCTAssertEqual(receipt["receipt_client_request_id"] as? String, request.clientRequestID) + XCTAssertEqual(receipt["receipt_command_id"] as? String, "TRACE-COMMAND-1") + XCTAssertEqual(receipt["accepted"] as? Bool, true) + XCTAssertEqual(receipt["device_confirmed"] as? Bool, false) + let finished = try fixture.output.last("command.snapshot_confirmed") + XCTAssertEqual(finished["command_id"] as? String, "TRACE-COMMAND-1") + XCTAssertEqual(finished["button_loading"] as? Bool, false) + XCTAssertEqual(finished["confirmed_flight_state"] as? String, "paused") + XCTAssertFalse(fixture.model.isCommandLoading(.pause)) + XCTAssertEqual(fixture.model.presentation.phase, .paused) + XCTAssertEqual(fixture.commands.requests.count, 1) + XCTAssertEqual(fixture.service.requests.count, 2, "只有首次读取与既有指令后回查,诊断不增加请求") + XCTAssertTrue(fixture.service.requests.allSatisfy { $0.taskID == 501 && !$0.liveBattery }) + } + + func testStaleMetricsAndNullFlightEvidenceStayDistinctFromRetainedDisplay() async throws { + let fixture = try DroneTaskTraceFixture(snapshot: Self.snapshot(changes: [ + "metrics": [["key": "battery", "raw": 0, "value": "0%", "source": "airport"]], + "metrics_stale": false, "metrics_updated_at": "2026-11-04 10:11:12"])) + await fixture.model.refresh() + let firstState = try dictionary(try fixture.output.last("snapshot.applied")["state"]) + let firstBackend = try dictionary(firstState["backend"]) + let firstMetric = try XCTUnwrap((firstBackend["metrics"] as? [[String: Any]])?.first) + XCTAssertEqual(firstMetric["raw"] as? Int, 0) + XCTAssertEqual(firstMetric["value"] as? String, "0%") + XCTAssertEqual(firstMetric["source"] as? String, "airport") + let control = DroneDockShootingTaskTestData.flightControl(batch: 9001, isAirborne: nil) + let stale = try Self.snapshot(version: 2, changes: ["flight_control": control, + "metrics": [["key": "battery", "raw": NSNull(), "value": NSNull(), "source": "airport"]], + "metrics_stale": true, "metrics_updated_at": NSNull()]) + XCTAssertEqual(fixture.model.applyTaskSnapshot(stale, source: .webSocket), .applied) + + let event = try fixture.output.last("snapshot.applied") + let state = try dictionary(event["state"]) + let backend = try dictionary(state["backend"]) + let local = try dictionary(state["local"]) + let loggedControl = try dictionary(backend["flight_control"]) + XCTAssertEqual(backend["metrics_count"] as? Int, 1) + let missingMetric = try XCTUnwrap((backend["metrics"] as? [[String: Any]])?.first) + XCTAssertTrue(missingMetric["raw"] is NSNull) + XCTAssertTrue(missingMetric["value"] is NSNull) + XCTAssertEqual(missingMetric["source"] as? String, "airport") + XCTAssertEqual(backend["metrics_stale"] as? Bool, true) + XCTAssertTrue(backend["metrics_updated_at"] is NSNull) + XCTAssertTrue(loggedControl["is_airborne"] is NSNull, "未知在飞证据不能补为 false") + XCTAssertEqual(local["using_retained_metrics"] as? Bool, true) + XCTAssertEqual(local["telemetry_stale"] as? Bool, true) + XCTAssertEqual(local["pause_allowed"] as? Bool, true, "遥测未知不覆盖后端明确暂停许可") + let telemetry = try dictionary(local["telemetry"]) + XCTAssertEqual(telemetry["battery"] as? String, "0%") + XCTAssertEqual(fixture.model.telemetry.batteryText, "0%") + XCTAssertEqual(fixture.model.response?.metrics.count, 1) + let raw = try dictionary(JSONSerialization.jsonObject(with: Data(stale.dataJSON.utf8))) + let rawMetric = try XCTUnwrap((raw["metrics"] as? [[String: Any]])?.first) + XCTAssertTrue(rawMetric["raw"] is NSNull) + XCTAssertTrue(rawMetric["value"] is NSNull) + XCTAssertEqual(fixture.service.requests.count, 1) + XCTAssertTrue(fixture.commands.requests.isEmpty) + } + + /// 遥测证据原样记录;三态不被补造,也不覆盖独立的后端安全许可。 + func testDroneTelemetryEvidencePreservesValuesAndExplicitUnknownAirborne() async throws { + for airborne: Bool? in [true, nil] { + let evidence: [String: Any] = [ + "drone_sn": "TEST-DRONE-058", "telemetry_source": "drone", + "elevation": airborne == true ? 30.25 as Any : NSNull(), + "horizontal_speed": airborne == true ? 0 as Any : NSNull(), + "vertical_speed": airborne == true ? -0.5 as Any : NSNull(), + "is_airborne": airborne as Any? ?? NSNull() + ] + var control = DroneDockShootingTaskTestData.flightControl(batch: 9001, isAirborne: airborne) + control["evidence"] = evidence + let snapshot = try Self.snapshot(changes: ["flight_control": control]) + let fixture = try DroneTaskTraceFixture(snapshot: snapshot) + await fixture.model.refresh() + + let raw = try dictionary(JSONSerialization.jsonObject(with: Data(snapshot.dataJSON.utf8))) + let rawControl = try dictionary(raw["flight_control"]) + let rawEvidence = try dictionary(rawControl["evidence"]) + let state = try dictionary(try fixture.output.last("snapshot.applied")["state"]) + let backend = try dictionary(state["backend"]) + let loggedControl = try dictionary(backend["flight_control"]) + let loggedEvidence = try dictionary(loggedControl["evidence"]) + XCTAssertTrue(NSDictionary(dictionary: rawEvidence).isEqual(to: evidence)) + XCTAssertTrue(NSDictionary(dictionary: loggedEvidence).isEqual(to: evidence)) + XCTAssertEqual(fixture.model.response?.flightControl?.isAirborne, airborne) + XCTAssertTrue(fixture.model.canSendCommand(.pause)) + XCTAssertTrue(fixture.model.canSendCommand(.returnHome)) + if airborne == nil { + XCTAssertTrue(rawControl["is_airborne"] is NSNull) + XCTAssertTrue(loggedControl["is_airborne"] is NSNull) + } + XCTAssertEqual(fixture.service.requests.count, 1) + XCTAssertFalse(try XCTUnwrap(fixture.service.requests.first).liveBattery) + XCTAssertTrue(fixture.commands.requests.isEmpty) + } + } + + /// 服务端补采的新版本立即更新六项读数;过期缓存保留最近值,后续有效读数恢复新鲜样式。 + func testNewMetricsVersionAdvancesDisplayAndPreservesLastValuesWhenStale() async throws { + let initialMetrics: [[String: Any]] = [ + ["key": "battery", "raw": 76, "value": "76%", "source": "drone"], + ["key": "wind_speed", "raw": 2, "value": "2m/s"] + ] + let refreshedMetrics: [[String: Any]] = [ + ["key": "battery", "raw": 75, "value": "75%", "source": "drone"], + ["key": "wind_speed", "raw": 0, "value": "0m/s"] + ] + let fixture = try DroneTaskTraceFixture(snapshot: Self.snapshot(changes: [ + "metrics": initialMetrics, "metrics_stale": false, "metrics_updated_at": "2026-11-04 15:00:00" + ])) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.telemetry.batteryText, "76%") + XCTAssertEqual(fixture.model.telemetry.windText, "2m/s") + + let refreshed = try Self.snapshot(version: 2, changes: [ + "metrics": refreshedMetrics, "metrics_stale": false, "metrics_updated_at": "2026-11-04 15:00:15" + ]) + XCTAssertEqual(fixture.model.applyTaskSnapshot(refreshed, source: .http), .applied) + XCTAssertEqual(fixture.model.telemetry.batteryText, "75%") + XCTAssertEqual(fixture.model.telemetry.windText, "0m/s") + XCTAssertEqual(fixture.model.response?.metricsUpdatedAt, "2026-11-04 15:00:15") + XCTAssertFalse(fixture.model.isTelemetryStale) + + let stale = try Self.snapshot(version: 3, changes: [ + "metrics": refreshedMetrics, "metrics_stale": true, "metrics_updated_at": "2026-11-04 15:00:15" + ]) + XCTAssertEqual(fixture.model.applyTaskSnapshot(stale, source: .http), .applied) + XCTAssertEqual(fixture.model.telemetry.batteryText, "75%") + XCTAssertEqual(fixture.model.telemetry.windText, "0m/s") + XCTAssertTrue(fixture.model.isTelemetryStale) + let staleState = try dictionary(try fixture.output.last("snapshot.applied")["state"]) + let staleBackend = try dictionary(staleState["backend"]) + let staleLocal = try dictionary(staleState["local"]) + XCTAssertEqual(staleBackend["metrics_updated_at"] as? String, "2026-11-04 15:00:15") + XCTAssertEqual(staleLocal["telemetry_stale"] as? Bool, true) + XCTAssertEqual(staleLocal["using_retained_metrics"] as? Bool, false, "完整缓存来自当前回包,不冒充 App 补值") + + let recovered = try Self.snapshot(version: 4, changes: [ + "metrics": [["key": "battery", "raw": 74, "value": "74%", "source": "drone"], + ["key": "wind_speed", "raw": 1.3, "value": "1.3m/s"]], + "metrics_stale": false, "metrics_updated_at": "2026-11-04 15:02:30" + ]) + XCTAssertEqual(fixture.model.applyTaskSnapshot(recovered, source: .http), .applied) + XCTAssertEqual(fixture.model.response?.executionBatch, 9001) + XCTAssertEqual(fixture.model.telemetry.batteryText, "74%") + XCTAssertEqual(fixture.model.telemetry.windText, "1.3m/s") + XCTAssertEqual(fixture.model.response?.metricsUpdatedAt, "2026-11-04 15:02:30") + XCTAssertFalse(fixture.model.isTelemetryStale) + XCTAssertEqual(fixture.service.requests.count, 1, "接收补采快照不新增状态请求或图传请求") + XCTAssertTrue(fixture.service.requests.allSatisfy { !$0.liveBattery }) + XCTAssertTrue(fixture.commands.requests.isEmpty) + } + + private func dictionary(_ value: Any?) throws -> [String: Any] { + try XCTUnwrap(value as? [String: Any]) + } + + /// 匿名完整快照,状态和权限来自显式合同字段,不依赖真实账号或设备。 + private static func snapshot(version: Int = 1, state: String = "executing", phase: String = "shooting", + changes: [String: Any] = [:]) throws -> DroneDockShootingResponse { + let starting = state == "starting" + let control = DroneDockShootingTaskTestData.flightControl(state: state, batch: 9001, + canPause: !starting, resumePhase: phase, droneInDock: starting ? "inside" : "outside", + isAirborne: !starting) + let payload: [String: Any] = ["order_flight_task_id": 501, "execution_batch": 9001, + "state_version": version, "snapshot_kind": "full", "task": ["id": 501, "status": 20], + "order_flight_task": ["id": 501, "status": 20], + "current_plane": ["id": 58, "sn_number": "TEST-TRACE-058", "work_status": 2], + "flight_control": control, "ui": ["phase": phase], + "execute_gate": ["can_execute": phase == "arrived_pending_start", "primary_action": "start_shoot"]] + return try DroneDockShootingTaskTestData.response(changes: payload.merging(changes) { _, new in new }) + } +} + +/// 每个用例拥有独立日志和内存服务,诊断代码无法转发网络。 +@MainActor +private struct DroneTaskTraceFixture { + let output: DroneTaskTraceOutput + let service: DroneDockShootingTaskTestService + let commands: DroneTaskTraceCommandService + let model: DroneDockShootingTaskViewModel + + init(snapshot: DroneDockShootingResponse, + countdownNow: @escaping @Sendable () -> ContinuousClock.Instant = { ContinuousClock.now }) throws { + let output = DroneTaskTraceOutput() + self.output = output + service = DroneDockShootingTaskTestService(result: .success(snapshot)) + commands = DroneTaskTraceCommandService() + let context = DroneDockShootingTaskTestData.context() + model = DroneDockShootingTaskViewModel(context: context, taskID: 501, + order: try DroneDockShootingTaskTestData.order(), service: service, commandService: commands, + countdownNow: countdownNow, diagnostics: DroneDockTaskDiagnostics(sink: { output.append($0) }), + currentContext: { context }) + } +} + +/// 受理回执显式回显客户端幂等键,随后由测试注入完整设备确认快照。 +@MainActor +private final class DroneTaskTraceCommandService: DroneDockCommandSending { + private(set) var requests: [(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String)] = [] + + func sendCommand(taskID: Int, command: DroneDockSafetyCommand, clientRequestID: String) async throws -> DroneDockCommandResponse { + requests.append((taskID, command, clientRequestID)) + let payload: [String: Any] = ["order_flight_task_id": taskID, "execution_batch": 9001, + "state_version": 2, "plane_id": 58, "airport_sn": "TEST-TRACE-058", "accepted": true, + "device_confirmed": false, "command": command.rawValue, "command_id": "TRACE-COMMAND-1", + "client_request_id": clientRequestID, + "pending_command": ["command": command.rawValue, "command_id": "TRACE-COMMAND-1", + "client_request_id": clientRequestID, "status": "pending", "message": ""]] + return try JSONDecoder().decode(DroneDockCommandResponse.self, + from: JSONSerialization.data(withJSONObject: payload)) + } +} + +/// 线程安全保存原始日志;读取时解析真实输出,任何无效 JSON 都会令测试失败。 +private final class DroneTaskTraceOutput: @unchecked Sendable { + private let lock = NSLock() + private var messages: [String] = [] + + func append(_ message: String) { + lock.lock() + defer { lock.unlock() } + messages.append(message) + } + + func all() throws -> [[String: Any]] { + lock.lock() + let snapshot = messages + lock.unlock() + return try snapshot.map { try XCTUnwrap(JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any]) } + } + + func events(_ name: String) throws -> [[String: Any]] { + try all().filter { $0["event"] as? String == name } + } + + func last(_ name: String) throws -> [String: Any] { + try XCTUnwrap(events(name).last, "未收到关键事件 \(name)") + } +}