diff --git a/AGENTS.md b/AGENTS.md index 5110753..a03dfea 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -177,3 +177,53 @@ Swift · UIKit · SnapKit(代码布局,约束写在 `setupUI()` / `setupCons - `ui.phase=post_shoot_uploading` 表示录制结束后的下载/上传/渲染(wayline 24/30/40),任务 status 仍为 20;即使 `finished_at` 有值或开拍门禁 false,也不能判为完成或阻止阶段。页面保留刷新,展示后端阶段标题/说明,不虚构百分比。 - `completed` / 一致的任务成功态才提供查看素材;失败、取消与冲突状态保留原有保护。HTTP 和 WS 共用阶段及版本校验。 - 代理仅编译、使用模拟器和隔离替身验证,不创建真实任务、不访问图传或飞控。 + +## 录制完成提示与图传结束(2026-11-03 后续用户要求) + +- 本节覆盖上文拍摄后仍在任务页展示“拍摄完毕上传中”的 UI 约定。可信 `post_shoot_uploading` 表示录制结束,页面显示“拍摄已完成”,弹窗提供“稍后再去 / 去查看”;进入当前订单素材库查看上传进度及素材,不更改后端 status=20,不宣告素材就绪或次数扣减。 +- 完成提示按任务和 execution_batch 在当前页面会话中去重;相同批次的上传、完成快照及前后台切换不重复弹出。失败、取消、身份不符及冲突快照不触发成功提示。 +- 录制结束后停止本地 RTC 接收、取消 live 补流/续期和在途请求,显示静态拍摄封面。准备页传入点位封面,缺失时显示中性封面;不使用演示照片冒充当前拍摄。旧播放器回调不能恢复实时画面,已结束任务首次读取后不再启动 live。 +- RTC 首帧等待超时只允许尝试另一路,保留已有房间等待晚到的发布/首帧;按 SDK 发布的 streamId 订阅,不假定流索引为 0。补流回包轮换 user_id 时,原房间凭证未临期则保留原身份,临期后才替换。 +- 只停止本机接收,不发送设备停流或飞控指令。Debug 的网络层、播放器和 SDK 初始化保护保持;代理仅用隔离替身、模拟器测试和无签名 Release 编译验证。 + +## 准备页电量与前往点位(2026-11-03 最新用户要求) + +- 用户要求准备页获取并展示电量。Release 的 `plane-status` 保留调用方 `live_battery=1`,覆盖旧的该接口一律强制 0 约定;Debug 真实传输仍强制 0。`shooting` 的 `live_battery=0` 和 `status` 的 `live_metrics=0` 不变。代理仍不执行真实采集,只验证隔离替身。 +- 准备页展示后端推荐设备的状态;完整文案缺少电量时补充 `battery_label` / 有效 `battery_percent`,避免重复,缺失不当作 0,不改选飞机。 +- 从确认并召唤进入任务页时,同任务、同订单、同景区的明确 `accepted=true` 且 `ui.phase=going_to_spot` 回执可用于首份快照前的“无人机正在赶来”过渡。不得将此回执当作真实起飞、到达或开放开拍的依据。 +- HTTP / WS 的 `going_to_spot` 展示“无人机正在赶来”;到达仍以 `arrived_pending_start` 和开拍门禁判断,不用固定等待时长或任务状态 20 推断。若后端过早报到达,需后端核查当前航线批次的到达首点判定。 + +## 任务页图传标识、完成态与倒计时(2026-11-03 最新用户要求) + +- 正在播放时不显示“刷新图传”,左上仅小绿点与“实时图传”;无首帧、失败或静态封面不能显示实时标识。失败/不可用时保留主动重试,本地演示仍明确标注模拟来源。 +- “拍摄已完成”状态按体验原型采用左侧浅绿圆形勾、右侧标题和说明、下方整行“查看素材”;该面板不再显示设备摘要和“详情”。返航说明必须有当前设备状态依据,后续失败快照仍优先显示失败。 +- 用户最新确认:到达后的 30 秒倒计时由 App 自行创建和维护,仅显示剩余秒数,覆盖旧的“等待后端提供截止时间字段”约定。首次接受本任务批次的可信到达快照后开始,同批次 HTTP/WS 刷新不重置;到零保留 0 秒,不自动请求状态、发送开拍或切换阶段。后端返回拍摄中时立即按接口更新 UI,即使倒计时尚未结束。 +- 本地倒计时采用单调时钟;离页/后台停止界面定时刷新,同一页面会话返回后按已过去时间继续。新执行批次重新计时,身份失效或明确清除快照时清理;不持久化或跨账号共享计时数据。 +- 用户再次明确:已到达且既有开拍门禁满足时,“开始拍摄”可手动点击,与倒计时不冲突;30 秒、倒数中及 0 秒均不因计时本身禁用。实际点击沿用防重复提交、受理/结果未知锁和后端状态确认,Debug 真实操作拦截继续保持。 + +## 无人机状态枚举职责(2026-11-03 用户补充 9.9.1 合同) + +- 设备忙闲以 `work_status` 为准:0 离线、1 空闲、2 拍摄中;`online_status=1` 表示在线,其他已提供整数表示离线,不能覆盖明确的工作态。`is_receive_order` 的 1/2 为可接单/暂停接单,不等同于当前任务操作许可。 +- 订单飞行任务 status:10 待执行、20 执行中、30 成功、40 失败、50 取消、60 待确认。航线 wayline_status 是另一组枚举:29 拍摄失败、39 上传失败、49 渲染失败、91 执行失败、90 取消;24/30/40 分别为下载/上传/渲染,不能混用数字值。 +- 拍摄页进度优先使用 `ui.phase`。`post_shoot_upload_failed` 单独展示素材处理失败及素材入口;录制已结束,停止本机图传,不弹成功提示,不因素材失败自动开放重召唤。后端明确 `failed_restartable` 的既有重召流程继续保留;工作态为 2 时显示忙碌并禁止重召。 +- 任务待确认时只读核对,不利用旧的开拍门禁或指令列表继续操作。未知枚举保持未知,不用设备在线或“拍摄中”工作态推导首点到达或自动开拍时间。 + +## 正常拍完开始返航即完成(2026-11-03 朱工最新合同) + +- 后端确认司空 `taskDetail.status=success` 后设置本批次返航标记并进入 `wayline=24`,返回 `ui.phase=post_shoot_uploading`,无需等回巢、finished_at 或素材就绪;App 立即展示“拍摄已完成”,沿用完成弹窗、静态封面及本机图传释放流程,不提前改写订单任务成功态。 +- 解析顶层与 UI 的 `shoot_complete_returning` 以及 `ui.wayline_stage=shoot_done_returning`。仅可信完成环节使用标记显示“无人机正在返航,请留意现场”;进入航线 30/40 后改为上传/渲染说明,显式 false 不沿用返航说明。完整快照按任务/批次/版本整体替换,不把旧标记留到后续状态。 +- `partially_done` 对应航线 29 和订单任务失败,手动 `result_code=return_home` 也属中断失败;失败、取消、待确认和冲突规则优先,标记不能把这些情况升级为拍摄完成。未知 UI 阶段也不只凭标记推导成功。 +- App 不直接探测司空任务、不执行后端 `markShootDoneReturning` 等内部操作;代理继续只使用隔离替身、模拟器及无签名 Release 编译验证。 + +## 工作台进入任务的返回路径(2026-11-03 用户要求) + +- “机巢工作台 → 拍摄准备 → 拍摄任务”进入任务时,以任务页替换导航栈顶的准备页;任务页返回直接回到原工作台实例。保留工作台之前已有的页面,不创建新的工作台,不通过自定义返回动作绕过导航栈。 +- 准备页成功自动进入任务和点击“查看拍摄任务”共用该路径;既有任务身份、导航防重、离页取消和 Debug 禁飞保护继续保持。 +- 独立模拟/调试启动以准备页本身作为导航根页面时,保留根页回退入口;不为此创建真实任务或构造新的工作台。 + +## 任务页移除详情与拍摄中原型对齐(2026-11-03 用户要求) + +- 拍摄任务页移除通用“详情”按钮,其他阶段的主按钮占整行;失败原因区域仍可点击展开完整原因。 +- 可信拍摄中阶段使用产品文案“无人机正在拍摄中”,说明分两行显示“请关注现场及实时画面。”和“请勿关闭本页或息屏。”。按 [机巢体验原型](https://voicestudio.suixinkan.cn/) 展示左侧浅蓝圆形视频图标、右侧标题与说明、下方整行浅蓝禁用“拍摄中”指示按钮。 +- 拍摄中面板不显示设备摘要和中央刷新操作;导航栏刷新保留。禁用的“拍摄中”仅作状态展示,不提交飞控或其他主操作。 +- 此调整只影响展示和操作布局,后台真实阶段、失败/取消优先级、任务身份与版本校验、安全门禁、HTTP/WS 读取及既有 Debug 禁飞保护不变;代理不执行真实任务创建、飞控或图传。 diff --git a/suixinkan/Core/Networking/DeviceCommandDebugPolicy.swift b/suixinkan/Core/Networking/DeviceCommandDebugPolicy.swift index 56aaeef..5b41a8b 100644 --- a/suixinkan/Core/Networking/DeviceCommandDebugPolicy.swift +++ b/suixinkan/Core/Networking/DeviceCommandDebugPolicy.swift @@ -22,7 +22,7 @@ enum DeviceCommandDebugPolicy { /// 页面与本地拦截共用的说明,不将未发送的请求表述为服务端执行失败。 static let blockedMessage = "当前禁止真实设备指令,请使用本地模拟调试" - /// 在日志和传输之前阻断操作请求;允许的状态读取关闭实时设备采集。 + /// 在日志和传输之前阻断操作请求;Release 准备页可读实时电量,其余状态读取关闭实时采集。 static func prepare(_ request: URLRequest, isLocalSimulation: Bool) throws -> URLRequest { guard !isLocalSimulation, let url = request.url else { return request } let path = "/" + url.path.split(separator: "/").joined(separator: "/") @@ -43,6 +43,10 @@ enum DeviceCommandDebugPolicy { guard request.httpMethod == "GET", readablePaths.contains(path) else { throw DeviceCommandDebugBlockedError() } + #if !DEBUG + // 2026-11-03 用户要求准备页获取电量;保留调用方的 live_battery,任务页仍强制读缓存。 + if path == "/api/app/airport/plane-status" { return request } + #endif let liveKey: String switch path { case "/api/app/airport/plane-status", "/api/app/airport/shooting": liveKey = "live_battery" diff --git a/suixinkan/Features/DroneDock/Models/DroneDockHomeModels.swift b/suixinkan/Features/DroneDock/Models/DroneDockHomeModels.swift index f5cd476..9094229 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockHomeModels.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockHomeModels.swift @@ -70,13 +70,13 @@ struct DroneDockHomeAirport: Decodable, Equatable, Sendable { let snNumber: String? /// 后端设备所属景区 ID。 let scenicAreaID: Int? - /// 原始在线状态;尚未取得完整枚举约定。 + /// 飞机表在线标记:1 在线,其他已提供整数为离线;忙闲以 workStatus 为准。 let onlineStatus: Int? /// 原始工作状态;不据此决定设备可否执行任务。 let workStatus: Int? /// 后端工作状态展示文案。 let workStatusLabel: String? - /// 原始接单配置;不等同于本次起飞许可。 + /// 接单配置:1 可接单、2 暂停接单;不等同于本次起飞许可。 let isReceiveOrder: Int? /// 任务类型原始值;当前样本为 null,暂不假定其枚举或值类型。 let taskType: DroneDockHomeJSONValue? diff --git a/suixinkan/Features/DroneDock/Models/DroneDockShootModels.swift b/suixinkan/Features/DroneDock/Models/DroneDockShootModels.swift index 7c46d50..17109e3 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockShootModels.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockShootModels.swift @@ -1,6 +1,6 @@ import Foundation -/// shoot 业务成功后的原始 data 回执,不假设或构造飞机、任务及飞行阶段字段。 +/// 保留 shoot 原始 data,并读取明确的同任务前往回执;不补造飞机或飞行阶段字段。 struct DroneDockShootResponse: Decodable, Equatable, Sendable { /// 完整 data JSON;nil 表示统一客户端未提供 data,不补造 null 或空对象。 let dataJSON: String? @@ -15,6 +15,30 @@ struct DroneDockShootResponse: Decodable, Equatable, Sendable { encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] dataJSON = String(decoding: try encoder.encode(DroneDockShootJSONSnapshot(value: raw)), as: UTF8.self) } + + /// 只认同一订单任务明确受理的前往阶段,用于进页过渡;回执不代表已经起飞或到达。 + func confirmsTravel(taskID: Int, orderNumber: String?, scenicID: Int) -> Bool { + guard taskID > 0, scenicID > 0, let orderNumber, !orderNumber.isEmpty, let dataJSON, + let receipt = try? JSONDecoder().decode(DroneDockSummonProgressReceipt.self, from: Data(dataJSON.utf8)), + receipt.accepted == true, receipt.ui?.phase == "going_to_spot", + receipt.orderFlightTask?.id == taskID, + receipt.orderFlightTask?.orderNumber == orderNumber, + receipt.orderFlightTask?.scenicID == scenicID else { return false } + return receipt.orderFlightTaskID == nil || receipt.orderFlightTaskID == taskID + } +} + +/// 首次召唤的已约定阶段和任务身份,仅支持显示前往中的过渡,不据此开放任何操作。 +private struct DroneDockSummonProgressReceipt: Decodable { + let accepted: Bool? + let ui: DroneDockShootingUI? + let orderFlightTaskID: Int? + let orderFlightTask: DroneDockResummonReceiptIdentity.TaskIdentity? + + /// 顶层 task_id 是航线任务,不参与订单任务匹配。 + private enum CodingKeys: String, CodingKey { + case accepted, ui, orderFlightTaskID = "order_flight_task_id", orderFlightTask = "order_flight_task" + } } /// 重新召唤回执中可核对的订单任务身份;顶层 task_id 属于实际航线任务,不作订单任务 ID 使用。 diff --git a/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift b/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift index 8e121ab..1785d77 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockShootingModels.swift @@ -16,6 +16,8 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable { let metricsUpdatedAt: String? /// 设备缓存过期时保留数值,但标为非实时读数。 let metricsStale: Bool? + /// 后端确认本批次正常拍完并开始返航;缺失表示旧合同,不能从工作态忙闲推断。 + let shootCompleteReturning: Bool? /// 后端若明确提供订单号则保留,不由请求上下文伪造响应身份。 let orderNumber: String? /// 实测返回的订单飞行任务身份;存在时必须与请求上下文核对。 @@ -48,6 +50,7 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable { case orderFlightTaskID = "order_flight_task_id", stateVersion = "state_version" case executionBatch = "execution_batch", snapshotKind = "snapshot_kind" case stateUpdatedAt = "state_updated_at", metricsUpdatedAt = "metrics_updated_at", metricsStale = "metrics_stale" + case shootCompleteReturning = "shoot_complete_returning" 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 @@ -64,6 +67,7 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable { stateUpdatedAt = try container.decodeIfPresent(String.self, forKey: .stateUpdatedAt) metricsUpdatedAt = try container.decodeIfPresent(String.self, forKey: .metricsUpdatedAt) metricsStale = try container.decodeIfPresent(Bool.self, forKey: .metricsStale) + shootCompleteReturning = try container.decodeIfPresent(Bool.self, forKey: .shootCompleteReturning) orderNumber = try container.decodeIfPresent(String.self, forKey: .orderNumber) orderFlightTask = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .orderFlightTask) task = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .task) @@ -91,22 +95,25 @@ struct DroneDockShootingTaskIdentity: Decodable, Equatable, Sendable { let orderNumber: String? /// 任务所属景区。 let scenicID: Int? - /// 后端原始任务状态,不与订单状态混用。 + /// 订单飞行任务状态:10 待执行、20 执行中、30 成功、40 失败、50 取消、60 待确认。 let status: Int? /// 服务端任务状态文案。 let statusLabel: String? - /// 实测航线任务状态,与订单飞行任务状态分别保留。 + /// 航线状态独立保留:29/39/49/91 失败,90 取消,24/30/40 为录制后的素材处理。 let waylineStatus: Int? /// 服务端航线状态文案;执行失败优先于笼统的订单任务执行中。 let waylineStatusLabel: String? /// 服务端实际记录的任务结果原因,空值不视为具体失败说明。 let resultMessage: String? + /// 任务结果原因码;return_home 表示手动返航中断,不能展示正常拍完提示。 + let resultCode: String? /// 已确认嵌套任务字段映射。 private enum CodingKeys: String, CodingKey { case id, orderNumber = "order_number", scenicID = "scenic_id", status, statusLabel = "status_label" case waylineStatus = "wayline_status", waylineStatusLabel = "wayline_status_label" case resultMessage = "result_message" + case resultCode = "result_code" } } @@ -169,7 +176,7 @@ struct DroneDockShootingPlane: Decodable, Equatable, Sendable { let id: Int? /// 当前设备序列号。 let snNumber: String? - /// 服务端连接状态;实测 2 为离线,不从电量推导连接状态。 + /// 飞机表在线标记:1 在线,0/2 等非 1 为离线;不覆盖明确的机巢工作态。 let onlineStatus: Int? /// 文档工作状态:0 离线、1 空闲、2 拍摄中;不据此推断返航完成。 let workStatus: Int? @@ -213,15 +220,28 @@ struct DroneDockShootingUI: Decodable, Equatable, Sendable { let title: String? /// 服务端阶段说明,不由 GET 请求成功拼造飞行进度。 let message: String? + /// 拍摄环节子阶段,shoot_done_returning 表示正常拍完后开始返航。 + let waylineStage: String? + /// 页面层的正常拍完返航标记,和顶层字段共同保留。 + let shootCompleteReturning: Bool? /// 服务端实际提供的安全指令;缺失时保持未知,不据阶段文案自行补齐。 let commands: [DroneDockShootingCommand]? /// 保留既有展示构造方式,新增动作列表默认为未知。 - init(phase: String?, title: String?, message: String?, commands: [DroneDockShootingCommand]? = nil) { + init(phase: String?, title: String?, message: String?, commands: [DroneDockShootingCommand]? = nil, + waylineStage: String? = nil, shootCompleteReturning: Bool? = nil) { self.phase = phase self.title = title self.message = message self.commands = commands + self.waylineStage = waylineStage + self.shootCompleteReturning = shootCompleteReturning + } + + /// 保留现有页面字段,并映射新增返航标记的原始命名。 + private enum CodingKeys: String, CodingKey { + case phase, title, message, commands + case waylineStage = "wayline_stage", shootCompleteReturning = "shoot_complete_returning" } } diff --git a/suixinkan/Features/DroneDock/Models/DroneDockTaskPresentation.swift b/suixinkan/Features/DroneDock/Models/DroneDockTaskPresentation.swift index a55115a..89af5e3 100644 --- a/suixinkan/Features/DroneDock/Models/DroneDockTaskPresentation.swift +++ b/suixinkan/Features/DroneDock/Models/DroneDockTaskPresentation.swift @@ -12,6 +12,8 @@ enum DroneDockTaskDisplayPhase: String, Equatable, Sendable { case shooting /// 录制已结束,素材仍在下载、上传或渲染,尚未就绪。 case postShootUploading + /// 录制已结束,但素材上传或渲染失败;可查看素材,不代表可重新召唤。 + case postShootUploadFailed /// 服务端明确已暂停。 case paused /// 服务端明确正在返航。 @@ -62,10 +64,13 @@ struct DroneDockTaskPresentation: Equatable, Sendable { let isActionEnabled: Bool /// 主动作下方的真实设备限制说明,未提供时不展示。 let actionNote: String? + /// 已到达阶段的本地展示倒计时;零秒不表示后端已经开始拍摄。 + let countdownSeconds: Int? /// 创建状态展示;动作提示默认为空,既有非失败状态保持原布局。 init(phase: DroneDockTaskDisplayPhase, title: String, message: String, deviceStatus: String, - action: DroneDockTaskDisplayAction, actionTitle: String?, isActionEnabled: Bool, actionNote: String? = nil) { + action: DroneDockTaskDisplayAction, actionTitle: String?, isActionEnabled: Bool, actionNote: String? = nil, + countdownSeconds: Int? = nil) { self.phase = phase self.title = title self.message = message @@ -74,5 +79,6 @@ struct DroneDockTaskPresentation: Equatable, Sendable { self.actionTitle = actionTitle self.isActionEnabled = isActionEnabled self.actionNote = actionNote + self.countdownSeconds = countdownSeconds } } diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockLiveViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockLiveViewModel.swift index 6f66060..34fabc0 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockLiveViewModel.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockLiveViewModel.swift @@ -99,7 +99,7 @@ final class DroneDockLiveViewModel { case .failed, .unavailable: return "重试" case .localPreview: return "重新加载模拟图传" case .connecting: return nil - case .playing: return "刷新图传" + case .playing: return nil } } @@ -137,8 +137,14 @@ final class DroneDockLiveViewModel { let canKeepSession = keepingPlayback && playbackSessionID != nil && sameDevice && rtcConfigurations.first?.appID == configurations.first?.appID - rtcConfigurations = configurations - rtcConfiguration = configurations.first + rtcConfigurations = configurations.map { incoming in + // live 每次可能生成新 user_id;补流时保留尚未临期的原入房身份,避免销毁健康房间。 + guard canKeepSession, let previous = rtcConfigurations.first(where: { $0.role == incoming.role }), + previous.appID == incoming.appID, previous.roomID == incoming.roomID, + previous.userID != incoming.userID, previous.expiresAt.timeIntervalSince(now()) > 30 else { return incoming } + return previous + } + rtcConfiguration = rtcConfigurations.first if !canKeepSession { activeRole = nil playbackSessionID = UUID() diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift index 3efe112..d3c11ec 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockPreparationViewModel.swift @@ -430,15 +430,17 @@ final class DroneDockPreparationViewModel { guard let selectedRoute else { return "\(selectedSpot.name) · 未选航线" } return "\(selectedSpot.name) · \(selectedRoute.name)" } - /// 优先展示服务端推荐无人机的完整文案,不自行重选列表中的另一架。 + /// 展示后端推荐设备,状态文案缺少电量时补充电量字段,不重选设备或把未知电量当零。 var deviceStatusText: String { guard let planeStatus else { return "状态待确认" } guard let recommendation = planeStatus.recommend else { return planeStatus.planes.isEmpty ? "暂无无人机" : "状态待确认" } - if let text = DroneDockHomeMetric.usableText(recommendation.statusText) { return text } - let state = DroneDockHomeMetric.usableText(recommendation.workStatusLabel) ?? "状态待确认" - let battery = DroneDockHomeMetric.usableText(recommendation.batteryLabel) + let state = DroneDockHomeMetric.usableText(recommendation.statusText) + ?? DroneDockHomeMetric.usableText(recommendation.workStatusLabel) ?? "状态待确认" + let percent = recommendation.batteryPercent.flatMap { (0...100).contains($0) ? $0 : nil } + let battery = DroneDockHomeMetric.usableText(recommendation.batteryLabel) ?? percent.map { "电量 \($0)%" } + if state.contains("%") || state.contains("%") || battery.map({ state.contains($0) }) == true { return state } return battery.map { "\(state) · \($0)" } ?? state } /// 状态颜色只映射文档定义的工作状态,未知值不展示为空闲。 diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift index 5ab7a77..7a749e1 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockShootingTaskViewModel.swift @@ -50,6 +50,8 @@ final class DroneDockShootingTaskViewModel { private let commandService: (any DroneDockCommandSending)? private let resummonService: (any DroneDockResummonServing)? private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext + private let countdownNow: @Sendable () -> ContinuousClock.Instant + private var arrivalCountdownDeadlines: [String: ContinuousClock.Instant] = [:] /// 无权限或登录失效后停止自动读取,旧数据仅用于展示。 private(set) var readAccessError: String? private var snapshotRevision = 0 @@ -62,6 +64,8 @@ final class DroneDockShootingTaskViewModel { private var resummonGeneration = 0 private var didSendResummon = false private var awaitingResummonSnapshot = false + // 仅在首份完整快照返回之前使用同一任务的 going_to_spot 回执,不补造设备状态。 + private var hasInitialTravelReceipt: Bool // 回查仍提供的已受理指令分别保留防重锁,避免另一条指令受理覆盖旧锁。 private var pendingAcceptedCommands: Set = [] @@ -71,6 +75,8 @@ final class DroneDockShootingTaskViewModel { startService: (any DroneDockStartShooting)? = nil, commandService: (any DroneDockCommandSending)? = nil, resummonService: (any DroneDockResummonServing)? = nil, + initialSummonReceipt: DroneDockShootResponse? = nil, + countdownNow: @escaping @Sendable () -> ContinuousClock.Instant = { ContinuousClock.now }, currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) { self.context = context self.taskID = taskID @@ -80,6 +86,9 @@ final class DroneDockShootingTaskViewModel { self.commandService = commandService self.resummonService = resummonService self.currentContext = currentContext + self.countdownNow = countdownNow + self.hasInitialTravelReceipt = context.canLoad && initialSummonReceipt?.confirmsTravel( + taskID: taskID, orderNumber: order.orderNumber, scenicID: context.scenicID) == true } /// 页面可见时读取同一任务;刷新及普通失败保留旧快照,身份失效立即清除。 @@ -166,6 +175,10 @@ final class DroneDockShootingTaskViewModel { } } response = value + if resolvedDisplayPhase().0 == .ready, arrivalCountdownDeadlines[recordingExecutionID] == nil { + arrivalCountdownDeadlines[recordingExecutionID] = countdownNow().advanced(by: .seconds(30)) + } + hasInitialTravelReceipt = false errorMessage = nil snapshotRevision &+= 1 DroneDockDiagnostics.event("shooting.snapshot_applied", taskID: taskID, fields: [ @@ -174,7 +187,7 @@ final class DroneDockShootingTaskViewModel { "state_version": value.stateVersion as Any? ?? NSNull(), "plane_id": value.currentPlane?.id as Any? ?? NSNull() ]) - if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .postShootUploading, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) { + if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .postShootUploading, .postShootUploadFailed, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) { awaitingResummonSnapshot = false } pendingAcceptedCommands.formIntersection(availableSafetyCommands) @@ -206,6 +219,8 @@ final class DroneDockShootingTaskViewModel { generation &+= 1 isLoading = false if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true } + if identityInvalidated || !preservingSnapshot { hasInitialTravelReceipt = false } + if identityInvalidated || !preservingSnapshot { arrivalCountdownDeadlines.removeAll() } if identityInvalidated { response = nil startResponse = nil @@ -316,6 +331,7 @@ final class DroneDockShootingTaskViewModel { /// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。 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) @@ -396,6 +412,7 @@ final class DroneDockShootingTaskViewModel { /// 此门禁用于客户端模拟交互,不代表后端已提供真实重试许可。 var canResummon: Bool { resummonService != nil && context.canLoad && taskID > 0 && !identityInvalidated + && !isTaskAwaitingConfirmation && readAccessError == nil && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil && !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown && !hasSubmittedResummon && pendingAcceptedCommands.isEmpty @@ -496,43 +513,102 @@ final class DroneDockShootingTaskViewModel { usable(response?.currentPlane?.statusText) ?? usable(response?.currentPlane?.workStatusLabel) ?? "—" } - /// 使用服务端阶段标题或任务状态,不从 GET 成功推导到达或拍摄完成。 + /// 录制完成与素材就绪分别保留;只由可信阶段触发完成提示,不修改后端任务状态。 + var isRecordingFinished: Bool { + let phase = resolvedDisplayPhase().0 + return [.postShootUploading, .postShootUploadFailed, .completed].contains(phase) + || (phase == .failed && hasMediaProcessingFailure) + } + + /// 只有录制正常结束或素材就绪才弹出完成提示,素材处理失败只展示失败状态。 + var shouldPresentRecordingCompletion: Bool { + [.postShootUploading, .completed].contains(resolvedDisplayPhase().0) + } + + /// 正常拍完后的返航说明仅取本批次可信完成阶段,上传/渲染或显式清标记后不沿用。 + var isShootCompleteReturning: Bool { + guard resolvedDisplayPhase().0 == .postShootUploading else { return false } + let waylines = [response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus].compactMap { $0 } + 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 flags.contains(true) || response?.ui?.waylineStage == "shoot_done_returning" { return true } + // 旧回包仍保留明确的设备返航文案;新合同不再依赖只有忙闲的 work_status。 + guard response?.ui?.waylineStage == nil else { return false } + return ["返航中", "正在返航"].contains(usable(response?.currentPlane?.workStatusLabel) ?? "") + } + + /// 完成提示按当前任务的执行批次去重,旧快照仍由统一版本校验拒绝。 + var recordingExecutionID: String { + "\(taskID):\(response?.executionBatch ?? 0)" + } + + /// App 首次确认本批次到达后显示 30 秒本地倒计时;到零仍等待后端阶段,不触发控制或状态读取。 + var countdownRemainingSeconds: Int? { + guard !identityInvalidated, readAccessError == nil, resolvedDisplayPhase().0 == .ready, + let deadline = arrivalCountdownDeadlines[recordingExecutionID] else { return nil } + let remaining = countdownNow().duration(to: deadline) + guard remaining > .zero else { return 0 } + let parts = remaining.components + 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 usable(response?.ui?.title) ?? "拍摄完毕上传中" + return "拍摄已完成" } return usable(response?.ui?.title) ?? usable(response?.task?.statusLabel) ?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认" } - /// 保留服务端阶段说明;操作结果未知时优先提示核对,不伪装为设备已执行。 + /// 拍摄阶段使用产品提示,其余保留服务端说明;操作结果未知时优先提示核对。 var statusMessage: String { if response == nil { if let errorMessage { return errorMessage } + if hasInitialTravelReceipt { return "召唤已受理,正在等待设备到达确认,请留在拍摄点。" } if isLoading { return "正在读取当前拍摄任务" } } if let resummonErrorMessage { return resummonErrorMessage } if awaitingResummonSnapshot { return "重新召唤请求已受理,请刷新核对任务状态" } if let commandErrorMessage { return commandErrorMessage } if resolvedDisplayPhase().0 == .failed { return failureMessage } + if resolvedDisplayPhase().0 == .postShootUploadFailed { return mediaFailureMessage } + if isTaskAwaitingConfirmation { return usable(response?.ui?.message) ?? "任务结果待确认,请刷新核对状态。" } if startOutcomeUnknown, let startErrorMessage { return startErrorMessage } if resolvedDisplayPhase().0 == .ready { if let startErrorMessage { return startErrorMessage } if hasSubmittedStart { return "开始拍摄请求已受理,请刷新确认任务状态" } } if resolvedDisplayPhase().0 == .postShootUploading { - return usable(response?.ui?.message) ?? "录制已结束,素材正在处理,请稍候。" + let waylines = [response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus] + let note: String + if isShootCompleteReturning { note = "无人机正在返航,请留意现场。" } + else if waylines.contains(30) { note = "素材上传中,可在素材库查看进度。" } + else if waylines.contains(40) { note = "素材渲染中,可在素材库查看进度。" } + else { note = "素材处理中,可在素材库查看进度。" } + return "本次拍摄已结束,可前往查看素材。\n" + note } + if resolvedDisplayPhase().0 == .shooting { return "请关注现场及实时画面。\n请勿关闭本页或息屏。" } return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—" } /// 组合可信阶段与本轮可用动作,不从请求成功、执行中或指令列表推断飞行进度。 var presentation: DroneDockTaskPresentation { + if response == nil, hasInitialTravelReceipt, errorMessage == nil, !identityInvalidated { + return DroneDockTaskPresentation(phase: .navigating, title: statusTitle, message: statusMessage, + deviceStatus: deviceStatusText, action: .none, actionTitle: nil, isActionEnabled: false) + } if response == nil, isLoading { return DroneDockTaskPresentation(phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务", deviceStatus: deviceStatusText, action: .none, actionTitle: nil, isActionEnabled: false) @@ -548,6 +624,10 @@ final class DroneDockShootingTaskViewModel { let actionTitle: String? let enabled: Bool switch phase { + case .shooting: + action = .none + actionTitle = "拍摄中" + enabled = false case .ready where hasSubmittedStart || startOutcomeUnknown || commandOutcomeUnknown || resummonOutcomeUnknown: action = .refresh actionTitle = "刷新状态" @@ -561,7 +641,7 @@ final class DroneDockShootingTaskViewModel { action = .resume actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "继续拍摄" enabled = false - case .completed: + case .completed, .postShootUploading, .postShootUploadFailed: action = .materials actionTitle = "查看素材" enabled = true @@ -581,7 +661,8 @@ 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) + actionNote: phase == .failed && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil, + countdownSeconds: countdownRemainingSeconds) } /// 后端六项展示读数,不解析文案反推设备状态或数值单位。 @@ -683,27 +764,34 @@ final class DroneDockShootingTaskViewModel { && scenicIDs.allSatisfy { $0 == context.scenicID } } - /// 只认识显式阶段和已确认任务状态;91 为真实航线执行失败,不把订单状态 20 当作正在拍摄。 + /// 按任务终态、明确 UI 阶段与航线失败判断,不把机巢忙闲或订单执行中当作拍摄进度。 private func resolvedDisplayPhase() -> (DroneDockTaskDisplayPhase, Bool) { guard let response else { return (.unknown, false) } let tasks = [response.task, response.orderFlightTask].compactMap { $0 } let statuses = Set(tasks.compactMap(\.status)) - if tasks.contains(where: { $0.waylineStatus == 91 }) || statuses.contains(40) { return (.failed, false) } - if statuses.contains(50) { return (.blocked, false) } + let waylines = Set(tasks.compactMap(\.waylineStatus)) + let rawPhase = usable(response.ui?.phase) + if statuses.contains(50) || waylines.contains(90) || statuses.contains(60) { return (.blocked, false) } + if tasks.contains(where: { $0.resultCode == "return_home" }) { return (.failed, false) } + if !waylines.isDisjoint(with: [29, 39, 49, 91]) || statuses.contains(40) { + let isMediaFailure = rawPhase == "post_shoot_upload_failed" + || (hasMediaProcessingFailure && rawPhase != "failed_restartable") + return (isMediaFailure ? .postShootUploadFailed : .failed, false) + } if statuses.count > 1 { return (.unknown, true) } let known: [String: DroneDockTaskDisplayPhase] = [ "going_to_spot": .navigating, "failed_restartable": .failed, "waiting_summon": .blocked, "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 ] - let rawPhase = usable(response.ui?.phase) let phase = rawPhase.flatMap { known[$0] } if rawPhase != nil && phase == nil { return (.unknown, false) } if phase == .failed { return (.failed, false) } if statuses.contains(30) { if phase == .returning { return (.returning, false) } - if let phase, [.navigating, .ready, .shooting, .postShootUploading, .paused].contains(phase) { return (.unknown, true) } + if let phase, [.navigating, .ready, .shooting, .postShootUploading, .postShootUploadFailed, .paused].contains(phase) { return (.unknown, true) } return (.completed, false) } if phase == .completed { @@ -725,21 +813,28 @@ final class DroneDockShootingTaskViewModel { 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 .navigating: return "无人机正在前往拍摄点" + case .navigating: return "无人机正在赶来" case .ready: return "无人机已到达" case .shooting: return "正在拍摄" - case .postShootUploading: return "拍摄完毕上传中" + case .postShootUploading: return "拍摄已完成" + case .postShootUploadFailed: return mediaFailureTitle case .paused: return "拍摄已暂停" case .returning: return "无人机正在返航" case .failed: return "任务执行失败" @@ -756,20 +851,54 @@ final class DroneDockShootingTaskViewModel { ?? usable(response?.executeGate?.message) ?? usable(response?.ui?.message) ?? "暂未返回具体失败原因" } + /// 39/49 表示录制后的素材处理失败,不能据此生成起飞或重召唤许可。 + private var hasMediaProcessingFailure: Bool { + [response?.task?.waylineStatus, response?.orderFlightTask?.waylineStatus] + .compactMap { $0 }.contains { [39, 49].contains($0) } + } + + private var isTaskAwaitingConfirmation: Bool { + response?.orderFlightTask?.status == 60 || response?.task?.status == 60 + } + + 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) + ? "素材渲染失败" : "素材上传失败" + } + + private var mediaFailureMessage: String { + usable(response?.orderFlightTask?.resultMessage) ?? usable(response?.task?.resultMessage) + ?? usable(response?.ui?.message) ?? usable(response?.task?.waylineStatusLabel) + ?? usable(response?.orderFlightTask?.waylineStatusLabel) ?? "素材处理失败,请前往素材库查看。" + } + + /// 工作态优先;工作态缺失或未识别时才用飞机表在线标记保守兜底。 + private var isResummonDeviceOffline: Bool { + switch response?.currentPlane?.workStatus { + case 0: return true + case 1, 2: return false + default: + if let online = response?.currentPlane?.onlineStatus { return online != 1 } + return usable(response?.currentPlane?.workStatusLabel) == "离线" + } + } + /// 明确离线或返航时保持禁用,不从普通空闲文案推导后端重试许可。 private var isResummonDeviceUnavailable: Bool { let plane = response?.currentPlane - return response?.planeStatus?.connected == false || plane?.onlineStatus == 2 || plane?.workStatus == 0 - || ["离线", "返航中", "正在返航"].contains(usable(plane?.workStatusLabel) ?? "") + return response?.planeStatus?.connected == false || isResummonDeviceOffline || plane?.workStatus == 2 + || ["返航中", "正在返航"].contains(usable(plane?.workStatusLabel) ?? "") || response?.ui?.phase == "returning" } /// 正式入口未注入操作服务时说明当前限制;模拟页保留实际设备不可用原因。 private var retryUnavailableNote: String { let plane = response?.currentPlane - if plane?.onlineStatus == 2 || plane?.workStatus == 0 || usable(plane?.workStatusLabel) == "离线" { + if isResummonDeviceOffline { return "无人机离线,暂不可召唤" } + if plane?.workStatus == 2 { return "无人机忙碌,暂不可召唤" } if let status = usable(plane?.workStatusLabel), ["返航中", "正在返航"].contains(status) { return "无人机返航中,暂不可召唤" } diff --git a/suixinkan/UI/DroneDock/DroneDockRecordingCompletionView.swift b/suixinkan/UI/DroneDock/DroneDockRecordingCompletionView.swift new file mode 100644 index 0000000..dfeabb2 --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneDockRecordingCompletionView.swift @@ -0,0 +1,86 @@ +import SnapKit +import UIKit + +/// 与任务原型一致的录制完成提示;只引导查看素材,不宣告上传成功或扣减次数。 +@MainActor +final class DroneDockRecordingCompletionView: UIView { + /// 关闭提示并继续留在任务页。 + var onLater: (() -> Void)? + /// 前往当前订单素材库。 + var onViewMaterials: (() -> Void)? + + /// 创建居中结果卡片,覆盖任务页但不触发生命周期或暂停只读状态更新。 + override init(frame: CGRect) { + super.init(frame: frame) + setupUI() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + private func setupUI() { + backgroundColor = .black.withAlphaComponent(0.5) + accessibilityViewIsModal = true + accessibilityIdentifier = "drone.task.recordingCompletion" + let card = UIView() + card.backgroundColor = .white + card.layer.cornerRadius = 14 + addSubview(card) + let symbol = UIImageView(image: UIImage(systemName: "checkmark.circle.fill")) + symbol.tintColor = DroneDockStyle.success + symbol.contentMode = .scaleAspectFit + let title = DroneDockStyle.label(size: 20, weight: .semibold) + title.text = "拍摄已完成" + title.textAlignment = .center + let message = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary) + message.text = "本次拍摄已完成,\n可前往订单素材库查看上传进度和素材。" + message.numberOfLines = 0 + message.textAlignment = .center + let later = button("稍后再去", primary: false, action: #selector(laterTapped)) + let materials = button("去查看", primary: true, action: #selector(materialsTapped)) + later.accessibilityIdentifier = "drone.task.recordingCompletion.later" + materials.accessibilityIdentifier = "drone.task.recordingCompletion.materials" + let actions = UIStackView(arrangedSubviews: [later, materials]) + actions.spacing = 10 + actions.distribution = .fillEqually + [symbol, title, message, actions].forEach { card.addSubview($0) } + card.snp.makeConstraints { make in + make.center.equalToSuperview() + make.width.equalTo(320).priority(.high) + make.leading.greaterThanOrEqualToSuperview().offset(24) + make.trailing.lessThanOrEqualToSuperview().offset(-24) + } + symbol.snp.makeConstraints { make in + make.top.equalToSuperview().offset(24) + make.centerX.equalToSuperview() + make.size.equalTo(50) + } + title.snp.makeConstraints { make in + make.top.equalTo(symbol.snp.bottom).offset(16) + make.leading.trailing.equalToSuperview().inset(20) + } + message.snp.makeConstraints { make in + make.top.equalTo(title.snp.bottom).offset(12) + make.leading.trailing.equalToSuperview().inset(20) + } + actions.snp.makeConstraints { make in + make.top.equalTo(message.snp.bottom).offset(24) + make.leading.trailing.bottom.equalToSuperview().inset(16) + make.height.equalTo(46) + } + } + + private func button(_ title: String, primary: Bool, action: Selector) -> UIButton { + let button = UIButton(type: .system) + button.setTitle(title, for: .normal) + button.setTitleColor(primary ? .white : DroneDockStyle.text, for: .normal) + button.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold) + button.backgroundColor = primary ? DroneDockStyle.primary : UIColor(hex: 0xEEF0F6) + button.layer.cornerRadius = 7 + button.addTarget(self, action: action, for: .touchUpInside) + return button + } + + @objc private func laterTapped() { onLater?() } + @objc private func materialsTapped() { onViewMaterials?() } +} diff --git a/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift b/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift index a98b716..9d7ca53 100644 --- a/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockRemotePreparationViewController.swift @@ -36,7 +36,9 @@ final class DroneDockRemotePreparationViewController: BaseViewController { self.viewModel = viewModel self.simulationRecordsProvider = simulationRecordsProvider self.taskControllerFactory = taskControllerFactory ?? { taskID, order, context in - DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context) + DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context, + coverURL: viewModel.selectedSpot?.displayCoverURL, + initialSummonReceipt: viewModel.shootResponse) } self.planeStatusPollDelay = planeStatusPollDelay super.init(nibName: nil, bundle: nil) @@ -222,7 +224,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController { present(alert, animated: true) } - /// 成功后自动导航一次;失败的已结束任务只在用户明确点击时查看原任务。 + /// 进入任务时替换有前驱的准备页,返回直达工作台;独立调试根页保留原返回入口。 @discardableResult private func openShootingTask(automatically: Bool) -> Bool { guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask, @@ -232,7 +234,12 @@ final class DroneDockRemotePreparationViewController: BaseViewController { DroneDockDiagnostics.event("navigation.open_task", taskID: taskID) automaticallyOpenedTaskID = taskID let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context) - navigationController.pushViewController(controller, animated: true) + let stack = navigationController.viewControllers + if stack.count > 1 { + navigationController.setViewControllers(Array(stack.dropLast()) + [controller], animated: true) + } else { + navigationController.pushViewController(controller, animated: true) + } return true } diff --git a/suixinkan/UI/DroneDock/DroneDockShootingTaskEntry.swift b/suixinkan/UI/DroneDock/DroneDockShootingTaskEntry.swift index ef9a035..2a5acc9 100644 --- a/suixinkan/UI/DroneDock/DroneDockShootingTaskEntry.swift +++ b/suixinkan/UI/DroneDock/DroneDockShootingTaskEntry.swift @@ -6,6 +6,13 @@ enum DroneDockShootingTaskEntry { /// 使用已有任务读取状态;Release 注入已授权的真实控制,Debug 保持只读。 static func makeController(taskID: Int, order: DroneDockHomeOrder, context: DroneDockHomeContext) -> UIViewController { + makeController(taskID: taskID, order: order, context: context, coverURL: nil) + } + + /// 准备页携带封面及召唤回执;其它入口不推断前往阶段,等 shooting 返回。 + static func makeController(taskID: Int, order: DroneDockHomeOrder, + context: DroneDockHomeContext, coverURL: URL?, + initialSummonReceipt: DroneDockShootResponse? = nil) -> UIViewController { let client = NetworkServices.shared.apiClient let realtime = DroneDockShootingRealtimeSession(taskID: taskID, ticketService: DroneDockSocketTokenAPI(client: client), @@ -22,7 +29,8 @@ enum DroneDockShootingTaskEntry { startService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockStartShootAPI(client: client), commandService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockCommandAPI(client: client), resummonService: DeviceCommandDebugPolicy.blocksFlightRequests ? nil : DroneDockShootAPI(client: client), + initialSummonReceipt: initialSummonReceipt, currentContext: { DroneDockHomeViewController.currentContext() } - ), liveViewModel: live, realtimeSession: realtime) + ), liveViewModel: live, coverURL: coverURL, realtimeSession: realtime) } } diff --git a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift index 0487a13..e764b80 100644 --- a/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockShootingTaskViewController.swift @@ -43,17 +43,27 @@ final class DroneDockShootingTaskViewController: BaseViewController { private var isSendingSafetyAction = false private var isResummoningAction = false private var wasRealtimeLive = false + private let coverURL: URL? + private var finishedExecutions: Set = [] + private var displayedCompletionIDs: Set = [] + private var completionNotice: DroneDockRecordingCompletionView? + private let countdownDelay: @Sendable () async throws -> Void + private var countdownTask: Task? + private var countdownGeneration = 0 /// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。 init(viewModel: DroneDockShootingTaskViewModel, liveViewModel: DroneDockLiveViewModel? = nil, livePlayer: (any DroneDockLivePlaying)? = nil, + coverURL: URL? = nil, realtimeSession: DroneDockShootingRealtimeSession? = nil, materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil, simulationRecordsProvider: (@MainActor () -> String)? = nil, shootingPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }, - liveParameterDelay: @escaping @Sendable (TimeInterval) async throws -> Void = { try await Task.sleep(for: .seconds($0)) }) { + liveParameterDelay: @escaping @Sendable (TimeInterval) async throws -> Void = { try await Task.sleep(for: .seconds($0)) }, + countdownDelay: @escaping @Sendable () async throws -> Void = { try await Task.sleep(for: .seconds(1)) }) { self.viewModel = viewModel + self.coverURL = coverURL self.feedPlaceholder = livePlayer.map { DroneDockTaskLiveView(rtcPlayer: $0) } ?? DroneDockTaskLiveView() self.realtimeSession = realtimeSession self.liveViewModel = liveViewModel ?? DroneDockLiveViewModel( @@ -62,6 +72,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { self.simulationRecordsProvider = simulationRecordsProvider self.shootingPollDelay = shootingPollDelay self.liveParameterDelay = liveParameterDelay + self.countdownDelay = countdownDelay self.materialsControllerFactory = materialsControllerFactory ?? { order, context in DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel( context: context, order: order, @@ -92,6 +103,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { resummonTask?.cancel() liveTask?.cancel() liveParameterTask?.cancel() + countdownTask?.cancel() NotificationCenter.default.removeObserver(self) } @@ -228,6 +240,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) isPageVisible = false + dismissCompletionNotice() logEvent("page.disappeared") cancelRefresh() stopLive() @@ -235,26 +248,103 @@ final class DroneDockShootingTaskViewController: BaseViewController { private func applySnapshot() { guard isViewLoaded else { return } + if viewModel.isRecordingFinished { finishedExecutions.insert(viewModel.recordingExecutionID) } + let recordingFinished = finishedExecutions.contains(viewModel.recordingExecutionID) + if !viewModel.shouldPresentRecordingCompletion { dismissCompletionNotice() } + if recordingFinished, liveTask != nil || liveParameterTask != nil || liveViewModel.playbackSessionID != nil || liveViewModel.playbackURL != nil { + stopLive() + } + feedPlaceholder.showRecordingCover(recordingFinished, url: coverURL) let loading = (viewModel.response == nil && (isRequesting || viewModel.isLoading)) || isStartingAction || viewModel.isStartingShooting || isSendingSafetyAction || viewModel.isSendingCommand || isResummoningAction || viewModel.isResummoning feedPlaceholder.apply(liveViewModel) - feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive) + feedPlaceholder.setPlaybackActive(isPageVisible && isApplicationActive && !recordingFinished) taskTitleLabel.text = viewModel.title subtitleLabel.text = viewModel.subtitle + (viewModel.response?.metricsStale == true ? " · 读数已过期" : "") let telemetry = viewModel.telemetry telemetryView.apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText, telemetry.rainText, telemetry.signalText, telemetry.satelliteText], isStale: viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric", preservingStaleValues: true) - let value = loading && viewModel.response == nil ? DroneDockTaskPresentation( + let presentation = viewModel.presentation + let value = loading && viewModel.response == nil && presentation.phase != .navigating ? DroneDockTaskPresentation( phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务", - deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation + deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : presentation statusView.apply(value, isRefreshing: loading) + updateArrivalCountdown() safetyView.apply(model: viewModel, isSimulation: simulationRecordsProvider != nil, isInteractive: isPageVisible && isApplicationActive && !loading) statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading navigationItem.rightBarButtonItems?.forEach { $0.isEnabled = isPageVisible && isApplicationActive && !loading } navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil + presentCompletionNoticeIfNeeded() + refreshLiveIfVisible(automatically: true) + } + + /// 倒计时只更新独立秒数标签;网络读取、飞控及后端阶段仍由原有流程驱动。 + private func updateArrivalCountdown() { + let seconds = viewModel.countdownRemainingSeconds + statusView.updateCountdown(seconds: seconds) + guard isPageVisible, isApplicationActive, let seconds, seconds > 0 else { + stopArrivalCountdown() + return + } + guard countdownTask == nil else { return } + countdownGeneration += 1 + let generation = countdownGeneration + let delay = countdownDelay + countdownTask = Task { @MainActor [weak self] in + while !Task.isCancelled { + do { try await delay() } catch { return } + guard let self, !Task.isCancelled, self.countdownGeneration == generation, + self.isPageVisible, self.isApplicationActive else { return } + let remaining = self.viewModel.countdownRemainingSeconds + self.statusView.updateCountdown(seconds: remaining) + if remaining == nil || remaining == 0 { + self.countdownTask = nil + return + } + } + } + } + + private func stopArrivalCountdown() { + countdownGeneration += 1 + countdownTask?.cancel() + countdownTask = nil + } + + private func presentCompletionNoticeIfNeeded() { + let id = viewModel.recordingExecutionID + guard viewModel.shouldPresentRecordingCompletion, isPageVisible, isApplicationActive, view.window != nil, + presentedViewController == nil, completionNotice == nil, !displayedCompletionIDs.contains(id) else { return } + displayedCompletionIDs.insert(id) + let notice = DroneDockRecordingCompletionView() + completionNotice = notice + notice.onLater = { [weak self] in self?.dismissCompletionNotice() } + notice.onViewMaterials = { [weak self] in + guard let self, self.isPageVisible, self.isApplicationActive, + self.viewModel.recordingExecutionID == id else { return } + self.dismissCompletionNotice() + self.openMaterials() + } + let container = navigationController?.view ?? view! + container.addSubview(notice) + notice.snp.makeConstraints { $0.edges.equalToSuperview() } + UIAccessibility.post(notification: .screenChanged, argument: notice) + } + + private func dismissCompletionNotice() { + completionNotice?.removeFromSuperview() + completionNotice = nil + } + + private func openMaterials() { + guard isPageVisible, isApplicationActive, presentedViewController == nil, + viewModel.presentation.action == .materials, viewModel.presentation.isActionEnabled, + let navigationController, navigationController.topViewController === self else { return } + dismissCompletionNotice() + navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true) } private func primaryActionTriggered() { @@ -274,8 +364,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { case .retry: resummonIfAllowed() case .materials: - guard let navigationController, navigationController.topViewController === self else { return } - navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true) + openMaterials() case .resume, .none: break } @@ -366,6 +455,7 @@ final class DroneDockShootingTaskViewController: BaseViewController { } private func cancelRefresh() { + stopArrivalCountdown() wasRealtimeLive = false realtimeSession?.stop() cancelScheduledPoll() @@ -473,6 +563,8 @@ 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 } guard !automatically || liveViewModel.loadsAutomatically else { return } guard isPageVisible, isApplicationActive, liveTask == nil, liveViewModel.canLoad else { return } liveParameterTask?.cancel() diff --git a/suixinkan/UI/DroneDock/DroneDockTaskCompletedView.swift b/suixinkan/UI/DroneDock/DroneDockTaskCompletedView.swift new file mode 100644 index 0000000..e20c40d --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneDockTaskCompletedView.swift @@ -0,0 +1,133 @@ +import SnapKit +import UIKit + +/// 拍摄完成区域:左侧完成图标、右侧状态说明以及整行素材入口。 +@MainActor +final class DroneDockTaskCompletedView: UIView { + /// 用户点击已允许的素材入口时通知任务页面。 + var onViewMaterials: (() -> Void)? + /// 与任务固定区域共享紧凑布局指标,操作区域始终至少 44 点高。 + private(set) var usesCompactLayout = false + + private let content = UIView() + private let iconBackground = UIView() + private let icon = UIImageView(image: UIImage(systemName: "checkmark.circle.fill")) + private let titleLabel = DroneDockStyle.label(size: 20, weight: .semibold) + private let messageLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary) + private let materialsButton = UIButton(type: .system) + private var messageHeight: Constraint? + private var titleHeight: Constraint? + private var buttonHeight: 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) { + titleLabel.text = presentation.title + messageLabel.text = presentation.message + var configuration = materialsButton.configuration + configuration?.title = presentation.actionTitle + materialsButton.isEnabled = presentation.action == .materials && presentation.isActionEnabled && !isRefreshing + configuration?.baseBackgroundColor = DroneDockStyle.primary.withAlphaComponent(materialsButton.isEnabled ? 1 : 0.35) + materialsButton.configuration = configuration + setNeedsLayout() + } + + /// 仅当前可见面板提供通用任务访问标识,防止状态切换后匹配到隐藏控件。 + func setIdentifiersActive(_ active: Bool) { + titleLabel.accessibilityIdentifier = active ? "drone.task.remote.statusTitle" : nil + messageLabel.accessibilityIdentifier = active ? "drone.task.remote.statusMessage" : nil + materialsButton.accessibilityIdentifier = active ? "drone.task.remote.primary" : nil + } + + /// 固定区域变小时收紧说明行数与间距,不改变整页布局或缩小点击区域。 + override func layoutSubviews() { + usesCompactLayout = bounds.height < 190 + let extreme = bounds.height < 120 + titleLabel.font = .systemFont(ofSize: extreme ? 17 : 20, weight: .semibold) + messageLabel.font = .systemFont(ofSize: usesCompactLayout ? 13 : 14) + messageLabel.numberOfLines = usesCompactLayout ? 2 : 3 + let width = max(1, bounds.width - 84) + let measured = messageLabel.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height + let title = ceil(titleLabel.font.lineHeight) + let button: CGFloat = usesCompactLayout ? 44 : 50 + let availableMessageHeight = max(0, bounds.height - 24 - title - 6 - 16 - button) + let body = min(ceil(measured), availableMessageHeight) + messageLabel.isHidden = body < messageLabel.font.lineHeight + messageHeight?.update(offset: messageLabel.isHidden ? 0 : body) + titleHeight?.update(offset: title) + buttonHeight?.update(offset: button) + super.layoutSubviews() + } + + private func setupUI() { + accessibilityIdentifier = "drone.task.remote.completed" + addSubview(content) + [iconBackground, titleLabel, messageLabel, materialsButton].forEach(content.addSubview) + iconBackground.addSubview(icon) + iconBackground.backgroundColor = DroneDockStyle.success.withAlphaComponent(0.12) + iconBackground.layer.cornerRadius = 20 + icon.contentMode = .scaleAspectFit + icon.tintColor = DroneDockStyle.success + titleLabel.accessibilityTraits = .header + titleLabel.numberOfLines = 1 + titleLabel.lineBreakMode = .byTruncatingTail + messageLabel.lineBreakMode = .byTruncatingTail + var configuration = UIButton.Configuration.filled() + configuration.baseForegroundColor = .white + configuration.background.cornerRadius = 8 + configuration.cornerStyle = .fixed + configuration.image = UIImage(systemName: "photo", withConfiguration: UIImage.SymbolConfiguration(pointSize: 15)) + configuration.imagePadding = 8 + configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in + var result = attributes + result.font = .systemFont(ofSize: 15, weight: .semibold) + return result + } + materialsButton.configuration = configuration + materialsButton.addTarget(self, action: #selector(viewMaterials), for: .touchUpInside) + } + + private func setupConstraints() { + content.snp.makeConstraints { make in + make.leading.trailing.equalToSuperview().inset(16) + make.centerY.equalToSuperview() + } + iconBackground.snp.makeConstraints { make in + make.top.leading.equalToSuperview() + make.size.equalTo(40) + } + icon.snp.makeConstraints { make in + make.center.equalToSuperview() + make.size.equalTo(22) + } + titleLabel.snp.makeConstraints { make in + make.top.trailing.equalToSuperview() + make.leading.equalTo(iconBackground.snp.trailing).offset(12) + titleHeight = make.height.equalTo(24).constraint + } + messageLabel.snp.makeConstraints { make in + make.top.equalTo(titleLabel.snp.bottom).offset(6) + make.leading.trailing.equalTo(titleLabel) + messageHeight = make.height.equalTo(34).constraint + } + materialsButton.snp.makeConstraints { make in + make.top.equalTo(messageLabel.snp.bottom).offset(16) + make.leading.trailing.bottom.equalToSuperview() + buttonHeight = make.height.equalTo(50).constraint + } + } + + @objc private func viewMaterials() { + guard !isHidden, materialsButton.isEnabled else { return } + onViewMaterials?() + } +} diff --git a/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift b/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift index 68bbaee..760b139 100644 --- a/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift +++ b/suixinkan/UI/DroneDock/DroneDockTaskLiveView.swift @@ -1,4 +1,5 @@ import AVFoundation +import Kingfisher import SnapKit import UIKit @@ -14,6 +15,8 @@ final class DroneDockTaskLiveView: UIView { private let titleLabel = DroneDockStyle.label(size: 15, weight: .medium, color: .white) private let messageLabel = DroneDockStyle.label(size: 12, color: .lightGray) private let sourceLabel = DroneDockStyle.label(size: 11, weight: .medium, color: .white) + private let sourceBadge = UIStackView() + private let liveDot = UIView() private let requestButton = UIButton(type: .system) private let labels = UIStackView() private var player: AVQueuePlayer? @@ -22,6 +25,12 @@ final class DroneDockTaskLiveView: UIView { private var activeURL: URL? private var isPlaybackActive = false private let rtcView = UIView() + private let coverView = UIImageView() + private let coverShade = UIView() + private let coverIcon = UIImageView(image: UIImage(systemName: "photo.on.rectangle.angled")) + private var labelsCenterY: Constraint? + private var isShowingCover = false + private var coverURL: URL? private let rtcPlayer: any DroneDockLivePlaying private var requestedRTC: [DroneDockVolcLiveConfiguration] = [] private var activeRTC: [DroneDockVolcLiveConfiguration] = [] @@ -64,6 +73,7 @@ final class DroneDockTaskLiveView: UIView { /// 在明确时机应用模型;远程 URL 即使错误传入也不会创建播放器。 func apply(_ model: DroneDockLiveViewModel) { + guard !isShowingCover else { return } titleLabel.text = model.title messageLabel.text = model.message requestButton.setTitle(model.actionTitle, for: .normal) @@ -74,8 +84,9 @@ final class DroneDockTaskLiveView: UIView { requestedSessionID = model.playbackSessionID let hasLocalPreview = requestedURL != nil let isPlaying = model.state == .playing - sourceLabel.text = hasLocalPreview ? "本地模拟画面 · 未连接无人机" : (isPlaying ? model.message + " · 实时图传" : nil) - sourceLabel.isHidden = !hasLocalPreview && !isPlaying + sourceLabel.text = hasLocalPreview ? "本地模拟画面 · 未连接无人机" : "实时图传" + sourceBadge.isHidden = !hasLocalPreview && !isPlaying + liveDot.isHidden = hasLocalPreview titleLabel.isHidden = hasLocalPreview || isPlaying messageLabel.isHidden = hasLocalPreview || isPlaying accessibilityLabel = hasLocalPreview || isPlaying ? sourceLabel.text : "\(model.title),\(model.message)" @@ -84,10 +95,32 @@ final class DroneDockTaskLiveView: UIView { /// 页面离开或进入后台立即释放播放器;重新获取图传参数由控制器协调。 func setPlaybackActive(_ active: Bool) { - isPlaybackActive = active + isPlaybackActive = active && !isShowingCover updatePlayback() } + /// 录制结束后仅展示静态封面;隐藏实时标记和重试按钮,旧模型不能恢复播放。 + func showRecordingCover(_ show: Bool, url: URL?) { + guard isShowingCover != show || coverURL != url else { return } + isShowingCover = show + coverURL = url + coverView.isHidden = !show + coverShade.isHidden = !show + coverIcon.isHidden = !show || url != nil + labelsCenterY?.update(offset: show ? 38 : -15) + guard show else { coverView.kf.cancelDownloadTask(); return } + setPlaybackActive(false) + coverView.contentMode = .scaleAspectFill + coverView.kf.setImage(with: url) + titleLabel.text = "拍摄已完成" + titleLabel.isHidden = false + messageLabel.text = "拍摄封面 · 实时图传已结束" + messageLabel.isHidden = false + sourceBadge.isHidden = true + requestButton.isHidden = true + accessibilityLabel = "拍摄已完成,拍摄封面,实时图传已结束" + } + private func setupUI() { backgroundColor = UIColor(hex: 0x171B22) clipsToBounds = true @@ -95,6 +128,19 @@ final class DroneDockTaskLiveView: UIView { layer.addSublayer(playerLayer) rtcView.backgroundColor = .clear addSubview(rtcView) + coverView.backgroundColor = UIColor(hex: 0x182A36) + coverView.tintColor = UIColor.white.withAlphaComponent(0.22) + coverView.clipsToBounds = true + coverView.isHidden = true + coverView.accessibilityIdentifier = "drone.task.remote.live.cover" + addSubview(coverView) + coverShade.backgroundColor = .black.withAlphaComponent(0.3) + coverShade.isHidden = true + addSubview(coverShade) + coverIcon.contentMode = .scaleAspectFit + coverIcon.tintColor = .white.withAlphaComponent(0.7) + coverIcon.isHidden = true + addSubview(coverIcon) playerLayer.videoGravity = .resizeAspect titleLabel.textAlignment = .center messageLabel.textAlignment = .center @@ -102,11 +148,16 @@ final class DroneDockTaskLiveView: UIView { messageLabel.accessibilityIdentifier = "drone.task.remote.live.status" titleLabel.accessibilityIdentifier = "drone.task.remote.live.title" sourceLabel.accessibilityIdentifier = "drone.task.remote.live.source" - sourceLabel.backgroundColor = UIColor.black.withAlphaComponent(0.65) - sourceLabel.textAlignment = .center - sourceLabel.layer.cornerRadius = 4 - sourceLabel.clipsToBounds = true - sourceLabel.isHidden = true + sourceBadge.axis = .horizontal + sourceBadge.alignment = .center + sourceBadge.spacing = 6 + sourceBadge.isHidden = true + sourceBadge.accessibilityIdentifier = "drone.task.remote.live.badge" + liveDot.backgroundColor = DroneDockStyle.success + liveDot.layer.cornerRadius = 3 + liveDot.accessibilityIdentifier = "drone.task.remote.live.dot" + sourceBadge.addArrangedSubview(liveDot) + sourceBadge.addArrangedSubview(sourceLabel) requestButton.tintColor = .white requestButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium) requestButton.backgroundColor = UIColor.black.withAlphaComponent(0.45) @@ -119,14 +170,21 @@ final class DroneDockTaskLiveView: UIView { labels.addArrangedSubview(titleLabel) labels.addArrangedSubview(messageLabel) addSubview(labels) - addSubview(sourceLabel) + addSubview(sourceBadge) addSubview(requestButton) } private func setupConstraints() { rtcView.snp.makeConstraints { $0.edges.equalToSuperview() } + coverView.snp.makeConstraints { $0.edges.equalToSuperview() } + coverShade.snp.makeConstraints { $0.edges.equalToSuperview() } + coverIcon.snp.makeConstraints { make in + make.centerX.equalToSuperview() + make.centerY.equalToSuperview().offset(-28) + make.size.equalTo(42) + } labels.snp.makeConstraints { make in - make.centerY.equalToSuperview().offset(-15) + labelsCenterY = make.centerY.equalToSuperview().offset(-15).constraint make.leading.trailing.equalToSuperview().inset(20) } requestButton.snp.makeConstraints { make in @@ -135,10 +193,10 @@ final class DroneDockTaskLiveView: UIView { make.width.greaterThanOrEqualTo(150) make.height.equalTo(36) } - sourceLabel.snp.makeConstraints { make in - make.top.leading.equalToSuperview().inset(10) - make.height.equalTo(24) - make.width.equalTo(200) + liveDot.snp.makeConstraints { $0.size.equalTo(6).priority(999) } + sourceBadge.snp.makeConstraints { make in + make.top.leading.equalToSuperview().inset(12) + make.trailing.lessThanOrEqualToSuperview().inset(12) } } diff --git a/suixinkan/UI/DroneDock/DroneDockTaskShootingView.swift b/suixinkan/UI/DroneDock/DroneDockTaskShootingView.swift new file mode 100644 index 0000000..f1c5fd8 --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneDockTaskShootingView.swift @@ -0,0 +1,191 @@ +import SnapKit +import UIKit + +/// 拍摄中状态区域:对齐体验网页的蓝色视频提示和禁用状态按钮,不执行任何操作。 +@MainActor +final class DroneDockTaskShootingView: UIView { + /// 当前内容采用的排版参考比例,不通过 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(image: UIImage(systemName: "video.fill")) + private let titleLabel = DroneDockStyle.label(size: 23, weight: .semibold, color: UIColor(hex: 0x101523)) + private let messageLabel = DroneDockStyle.label(size: 14, color: UIColor(hex: 0x6A79A0)) + private let indicatorButton = UIButton(type: .system) + private var presentation: DroneDockTaskPresentation? + 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 indicatorTop: Constraint? + private var indicatorHeight: 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) { + self.presentation = presentation + titleLabel.text = presentation.title + messageLabel.text = presentation.message + indicatorButton.isEnabled = false + setNeedsLayout() + } + + /// 仅可见状态面板提供通用访问标识,避免匹配到隐藏的标题或说明。 + func setIdentifiersActive(_ active: Bool) { + titleLabel.accessibilityIdentifier = active ? "drone.task.remote.statusTitle" : nil + messageLabel.accessibilityIdentifier = active ? "drone.task.remote.statusMessage" : nil + } + + /// 按可用高度调整内部排版,状态按钮始终保留至少 44 点高度。 + override func layoutSubviews() { + updateContentLayout() + super.layoutSubviews() + } + + private func setupUI() { + accessibilityIdentifier = "drone.task.remote.shooting" + backgroundColor = .white + addSubview(content) + content.addSubview(header) + content.addSubview(indicatorButton) + [iconBackground, titleLabel, messageLabel].forEach(header.addSubview) + iconBackground.addSubview(icon) + iconBackground.backgroundColor = UIColor(hex: 0xE2EDFF) + iconBackground.layer.cornerRadius = 20.5 + icon.contentMode = .scaleAspectFit + icon.tintColor = UIColor(hex: 0x0671FF) + titleLabel.accessibilityTraits = .header + titleLabel.numberOfLines = 1 + titleLabel.lineBreakMode = .byTruncatingTail + messageLabel.numberOfLines = 2 + messageLabel.lineBreakMode = .byTruncatingTail + + var configuration = UIButton.Configuration.filled() + configuration.title = "拍摄中" + configuration.image = UIImage(systemName: "camera") + configuration.imagePadding = 12 + configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 24, weight: .regular) + configuration.background.backgroundColor = UIColor(hex: 0xD7E7FF) + configuration.background.cornerRadius = 8 + configuration.cornerStyle = .fixed + configuration.baseForegroundColor = UIColor(hex: 0x4D91FF) + configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8) + indicatorButton.configuration = configuration + indicatorButton.isEnabled = false + indicatorButton.accessibilityIdentifier = "drone.task.remote.shootingIndicator" + indicatorButton.configurationUpdateHandler = { button in + button.configuration?.background.backgroundColor = UIColor(hex: 0xD7E7FF) + button.configuration?.baseForegroundColor = UIColor(hex: 0x4D91FF) + button.configuration?.imageColorTransformer = UIConfigurationColorTransformer { _ in UIColor(hex: 0x4D91FF) } + } + } + + 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(30).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 + } + indicatorButton.snp.makeConstraints { make in + indicatorTop = make.top.equalTo(header.snp.bottom).offset(16).constraint + make.leading.trailing.bottom.equalToSuperview() + indicatorHeight = make.height.equalTo(50).constraint + } + } + + private func updateContentLayout() { + guard let presentation, bounds.width > 0, bounds.height > 0 else { return } + 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 : 23 + let messageSize: CGFloat = compact ? 13 : 14 + let title = max(ceil(UIFont.systemFont(ofSize: titleSize, weight: .semibold).lineHeight), compact ? 0 : 30) + let textGap: CGFloat = extreme ? 3 : compact ? 4 : 6 + let actionGap: CGFloat = extreme ? 8 : compact ? 12 : 16 + let actionHeight: CGFloat = compact ? 44 : 50 + let inset: CGFloat = extreme ? 4 : 6 + let textWidth = max(1, bounds.width - 36 - diameter - iconGap) + let available = max(1, bounds.height - inset * 2) + let paragraph = NSMutableParagraphStyle() + paragraph.minimumLineHeight = messageSize * 1.6 + paragraph.maximumLineHeight = messageSize * 1.6 + paragraph.lineBreakMode = .byTruncatingTail + titleLabel.font = .systemFont(ofSize: titleSize, weight: .semibold) + let messageFont = UIFont.systemFont(ofSize: messageSize) + messageLabel.font = messageFont + let attributes: [NSAttributedString.Key: Any] = [ + .font: messageFont, + .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 + var lines = extreme || presentation.message.isEmpty ? 0 : 2 + var body = lines == 0 ? 0 : ceil(min(measured, paragraph.maximumLineHeight * CGFloat(lines))) + while max(diameter, title + (lines > 0 ? textGap + body : 0)) + actionGap + actionHeight > 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 + let header = max(diameter, title + (lines > 0 ? textGap + body : 0)) + let natural = title + textGap + ceil(messageSize * 3.2) + actionGap + actionHeight + effectiveScale = min(1, max(0.8, available / max(1, natural))) + headerHeight?.update(offset: header) + 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) + indicatorTop?.update(offset: actionGap) + indicatorHeight?.update(offset: actionHeight) + indicatorButton.configuration?.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in + var result = attributes + result.font = .systemFont(ofSize: compact ? 16 : 18, weight: .semibold) + result.foregroundColor = UIColor(hex: 0x4D91FF) + return result + } + } +} diff --git a/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift b/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift index f5ec512..5105d0e 100644 --- a/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift +++ b/suixinkan/UI/DroneDock/DroneDockTaskStatusView.swift @@ -6,7 +6,7 @@ import UIKit final class DroneDockTaskStatusView: UIView { /// 当前状态的主操作,由页面协调执行,不在组件中调用接口。 var onPrimaryAction: (() -> Void)? - /// 展开完整状态说明,由页面提供详情展示。 + /// 点击失败原因区域时展开完整说明,由页面协调展示。 var onDetails: (() -> Void)? /// 当前内容采用的字号和间距参考比例,始终介于 0.8 与 1。 private(set) var effectiveScale: CGFloat = 1 @@ -18,12 +18,15 @@ 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 detailsButton = UIButton(type: .system) private let failureView = DroneDockTaskFailureView() + private let completedView = DroneDockTaskCompletedView() + private let shootingView = DroneDockTaskShootingView() private var presentation: DroneDockTaskPresentation? + private var countdownSeconds: Int? private var contentTop: Constraint? private var contentLeading: Constraint? private var contentTrailing: Constraint? @@ -33,7 +36,7 @@ final class DroneDockTaskStatusView: UIView { private var messageHeight: Constraint? private var deviceHeight: Constraint? - /// 创建稳定的标题、说明、设备摘要与操作槽,所有状态复用同一组视图。 + /// 创建固定状态槽,完成、失败与进行中使用各自的内容布局。 override init(frame: CGRect) { super.init(frame: frame) setupUI() @@ -51,9 +54,30 @@ final class DroneDockTaskStatusView: UIView { /// 更新真实状态与动作许可;刷新期间保留内容,只暂时禁用主操作。 func apply(_ presentation: DroneDockTaskPresentation, isRefreshing: Bool = false) { self.presentation = presentation + updateCountdown(seconds: presentation.countdownSeconds) let isFailure = presentation.phase == .failed - contentStack.isHidden = isFailure + let isCompleted = [.postShootUploading, .completed].contains(presentation.phase) + let isShooting = presentation.phase == .shooting + contentStack.isHidden = isFailure || isCompleted || isShooting failureView.isHidden = !isFailure + completedView.isHidden = !isCompleted + shootingView.isHidden = !isShooting + completedView.setIdentifiersActive(isCompleted) + shootingView.setIdentifiersActive(isShooting) + titleLabel.accessibilityIdentifier = isCompleted || isShooting ? nil : "drone.task.remote.statusTitle" + messageLabel.accessibilityIdentifier = isCompleted || isShooting ? nil : "drone.task.remote.statusMessage" + if isShooting { + primaryButton.accessibilityIdentifier = nil + shootingView.apply(presentation) + setNeedsLayout() + return + } + if isCompleted { + primaryButton.accessibilityIdentifier = nil + completedView.apply(presentation, isRefreshing: isRefreshing) + setNeedsLayout() + return + } if isFailure { failureView.apply(presentation, isRefreshing: isRefreshing) setNeedsLayout() @@ -76,8 +100,33 @@ final class DroneDockTaskStatusView: UIView { setNeedsLayout() } + /// 只刷新已到达阶段的剩余秒数,不变更主操作、服务端阶段或执行任何回调。 + func updateCountdown(seconds: Int?) { + let value = presentation?.phase == .ready ? 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() } + } + /// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。 override func layoutSubviews() { + if presentation?.phase == .shooting { + super.layoutSubviews() + shootingView.layoutIfNeeded() + effectiveScale = shootingView.effectiveScale + usesCompactLayout = shootingView.usesCompactLayout + return + } + if let phase = presentation?.phase, [.postShootUploading, .completed].contains(phase) { + super.layoutSubviews() + completedView.layoutIfNeeded() + effectiveScale = 1 + usesCompactLayout = completedView.usesCompactLayout + return + } if presentation?.phase == .failed { super.layoutSubviews() failureView.layoutIfNeeded() @@ -91,6 +140,11 @@ final class DroneDockTaskStatusView: UIView { private func setupUI() { backgroundColor = .white + addSubview(shootingView) + shootingView.isHidden = true + addSubview(completedView) + completedView.isHidden = true + completedView.onViewMaterials = { [weak self] in self?.onPrimaryAction?() } addSubview(failureView) failureView.isHidden = true failureView.onDetails = { [weak self] in self?.onDetails?() } @@ -101,6 +155,7 @@ final class DroneDockTaskStatusView: UIView { addSubview(contentStack) contentStack.addArrangedSubview(titleRow) contentStack.addArrangedSubview(messageLabel) + contentStack.addArrangedSubview(countdownLabel) contentStack.addArrangedSubview(deviceLabel) contentStack.addArrangedSubview(actionRow) titleRow.addSubview(iconView) @@ -113,28 +168,25 @@ 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) - actionRow.addSubview(detailsButton) primaryButton.layer.cornerRadius = 9 primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold) primaryButton.titleLabel?.lineBreakMode = .byTruncatingTail primaryButton.setTitleColor(.white, for: .normal) primaryButton.setTitleColor(.white.withAlphaComponent(0.9), for: .disabled) primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside) - detailsButton.setTitle("详情", for: .normal) - detailsButton.setTitleColor(DroneDockStyle.primary, for: .normal) - detailsButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium) - detailsButton.backgroundColor = DroneDockStyle.background - detailsButton.layer.cornerRadius = 9 - detailsButton.accessibilityIdentifier = "drone.task.remote.details" - detailsButton.accessibilityLabel = "查看完整任务状态" - detailsButton.addTarget(self, action: #selector(detailsTapped), for: .touchUpInside) } private func setupConstraints() { + shootingView.snp.makeConstraints { $0.edges.equalToSuperview() } + completedView.snp.makeConstraints { $0.edges.equalToSuperview() } failureView.snp.makeConstraints { make in make.edges.equalToSuperview() } contentStack.snp.makeConstraints { make in contentTop = make.top.equalToSuperview().offset(12).constraint @@ -151,23 +203,20 @@ 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) } - detailsButton.snp.makeConstraints { make in - make.top.trailing.bottom.equalToSuperview() - make.width.equalTo(64) - } primaryButton.snp.makeConstraints { make in - make.top.leading.bottom.equalToSuperview() - make.trailing.equalTo(detailsButton.snp.leading).offset(-8) + make.edges.equalToSuperview() } } 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 ? 6 : 12 + let verticalInset: CGFloat = isExtreme ? (hasCountdown ? 4 : 6) : 12 let width = max(1, bounds.width - horizontalInset * 2) let availableHeight = max(1, bounds.height - verticalInset * 2) let message = DroneDockHomeMetric.usableText(presentation.message) @@ -179,18 +228,20 @@ 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 naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0)) * 10 - let naturalHeight = naturalTitle + naturalMessage + naturalDevice + 44 + naturalGaps + 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 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: max(17, 22 * fontScale), weight: .semibold) + titleLabel.font = .systemFont(ofSize: isExtreme && hasCountdown ? 17 : 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 ? 4 : max(4, 10 * effectiveScale) + let gap: CGFloat = isExtreme ? (hasCountdown ? 2 : 4) + : hasCountdown && usesCompactLayout ? 6 : max(4, 10 * effectiveScale) let titleGap: CGFloat = usesCompactLayout ? 8 : 10 * effectiveScale titleLabel.numberOfLines = usesCompactLayout ? 1 : 2 messageLabel.numberOfLines = usesCompactLayout ? 2 : 3 @@ -204,8 +255,8 @@ final class DroneDockTaskStatusView: UIView { width: width, lines: messageLineCount) let deviceTextHeight = deviceLabel.isHidden ? 0 : ceil(deviceLabel.font.lineHeight) var contentHeight: CGFloat { - titleHeight + bodyHeight + deviceTextHeight + 44 - + CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1)) * gap + titleHeight + bodyHeight + countdownTextHeight + deviceTextHeight + 44 + + CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1) + (hasCountdown ? 1 : 0)) * gap } while contentHeight > availableHeight && messageLineCount > 1 && !messageLabel.isHidden { messageLineCount -= 1 @@ -246,7 +297,8 @@ final class DroneDockTaskStatusView: UIView { case .navigating: ("paperplane.fill", DroneDockStyle.primary) case .ready: ("checkmark.circle.fill", DroneDockStyle.success) case .shooting: ("video.fill", DroneDockStyle.primary) - case .postShootUploading: ("icloud.and.arrow.up", DroneDockStyle.primary) + case .postShootUploading: ("checkmark.circle.fill", DroneDockStyle.success) + case .postShootUploadFailed: ("exclamationmark.circle.fill", DroneDockStyle.warning) case .paused: ("pause.circle.fill", DroneDockStyle.warning) case .returning: ("arrow.uturn.backward.circle.fill", DroneDockStyle.warning) case .completed: ("checkmark.circle.fill", DroneDockStyle.success) @@ -261,5 +313,4 @@ final class DroneDockTaskStatusView: UIView { onPrimaryAction?() } - @objc private func detailsTapped() { onDetails?() } } diff --git a/suixinkan/UI/DroneDock/DroneDockVolcEngineAdapter.swift b/suixinkan/UI/DroneDock/DroneDockVolcEngineAdapter.swift new file mode 100644 index 0000000..70d2073 --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneDockVolcEngineAdapter.swift @@ -0,0 +1,99 @@ +import UIKit +@preconcurrency import VolcEngineRTC + +/// 接收端最小能力,隔离测试无需初始化 SDK 或使用真实凭证。 +@MainActor +protocol DroneDockRTCReceivingEngine: AnyObject { + /// 创建一个独立接收房间并转交事件。 + func makeRoom(_ id: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingRoom)? + /// 按 SDK 提供的流 ID 绑定或解绑画布。 + func setVideoView(_ view: UIView?, streamID: String) -> Int + /// 销毁引擎及本地接收资源。 + func destroy() +} + +/// 单路只收视频的房间;不提供发布、采集或设备控制能力。 +@MainActor +protocol DroneDockRTCReceivingRoom: AnyObject { + /// 使用与当前用户匹配的凭证入房。 + func join(_ configuration: DroneDockVolcLiveConfiguration) -> Int + /// 同用户凭证续期。 + func updateToken(_ token: String) -> Int + /// 订阅或取消订阅远端视频。 + func subscribeVideo(_ streamID: String, subscribe: Bool) -> Int + /// 退出并销毁接收房间。 + func destroy() +} + +/// 火山 SDK 适配器;真实创建点再次拦截 Debug,测试不能通过注入绕开保护。 +@MainActor +final class DroneDockVolcEngineAdapter: DroneDockRTCReceivingEngine { + private let engine: ByteRTCEngine + private let delegate: DroneDockVolcDelegate + + private init(engine: ByteRTCEngine, delegate: DroneDockVolcDelegate) { + self.engine = engine + self.delegate = delegate + } + + /// 仅在构建策略允许真实图传时构造 SDK。 + static func make(appID: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)? { + guard !DeviceCommandDebugPolicy.blocksLiveRequests else { return nil } + let delegate = DroneDockVolcDelegate(emit: onEvent) + let config = ByteRTCEngineConfig() + config.appID = appID + guard let engine = ByteRTCEngine.createRTCEngine(config, delegate: delegate) else { return nil } + return DroneDockVolcEngineAdapter(engine: engine, delegate: delegate) + } + + /// 每个房间独立保留回调桥接,避免弱引用导致事件丢失。 + func makeRoom(_ id: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingRoom)? { + guard let room = engine.createRTCRoom(id) else { return nil } + return DroneDockVolcRoomAdapter(room: room, delegate: DroneDockVolcDelegate(emit: onEvent)) + } + + /// 画布只依赖发布回调的 streamID,不假定远端流索引为零。 + func setVideoView(_ view: UIView?, streamID: String) -> Int { + let canvas = ByteRTCVideoCanvas() + canvas.view = view + canvas.renderMode = .fit + return Int(engine.setRemoteVideoCanvas(streamID, withCanvas: canvas)) + } + + /// 房间由接收器先释放,再销毁共享引擎。 + func destroy() { + engine.delegate = nil + ByteRTCEngine.destroyRTCEngine() + } +} + +/// 将只收视频的房间配置封装在 SDK 边界,所有回调由接收器切回主线程。 +@MainActor +private final class DroneDockVolcRoomAdapter: DroneDockRTCReceivingRoom { + private let room: ByteRTCRoom + private let delegate: DroneDockVolcDelegate + + init(room: ByteRTCRoom, delegate: DroneDockVolcDelegate) { + self.room = room + self.delegate = delegate + room.setRTCRoomDelegate(delegate) + } + + func join(_ configuration: DroneDockVolcLiveConfiguration) -> Int { + let config = ByteRTCRoomConfig() + config.isPublishAudio = false + config.isPublishVideo = false + config.isAutoSubscribeAudio = false + config.isAutoSubscribeVideo = false + let user = ByteRTCUserInfo() + user.userId = configuration.userID + return Int(room.joinRoom(configuration.token, userInfo: user, userVisibility: false, roomConfig: config)) + } + + func updateToken(_ token: String) -> Int { Int(room.updateToken(token)) } + func subscribeVideo(_ streamID: String, subscribe: Bool) -> Int { Int(room.subscribeStreamVideo(streamID, subscribe: subscribe)) } + func destroy() { + room.setRTCRoomDelegate(nil) + room.destroy() + } +} diff --git a/suixinkan/UI/DroneDock/DroneDockVolcLivePlayer.swift b/suixinkan/UI/DroneDock/DroneDockVolcLivePlayer.swift index c9034d0..ef49c33 100644 --- a/suixinkan/UI/DroneDock/DroneDockVolcLivePlayer.swift +++ b/suixinkan/UI/DroneDock/DroneDockVolcLivePlayer.swift @@ -11,11 +11,37 @@ protocol DroneDockLivePlaying: AnyObject { func stop() } -/// 一个 RTC 引擎接收两个房间,机巢先接入,无人机有帧后覆盖,停流后恢复机巢。 +/// 真实 SDK 入口始终执行编译期禁飞保护,没有运行时放行参数。 @MainActor final class DroneDockVolcLivePlayer: DroneDockLivePlaying { - private var engine: ByteRTCEngine? - private var delegate: DroneDockVolcDelegate? + private let receiver = DroneDockLiveReceiver(makeEngine: DroneDockVolcEngineAdapter.make) + + /// Release 通过接收器播放;Debug 在创建 SDK 之前拒绝连接。 + func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView, + onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) { + guard !DeviceCommandDebugPolicy.blocksLiveRequests else { + stop(); onEvent(.failed(DeviceCommandDebugPolicy.blockedMessage)); return + } + receiver.start(configurations, in: view, onEvent: onEvent) + } + + /// 释放本机播放资源,不发送任何设备控制请求。 + func stop() { receiver.stop() } +} + +/// 一个 RTC 引擎接收两个房间,机巢先接入,无人机有帧后覆盖,停流后恢复机巢。 +@MainActor +final class DroneDockLiveReceiver: DroneDockLivePlaying { + private var engine: (any DroneDockRTCReceivingEngine)? + private let makeEngine: (String, @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)? + private let firstFrameDelay: @Sendable () async throws -> Void + + /// 生产环境注入带 Debug 保护的适配器;测试只注入内存接收端。 + init(makeEngine: @escaping (String, @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)?, + firstFrameDelay: @escaping @Sendable () async throws -> Void = { try await Task.sleep(for: .seconds(20)) }) { + self.makeEngine = makeEngine + self.firstFrameDelay = firstFrameDelay + } private weak var container: UIView? private var sources: [String: DroneDockVolcSource] = [:] private var configurations: [DroneDockVolcLiveConfiguration] = [] @@ -29,9 +55,6 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying { /// 加入只收视频的房间;同一来源只更新 Token,避免后台重查导致画面闪断。 func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView, onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) { - guard !DeviceCommandDebugPolicy.blocksLiveRequests else { - stop(); onEvent(.failed(DeviceCommandDebugPolicy.blockedMessage)); return - } guard let first = configurations.first else { stop(); return } if container !== view || self.configurations.first?.appID != first.appID { stop() } self.onEvent = onEvent @@ -39,16 +62,12 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying { self.configurations = configurations if engine == nil { let generation = generation - let delegate = DroneDockVolcDelegate { [weak self] event in + guard let engine = makeEngine(first.appID, { [weak self] event in Task { @MainActor [weak self] in guard let self, self.generation == generation else { return } self.receive(event) } - } - self.delegate = delegate - let config = ByteRTCEngineConfig() - config.appID = first.appID - guard let engine = ByteRTCEngine.createRTCEngine(config, delegate: delegate) else { + }) else { stop(); onEvent(.failed("图传播放器初始化失败")); return } self.engine = engine @@ -74,10 +93,8 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying { generation = UUID() onEvent = nil for role in Array(sources.keys) { removeSource(role) } - engine?.delegate = nil - if engine != nil { ByteRTCEngine.destroyRTCEngine() } + engine?.destroy() engine = nil - delegate = nil container = nil configurations = [] selection = DroneDockLiveSourceSelection() @@ -105,7 +122,15 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying { scheduleExpiry(source) return } - guard let container, let room = engine?.createRTCRoom(configuration.roomID) else { + guard let container else { return } + let generation = generation + let sourceID = UUID() + guard let room = engine?.makeRoom(configuration.roomID, onEvent: { [weak self] event in + Task { @MainActor [weak self] in + guard let self, self.generation == generation, self.sources[role]?.id == sourceID else { return } + self.receive(event) + } + }) else { failedRoles.insert(role) if role == "airport" { allowsDroneConnection = true } return @@ -115,25 +140,9 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying { view.backgroundColor = .black view.isHidden = true container.addSubview(view) - let generation = generation - let sourceID = UUID() - let delegate = DroneDockVolcDelegate { [weak self] event in - Task { @MainActor [weak self] in - guard let self, self.generation == generation, self.sources[role]?.id == sourceID else { return } - self.receive(event) - } - } - let source = DroneDockVolcSource(id: sourceID, configuration: configuration, room: room, view: view, delegate: delegate) + let source = DroneDockVolcSource(id: sourceID, configuration: configuration, room: room, view: view) sources[role] = source - room.setRTCRoomDelegate(delegate) - let roomConfig = ByteRTCRoomConfig() - roomConfig.isPublishAudio = false - roomConfig.isPublishVideo = false - roomConfig.isAutoSubscribeAudio = false - roomConfig.isAutoSubscribeVideo = false - let user = ByteRTCUserInfo() - user.userId = configuration.userID - let result = room.joinRoom(configuration.token, userInfo: user, userVisibility: false, roomConfig: roomConfig) + let result = room.join(configuration) guard result == 0 else { removeSource(role) failedRoles.insert(role) @@ -141,10 +150,12 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying { return } // 机巢无首帧时不能无限等待,仍尝试无人机;已连房间继续等待发布事件。 + let delay = firstFrameDelay source.timeoutTask = Task { @MainActor [weak self] in - try? await Task.sleep(for: .seconds(20)) + do { try await delay() } catch { return } guard !Task.isCancelled, let self, self.generation == generation, self.sources[role]?.id == sourceID else { return } - self.sourceFailed(role) + // 首帧等待超时只开放另一路;不能销毁仍在等待发布的房间或取消补取参数。 + self.markReady(false, source: source) } scheduleExpiry(source) } @@ -163,6 +174,11 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying { guard !Task.isCancelled, let self, self.generation == generation, self.sources[role]?.id == sourceID else { return } self.removeSource(role) self.displaySelectedSource() + if self.sources.isEmpty { + let callback = self.onEvent + self.stop() + callback?(.expired) + } } } @@ -171,32 +187,28 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying { guard let source = sources.removeValue(forKey: role) else { return } source.timeoutTask?.cancel() source.expiryTask?.cancel() - if let streamID = source.streamID { engine?.setRemoteVideoCanvas(streamID, withCanvas: nil) } - source.room.setRTCRoomDelegate(nil) + if let streamID = source.streamID { _ = engine?.setVideoView(nil, streamID: streamID) } source.room.destroy() source.view.removeFromSuperview() } private func receive(_ event: DroneDockVolcEvent) { switch event { - case .published(let id, let roomID, let index, let published): - guard index == 0, let source = source(in: roomID) else { return } + case .published(let id, let roomID, let published): + guard !id.isEmpty, let source = source(in: roomID) else { return } if !published { guard source.streamID == id else { return } - engine?.setRemoteVideoCanvas(id, withCanvas: nil) - source.room.subscribeStreamVideo(id, subscribe: false) + _ = engine?.setVideoView(nil, streamID: id) + _ = source.room.subscribeVideo(id, subscribe: false) source.streamID = nil markReady(false, source: source) return } guard source.streamID == nil else { return } source.streamID = id - let canvas = ByteRTCVideoCanvas() - canvas.view = source.view - canvas.renderMode = .fit - let render = engine?.setRemoteVideoCanvas(id, withCanvas: canvas) - let subscribe = source.room.subscribeStreamVideo(id, subscribe: true) - if render != 0 || subscribe != 0 { sourceFailed(source.configuration.role) } + let render = engine?.setVideoView(source.view, streamID: id) + let subscribe = source.room.subscribeVideo(id, subscribe: true) + if render != 0 || subscribe != 0 { sourceFailed(source.configuration.role, message: "图传订阅失败(\(render ?? -1)/\(subscribe)),请重试") } case .frame(let id, let roomID): guard let source = source(in: roomID), source.streamID == id else { return } markReady(true, source: source) @@ -207,9 +219,9 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying { case .stopped, .frozen, .failed: markReady(false, source: source) default: break } - case .roomFailed(let roomID): + case .roomFailed(let roomID, let code): guard let source = source(in: roomID) else { return } - sourceFailed(source.configuration.role) + sourceFailed(source.configuration.role, message: "图传入房失败(\(code)),请重试") case .connectionLost: for source in sources.values { selection.setReady(false, role: source.configuration.role) } displaySelectedSource() @@ -237,7 +249,7 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying { } } - private func sourceFailed(_ role: String) { + private func sourceFailed(_ role: String, message: String) { failedRoles.insert(role) selection.setReady(false, role: role) if role == "airport" { allowsDroneConnection = true; connectDroneIfAllowed() } @@ -245,7 +257,7 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying { if selection.selectedRole == nil, Set(configurations.map(\.role)).isSubset(of: failedRoles) { let callback = onEvent stop() - callback?(.failed("暂未收到可用的图传画面,请重试")) + callback?(.failed(message)) } } @@ -264,39 +276,38 @@ final class DroneDockVolcLivePlayer: DroneDockLivePlaying { private final class DroneDockVolcSource { let id: UUID var configuration: DroneDockVolcLiveConfiguration - let room: ByteRTCRoom + let room: any DroneDockRTCReceivingRoom let view: UIView - let delegate: DroneDockVolcDelegate var streamID: String? var timeoutTask: Task? var expiryTask: Task? - init(id: UUID, configuration: DroneDockVolcLiveConfiguration, room: ByteRTCRoom, view: UIView, delegate: DroneDockVolcDelegate) { - self.id = id; self.configuration = configuration; self.room = room; self.view = view; self.delegate = delegate + init(id: UUID, configuration: DroneDockVolcLiveConfiguration, room: any DroneDockRTCReceivingRoom, view: UIView) { + self.id = id; self.configuration = configuration; self.room = room; self.view = view } } /// SDK 工作线程只转交值类型事件;事件带房间和流身份以隔离两路回调。 -private enum DroneDockVolcEvent: Sendable { - case published(String, String, Int, Bool) +enum DroneDockVolcEvent: Sendable { + case published(String, String, Bool) case frame(String, String) case videoState(String, String, ByteRTCRemoteVideoState) - case roomFailed(String) + case roomFailed(String, Int) case connectionLost case failed(Int) } /// SDK 回调桥接,不采集音视频,不处理设备控制消息。 -private final class DroneDockVolcDelegate: NSObject, ByteRTCEngineDelegate, ByteRTCRoomDelegate { +final class DroneDockVolcDelegate: NSObject, ByteRTCEngineDelegate, ByteRTCRoomDelegate { private let emit: @Sendable (DroneDockVolcEvent) -> Void init(emit: @escaping @Sendable (DroneDockVolcEvent) -> Void) { self.emit = emit } func rtcRoom(_ rtcRoom: ByteRTCRoom, onUserPublishStreamVideo streamId: String, info: ByteRTCStreamInfo, isPublish: Bool) { - emit(.published(streamId, info.roomId, info.streamIndex, isPublish)) + emit(.published(streamId, info.roomId, isPublish)) } func rtcRoom(_ rtcRoom: ByteRTCRoom, onRoomStateChanged roomId: String, withUid uid: String, state: Int, extraInfo: String) { - if state != 0 { emit(.roomFailed(roomId)) } + if state != 0 { emit(.roomFailed(roomId, state)) } } func rtcEngine(_ engine: ByteRTCEngine, onFirstRemoteVideoFrameDecoded streamId: String, diff --git a/suixinkanTests/DeviceCommandDebugPolicyTests.swift b/suixinkanTests/DeviceCommandDebugPolicyTests.swift index 231d1dd..179baa5 100644 --- a/suixinkanTests/DeviceCommandDebugPolicyTests.swift +++ b/suixinkanTests/DeviceCommandDebugPolicyTests.swift @@ -5,6 +5,25 @@ import XCTest /// 验证禁飞调试在进入传输层之前拦截真实操作,所有探针本身也不联网。 @MainActor final class DeviceCommandDebugPolicyTests: XCTestCase { + /// 不联网核对编译策略:Release 保留准备页电量参数,Debug 强制缓存;不开放任务实时采集。 + func testPreparationBatteryPolicyIsScopedToBuildAndEndpoint() throws { + for (path, key) in [("plane-status", "live_battery"), ("shooting", "live_battery"), ("status", "live_metrics")] { + for value in ["0", "1"] { + var request = URLRequest(url: try XCTUnwrap(URL(string: + "https://policy.invalid/api/app/airport/\(path)?scenic_id=128&\(key)=\(value)"))) + request.httpMethod = "GET" + let prepared = try DeviceCommandDebugPolicy.prepare(request, isLocalSimulation: false) + let items = try XCTUnwrap(URLComponents(url: XCTUnwrap(prepared.url), resolvingAgainstBaseURL: false)?.queryItems) + #if DEBUG + let expected = "0" + #else + let expected = path == "plane-status" ? value : "0" + #endif + XCTAssertEqual(items.first { $0.name == key }?.value, expected) + XCTAssertEqual(items.first { $0.name == "scenic_id" }?.value, "128") + } + } + } /// 用户授权 Release 真机操作,当前模拟器 Debug 测试仍必须禁止真实飞控。 func testDebugKeepsFlightRestriction() { XCTAssertTrue(DeviceCommandDebugPolicy.blocksFlightRequests) diff --git a/suixinkanTests/DroneDockArrivalCountdownTests.swift b/suixinkanTests/DroneDockArrivalCountdownTests.swift new file mode 100644 index 0000000..7f0a3b7 --- /dev/null +++ b/suixinkanTests/DroneDockArrivalCountdownTests.swift @@ -0,0 +1,290 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 验证 App 自行维护的到达倒计时只影响显示,所有时钟和接口均由隔离替身提供。 +@MainActor +final class DroneDockArrivalCountdownTests: XCTestCase { + /// 只有首次可信到达才开始 30 秒;零点之前向上取整,永不显示负数。 + func testReadyStartsThirtySecondsAndRoundsRemainingTimeUp() async throws { + let fixture = try makeFixture() + XCTAssertNil(fixture.model.countdownRemainingSeconds) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 30) + XCTAssertEqual(fixture.model.presentation.countdownSeconds, 30) + fixture.clock.advance(by: .milliseconds(1)) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 30) + fixture.clock.advance(by: .milliseconds(999)) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 29) + fixture.clock.advance(by: .milliseconds(28_500)) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 1) + fixture.clock.advance(by: .milliseconds(500)) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 0) + fixture.clock.advance(by: .seconds(100)) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 0) + } + + /// 倒数到零既不读取接口也不调用开拍,页面仍等后端返回拍摄中。 + func testExpiryDoesNotStartShootingOrIssueAdditionalRequests() async throws { + let fixture = try makeFixture() + await fixture.model.refresh() + XCTAssertTrue(fixture.model.canStartShooting, "测试显式注入开拍替身,验证到零也不会调用它") + fixture.clock.advance(by: .seconds(35)) + for _ in 0..<5 { + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 0) + XCTAssertEqual(fixture.model.presentation.countdownSeconds, 0) + XCTAssertEqual(fixture.model.presentation.phase, .ready) + XCTAssertFalse(fixture.model.hasSubmittedStart) + } + XCTAssertEqual(fixture.service.requests.count, 1) + XCTAssertEqual(fixture.actions.startCount, 0) + let shooting = try snapshot(phase: "shooting", version: 2) + XCTAssertEqual(fixture.model.applyTaskSnapshot(shooting), .applied) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + XCTAssertNil(fixture.model.countdownRemainingSeconds) + XCTAssertNil(fixture.model.presentation.countdownSeconds) + XCTAssertEqual(fixture.actions.startCount, 0) + XCTAssertEqual(fixture.service.requests.count, 1) + } + + /// 后端提前开拍时立即按快照切换,不等待 App 的显示倒数结束。 + func testBackendShootingSnapshotEndsCountdownBeforeZero() async throws { + let fixture = try makeFixture() + await fixture.model.refresh() + fixture.clock.advance(by: .seconds(7)) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 23) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try snapshot(phase: "shooting", version: 2)), .applied) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + XCTAssertNil(fixture.model.presentation.countdownSeconds) + fixture.clock.advance(by: .seconds(40)) + XCTAssertEqual(fixture.model.presentation.phase, .shooting) + XCTAssertNil(fixture.model.countdownRemainingSeconds) + XCTAssertEqual(fixture.actions.startCount, 0) + XCTAssertEqual(fixture.service.requests.count, 1) + } + + /// HTTP 刷新、重复版本和新版本到达包都不重新从 30 秒开始。 + func testRepeatedHTTPAndWebSocketReadySnapshotsDoNotResetDeadline() async throws { + let fixture = try makeFixture() + await fixture.model.refresh() + fixture.clock.advance(by: .seconds(12)) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 18) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try snapshot()), .duplicate) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 18) + guard case .snapshot(let socketValue) = try DroneDockShootingSocketMessage.decode( + RealtimeTestData.push(payload(version: 2))) else { return XCTFail("隔离完整推送应可解析") } + XCTAssertEqual(fixture.model.applyTaskSnapshot(socketValue), .applied) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 18) + fixture.clock.advance(by: .seconds(7)) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 11) + XCTAssertEqual(fixture.service.requests.count, 2) + XCTAssertTrue(fixture.service.requests.allSatisfy { !$0.liveBattery }) + XCTAssertEqual(fixture.actions.startCount, 0) + } + + /// 新执行批次建立新期限,过期版本和旧批次不能重置或清除当前倒计时。 + func testNewExecutionBatchStartsFreshCountdownAndRejectsOldSnapshots() async throws { + let fixture = try makeFixture() + await fixture.model.refresh() + fixture.clock.advance(by: .seconds(20)) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 10) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try snapshot(batch: 101, version: 1)), .applied) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 30) + fixture.clock.advance(by: .seconds(4)) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try snapshot(phase: "shooting", batch: 100, version: 999)), .outdated) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 26) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try snapshot(phase: "shooting", batch: 101, version: 0)), .outdated) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 26) + XCTAssertEqual(fixture.model.presentation.phase, .ready) + } + + /// HTTP 或 WS 首次进入到达状态都使用接收时的 App 时钟,不要求后端倒计时字段。 + func testHTTPAndWebSocketFirstArrivalHaveEquivalentCountdowns() async throws { + let http = try makeFixture() + let socket = try makeFixture() + await http.model.refresh() + guard case .snapshot(let value) = try DroneDockShootingSocketMessage.decode( + RealtimeTestData.push(payload())) else { return XCTFail("隔离完整推送应可解析") } + XCTAssertEqual(socket.model.applyTaskSnapshot(value), .applied) + XCTAssertEqual(http.model.countdownRemainingSeconds, 30) + XCTAssertEqual(socket.model.countdownRemainingSeconds, 30) + http.clock.advance(by: .seconds(9)) + socket.clock.advance(by: .seconds(9)) + XCTAssertEqual(http.model.presentation.countdownSeconds, socket.model.presentation.countdownSeconds) + XCTAssertTrue(socket.service.requests.isEmpty) + XCTAssertEqual(http.actions.startCount + socket.actions.startCount, 0) + } + + /// 后台或离页只停止 UI 刷新;保留快照时本地期限继续流逝,回到同批次不重置。 + func testPreservedSnapshotCountsElapsedForegroundGapWithoutResetting() async throws { + let fixture = try makeFixture() + await fixture.model.refresh() + fixture.clock.advance(by: .seconds(8)) + fixture.model.invalidate(preservingSnapshot: true) + fixture.clock.advance(by: .seconds(15)) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 7) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 7) + fixture.model.invalidate(preservingSnapshot: true) + fixture.clock.advance(by: .seconds(40)) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 0) + XCTAssertEqual(fixture.model.presentation.phase, .ready) + XCTAssertEqual(fixture.actions.startCount, 0) + } + + /// 离开到达阶段隐藏数字,同批次再次返回到达不重建已开始的期限。 + func testLeavingReadyHidesCountdownWithoutResettingSameExecution() async throws { + 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) + XCTAssertNil(fixture.model.countdownRemainingSeconds) + XCTAssertNil(fixture.model.presentation.countdownSeconds) + fixture.clock.advance(by: .seconds(5)) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try snapshot(version: 3)), .applied) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 19) + for (version, phase) in [(4, "shooting"), (5, "post_shoot_uploading"), (6, "post_shoot_upload_failed"), (7, "blocked")] { + XCTAssertEqual(fixture.model.applyTaskSnapshot(try snapshot(phase: phase, version: version)), .applied) + XCTAssertNil(fixture.model.countdownRemainingSeconds, phase) + XCTAssertNil(fixture.model.presentation.countdownSeconds, phase) + } + } + + /// 缺少执行批次的旧响应仍可计时,但重复刷新不能反复延长显示。 + func testLegacySnapshotsWithoutBatchShareOneLocalDeadline() async throws { + let fixture = try makeFixture(response: snapshot(batch: nil, version: nil)) + await fixture.model.refresh() + fixture.clock.advance(by: .seconds(10)) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 20) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try snapshot(batch: nil, version: nil)), .applied) + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 20) + } + + /// 未允许开拍的“到达”文案、未知阶段与错误任务身份不能创建倒计时。 + func testBlockedUnknownAndMismatchedSnapshotsDoNotStartCountdown() 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.applyTaskSnapshot(try snapshot(phase: "future_phase", version: 3)), .applied) + XCTAssertNil(fixture.model.countdownRemainingSeconds) + var wrong = payload(version: 4) + wrong["order_flight_task_id"] = 999 + XCTAssertEqual(fixture.model.applyTaskSnapshot(try DroneDockShootingTaskTestData.decode(wrong)), .invalid) + XCTAssertNil(fixture.model.countdownRemainingSeconds) + XCTAssertEqual(fixture.actions.startCount, 0) + } + + /// 明确清除快照或身份变化会清理本地计时;不能把旧任务秒数带到失效页面。 + func testClearSnapshotAndIdentityChangeRemoveCountdown() async throws { + let fixture = try makeFixture() + await fixture.model.refresh() + fixture.clock.advance(by: .seconds(12)) + fixture.model.invalidate() + XCTAssertNil(fixture.model.countdownRemainingSeconds) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.countdownRemainingSeconds, 30) + fixture.scope.value = DroneDockShootingTaskTestData.context(scenicID: 129) + fixture.model.invalidate(preservingSnapshot: true) + XCTAssertNil(fixture.model.countdownRemainingSeconds) + XCTAssertNil(fixture.model.presentation.countdownSeconds) + XCTAssertFalse(fixture.model.canContinuePolling) + } + + /// 权限终止立即隐藏旧倒计时,即使为只读展示仍保留旧任务快照。 + func testPermissionDenialHidesCountdownAndRejectsLaterReadySnapshot() async throws { + let fixture = try makeFixture() + await fixture.model.refresh() + fixture.model.stopReading(message: "本地模拟:无权限") + XCTAssertNotNil(fixture.model.response) + XCTAssertNil(fixture.model.countdownRemainingSeconds) + XCTAssertNil(fixture.model.presentation.countdownSeconds) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try snapshot(version: 2)), .invalid) + XCTAssertEqual(fixture.actions.startCount, 0) + } + + private func payload(phase: String = "arrived_pending_start", batch: Int? = 100, version: Int? = 1) -> [String: Any] { + var value = DroneDockShootingTaskTestData.payload() + value["order_flight_task_id"] = 501 + value["task"] = ["id": 501, "status": 20, "wayline_status": 20] + 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 version { value["state_version"] = version } + value["snapshot_kind"] = "full" + return value + } + + private func snapshot(phase: String = "arrived_pending_start", batch: Int? = 100, version: Int? = 1) throws -> DroneDockShootingResponse { + try DroneDockShootingTaskTestData.decode(payload(phase: phase, batch: batch, version: version)) + } + + private func makeFixture(response: DroneDockShootingResponse? = nil) throws -> ( + model: DroneDockShootingTaskViewModel, service: DroneDockShootingTaskTestService, + clock: DroneDockCountdownTestClock, actions: ArrivalCountdownStartProbe, scope: ArrivalCountdownScope + ) { + let context = DroneDockShootingTaskTestData.context() + let scope = ArrivalCountdownScope(value: context) + let clock = DroneDockCountdownTestClock() + let service = DroneDockShootingTaskTestService(result: .success(try response ?? snapshot())) + let actions = ArrivalCountdownStartProbe() + let model = DroneDockShootingTaskViewModel(context: context, taskID: 501, + order: try DroneDockShootingTaskTestData.order(), service: service, startService: actions, + countdownNow: { clock.now() }, currentContext: { scope.value }) + return (model, service, clock, actions, scope) + } +} + +/// 以锁保护可推进的单调时钟,测试不依赖真实 30 秒等待或系统墙钟调整。 +final class DroneDockCountdownTestClock: @unchecked Sendable { + private let lock = NSLock() + private var instant = ContinuousClock.now + + /// 从当前单调时间建立可推进测试时钟。 + init() {} + + /// 读取当前模拟时间,供 nonisolated ViewModel 的 Sendable 闭包使用。 + func now() -> ContinuousClock.Instant { + lock.lock() + defer { lock.unlock() } + return instant + } + + /// 手动推进经过时间,不调度计时器或任何网络请求。 + func advance(by duration: Duration) { + lock.lock() + defer { lock.unlock() } + instant = instant.advanced(by: duration) + } + + /// 供页面生命周期测试按秒推进同一时钟。 + func advance(seconds: Double) { advance(by: .seconds(seconds)) } +} + +/// 可切换身份的隔离会话,仅用于检查旧任务倒计时清理。 +@MainActor +private final class ArrivalCountdownScope { + var value: DroneDockHomeContext + + /// 建立固定匿名测试会话。 + init(value: DroneDockHomeContext) { self.value = value } +} + +/// 只统计手动开拍服务调用,不连接网络;倒数到零时必须仍为零次。 +@MainActor +private final class ArrivalCountdownStartProbe: DroneDockStartShooting { + private(set) var startCount = 0 + + /// 任何误触发都会留下次数;返回本地错误避免伪造后端成功。 + func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse { + startCount += 1 + throw APIError.networkFailed("本地模拟,未发送真实开拍") + } +} diff --git a/suixinkanTests/DroneDockArrivalCountdownViewTests.swift b/suixinkanTests/DroneDockArrivalCountdownViewTests.swift new file mode 100644 index 0000000..68c3677 --- /dev/null +++ b/suixinkanTests/DroneDockArrivalCountdownViewTests.swift @@ -0,0 +1,207 @@ +import UIKit +import XCTest +@testable import suixinkan + +/// 使用可推进时钟和隔离读取验证逐秒显示、生命周期与后端状态切换,不连接真实设备。 +@MainActor +final class DroneDockArrivalCountdownViewTests: XCTestCase { + /// 每秒只更新显示,到零不额外读取或开拍;后端明确拍摄中后才切换阶段。 + func testCountdownOnlyUpdatesLabelAndWaitsForBackendShooting() 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) + XCTAssertTrue(action.isEnabled) + let initialFrame = action.convert(action.bounds, to: fixture.controller.view) + try await capture(fixture.window, action: action, name: "App本地到达倒计时30秒(隔离替身)") + fixture.clock.advance(seconds: 1) + fixture.pulse.fire() + try await settle(fixture.window) { label.text == "自动开拍倒计时:29 秒" && fixture.pulse.pendingCount == 1 } + 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 } + 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秒仍等待后端(隔离替身)") + 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) + XCTAssertNil(fixture.model.countdownRemainingSeconds) + XCTAssertEqual(fixture.service.requests.count, 2) + XCTAssertEqual(fixture.start.count, 0) + XCTAssertEqual(fixture.pulse.pendingCount, 0) + } + + /// 手动开拍与本地数字显示并行,30秒、倒数中和0秒均可点,连点仍只提交一次。 + func testManualStartRemainsTappableThroughoutCountdown() async throws { + for elapsed in [0.0, 12.0, 30.0] { + let fixture = try makeFixture() + defer { fixture.close() } + try await settle(fixture.window) { fixture.pulse.pendingCount == 1 } + let label = try countdownLabel(in: fixture.controller.view) + if elapsed > 0 { + fixture.clock.advance(seconds: elapsed) + fixture.pulse.fire() + try await settle(fixture.window) { label.text == "自动开拍倒计时:\(30 - Int(elapsed)) 秒" } + } + let action = try XCTUnwrap(find(in: fixture.controller.view, id: "drone.task.remote.primary") as? UIButton) + XCTAssertEqual(action.title(for: .normal), "开始拍摄") + XCTAssertTrue(action.isEnabled) + XCTAssertEqual(fixture.start.count, 0) + action.sendActions(for: .touchUpInside) + action.sendActions(for: .touchUpInside) + try await settle(fixture.window) { fixture.start.count == 1 && !fixture.model.isStartingShooting } + XCTAssertTrue(fixture.model.startOutcomeUnknown, "隔离替身返回超时类错误,不能自动再次开拍") + XCTAssertEqual(fixture.service.requests.count, 1, "本地倒计时与未知开拍结果不额外触发读取") + XCTAssertEqual(fixture.model.presentation.phase, .ready, "受理或提交本身不替代后端拍摄中状态") + } + } + + /// 后台与离页取消定时刷新;同任务批次返回后按已经过去的时间继续,不再从30开始。 + func testBackgroundAndPageReentryPreserveElapsedTimeAndCancelTicks() 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) + 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 } + 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 秒" } + XCTAssertEqual(fixture.pulse.pendingCount, 0) + XCTAssertEqual(fixture.start.count, 0) + XCTAssertEqual(fixture.model.presentation.phase, .ready) + } + + private func makeFixture() throws -> CountdownPageFixture { + let context = DroneDockShootingTaskTestData.context() + let clock = DroneDockCountdownTestClock() + let service = DroneDockShootingTaskTestService(result: .success(try snapshot(phase: "arrived_pending_start", version: 1))) + let start = CountdownPageStartProbe() + let model = try DroneDockShootingTaskViewModel(context: context, taskID: 501, + order: DroneDockShootingTaskTestData.order(), service: service, startService: start, + countdownNow: { clock.now() }, currentContext: { context }) + let pulse = CountdownPagePulse() + let controller = DroneDockShootingTaskViewController(viewModel: model, + shootingPollDelay: { _ in try await Task.sleep(for: .seconds(3600)) }, countdownDelay: { try await pulse.wait() }) + let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first + let previous = scene?.windows.first { $0.isKeyWindow } + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + window.rootViewController = UINavigationController(rootViewController: controller) + window.makeKeyAndVisible() + return CountdownPageFixture(controller: controller, window: window, previous: previous, model: model, + service: service, clock: clock, pulse: pulse, start: start) + } + + private func snapshot(phase: String, version: Int) throws -> DroneDockShootingResponse { + 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", + "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 + } + + private func settle(_ window: UIWindow, until predicate: () -> Bool) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(3)) + while ContinuousClock.now < deadline { + window.layoutIfNeeded() + if predicate() { return } + try await Task.sleep(for: .milliseconds(10)) + } + XCTFail("本地倒计时页面未达到预期状态") + throw NSError(domain: "CountdownPage", code: 1) + } + + private func capture(_ window: UIWindow, action: UIButton, name: String) async throws { + try await Task.sleep(for: .milliseconds(300)) + window.layoutIfNeeded() + XCTAssertEqual(action.titleLabel?.text, "开始拍摄", "数字变化后按钮实际文字仍保持手动开拍") + let attachment = XCTAttachment(image: UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + }) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } +} + +/// 持有单页隔离依赖并恢复测试前的窗口,避免通知或计时任务影响其他用例。 +@MainActor +private struct CountdownPageFixture { + let controller: DroneDockShootingTaskViewController + let window: UIWindow + let previous: UIWindow? + let model: DroneDockShootingTaskViewModel + let service: DroneDockShootingTaskTestService + let clock: DroneDockCountdownTestClock + let pulse: CountdownPagePulse + let start: CountdownPageStartProbe + + func close() { + controller.viewWillDisappear(false) + window.isHidden = true + window.rootViewController = nil + previous?.makeKeyAndVisible() + } +} + +/// 由测试主动唤醒的本地逐秒刷新等待器,取消时立即释放 continuation。 +@MainActor +private final class CountdownPagePulse { + private var pending: [(UUID, CheckedContinuation)] = [] + var pendingCount: Int { pending.count } + + func wait() async throws { + let id = UUID() + try Task.checkCancellation() + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { pending.append((id, $0)) } + } onCancel: { + Task { @MainActor in + guard let index = self.pending.firstIndex(where: { $0.0 == id }) else { return } + self.pending.remove(at: index).1.resume(throwing: CancellationError()) + } + } + } + + func fire() { + guard !pending.isEmpty else { return } + pending.removeFirst().1.resume() + } +} + +/// 记录意外开拍调用,只返回本地错误,不创建网络传输。 +@MainActor +private final class CountdownPageStartProbe: DroneDockStartShooting { + private(set) var count = 0 + + func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse { + count += 1 + throw APIError.networkFailed("本地模拟:不应自动开拍") + } +} diff --git a/suixinkanTests/DroneDockLiveReceiverTests.swift b/suixinkanTests/DroneDockLiveReceiverTests.swift new file mode 100644 index 0000000..a392935 --- /dev/null +++ b/suixinkanTests/DroneDockLiveReceiverTests.swift @@ -0,0 +1,124 @@ +import UIKit +import XCTest +@preconcurrency import VolcEngineRTC +@testable import suixinkan + +/// 直接驱动生产接收器的房间与首帧流程,SDK 边界全部使用无网络替身。 +@MainActor +final class DroneDockLiveReceiverTests: XCTestCase { + /// 首帧晚于原 20 秒窗口时仍可订阅;超时开放第二路,不销毁第一路。 + func testLatePublicationAfterTimeoutStillPlaysAndFallsBack() async throws { + let engine = ReceiverEngineProbe() + let receiver = DroneDockLiveReceiver(makeEngine: { _, _ in engine }, firstFrameDelay: { try await Task.sleep(for: .milliseconds(10)) }) + let view = UIView(frame: CGRect(x: 0, y: 0, width: 390, height: 220)) + var events: [DroneDockLivePlaybackEvent] = [] + receiver.start([configuration("airport"), configuration("drone")], in: view) { events.append($0) } + defer { receiver.stop() } + XCTAssertEqual(engine.rooms.count, 1) + try await Task.sleep(for: .milliseconds(80)) + XCTAssertEqual(engine.rooms.count, 2) + XCTAssertEqual(engine.destroyCount, 0) + XCTAssertTrue(events.isEmpty, "无首帧不能上报致命失败或假装正在播放") + let airport = try XCTUnwrap(engine.rooms["airport-room"]) + let drone = try XCTUnwrap(engine.rooms["drone-room"]) + airport.emit(.published("airport-video", "airport-room", true)) + try await settle() + XCTAssertEqual(airport.subscriptions, ["airport-video:true"]) + airport.emit(.frame("airport-video", "airport-room")) + try await settle() + XCTAssertEqual(events.last, .sourceChanged("airport")) + drone.emit(.published("drone-video", "drone-room", true)) + try await settle() + XCTAssertEqual(events.last, .sourceChanged("airport"), "凭证或发布成功不能提前切走机巢画面") + drone.emit(.frame("drone-video", "drone-room")) + try await settle() + XCTAssertEqual(events.last, .sourceChanged("drone")) + drone.emit(.videoState("drone-video", "drone-room", .frozen)) + try await settle() + XCTAssertEqual(events.last, .sourceChanged("airport")) + receiver.stop() + let count = events.count + drone.emit(.frame("drone-video", "drone-room")) + try await settle() + XCTAssertEqual(events.count, count) + XCTAssertEqual(airport.destroyCount, 1) + XCTAssertEqual(drone.destroyCount, 1) + XCTAssertEqual(engine.destroyCount, 1) + } + + /// 缺少无人机参数时机巢继续等待,补取参数后仍可接入第二路。 + func testSingleSourceTimeoutDoesNotCancelFutureDiscovery() async throws { + let engine = ReceiverEngineProbe() + let receiver = DroneDockLiveReceiver(makeEngine: { _, _ in engine }, firstFrameDelay: { try await Task.sleep(for: .milliseconds(10)) }) + let view = UIView() + var events: [DroneDockLivePlaybackEvent] = [] + receiver.start([configuration("airport")], in: view) { events.append($0) } + try await Task.sleep(for: .milliseconds(60)) + XCTAssertEqual(engine.destroyCount, 0) + XCTAssertTrue(events.isEmpty) + receiver.start([configuration("airport"), configuration("drone")], in: view) { events.append($0) } + XCTAssertEqual(engine.rooms.count, 2) + receiver.stop() + } + + /// SDK 入房错误保留数值供用户定位;纯等待与错误不混为一谈。 + func testRoomFailureShowsActualSDKCode() async throws { + let engine = ReceiverEngineProbe() + let receiver = DroneDockLiveReceiver(makeEngine: { _, _ in engine }) + var events: [DroneDockLivePlaybackEvent] = [] + let view = UIView() + receiver.start([configuration("drone")], in: view) { events.append($0) } + engine.rooms["drone-room"]?.emit(.roomFailed("drone-room", -1000)) + try await settle() + XCTAssertEqual(events.last, .failed("图传入房失败(-1000),请重试")) + XCTAssertEqual(engine.destroyCount, 1) + } + + /// 验证 optional Objective-C 回调确实注册,防止 Swift 方法仅编译通过却不被 SDK 调用。 + func testSDKDelegateSelectorsAreRegisteredAndDebugFactoryIsBlocked() { + let delegate = DroneDockVolcDelegate { _ in } + for selector in ["rtcRoom:onUserPublishStreamVideo:info:isPublish:", "rtcRoom:onRoomStateChanged:withUid:state:extraInfo:", + "rtcEngine:onFirstRemoteVideoFrameDecoded:info:withFrameInfo:", + "rtcEngine:onRemoteVideoStateChanged:info:withVideoState:withVideoStateReason:"] { + XCTAssertTrue(delegate.responds(to: NSSelectorFromString(selector)), selector) + } + XCTAssertNil(DroneDockVolcEngineAdapter.make(appID: "TEST-ONLY") { _ in }) + } + + private func configuration(_ role: String) -> DroneDockVolcLiveConfiguration { + DroneDockVolcLiveConfiguration(appID: "TEST", roomID: "\(role)-room", userID: "viewer", token: "TEST", + expiresAt: Date().addingTimeInterval(3600), role: role) + } + + private func settle() async throws { try await Task.sleep(for: .milliseconds(25)) } +} + +/// 无 SDK 引擎;只记录画布绑定和房间创建。 +@MainActor +private final class ReceiverEngineProbe: DroneDockRTCReceivingEngine { + var rooms: [String: ReceiverRoomProbe] = [:] + var destroyCount = 0 + func makeRoom(_ id: String, onEvent: @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingRoom)? { + let room = ReceiverRoomProbe(emit: onEvent) + rooms[id] = room + return room + } + func setVideoView(_ view: UIView?, streamID: String) -> Int { 0 } + func destroy() { destroyCount += 1 } +} + +/// 无网络房间;回调由测试主动发送。 +@MainActor +private final class ReceiverRoomProbe: DroneDockRTCReceivingRoom { + let emit: @Sendable (DroneDockVolcEvent) -> Void + var subscriptions: [String] = [] + var destroyCount = 0 + init(emit: @escaping @Sendable (DroneDockVolcEvent) -> Void) { self.emit = emit } + func join(_ configuration: DroneDockVolcLiveConfiguration) -> Int { 0 } + func updateToken(_ token: String) -> Int { 0 } + func subscribeVideo(_ streamID: String, subscribe: Bool) -> Int { + subscriptions.append("\(streamID):\(subscribe)") + return 0 + } + func destroy() { destroyCount += 1 } +} diff --git a/suixinkanTests/DroneDockPreparationRouteTests.swift b/suixinkanTests/DroneDockPreparationRouteTests.swift new file mode 100644 index 0000000..22ad028 --- /dev/null +++ b/suixinkanTests/DroneDockPreparationRouteTests.swift @@ -0,0 +1,209 @@ +import UIKit +import XCTest +@testable import suixinkan + +/// 使用纯内存准备/召唤替身验证准备页替换路由,不连接真实设备或图传。 +@MainActor +final class DroneDockPreparationRouteTests: XCTestCase { + private weak var previousKeyWindow: UIWindow? + + /// 正常业务栈移除准备页,任务返回原工作台;更早的导航页面仍完整保留。 + func testSuccessfulSummonReplacesPreparationAndReturnsToSameWorkbench() async throws { + for hasEarlierRoot in [false, true] { + let creation = DroneDockTaskCreationTestService(result: .success(try DroneDockTaskCreationTestData.response())) + let shoot = DroneDockShootTestService(result: .success(try DroneDockShootTestData.response())) + let task = PreparationRouteTaskStub(taskID: 501) + var destinationCount = 0 + let project = try DroneDockPreparationViewFixtures.projectEnvelope() + let (preparation, projects) = try DroneDockPreparationViewFixtures.controller( + context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(), + responses: [project, project], creationService: creation, shootService: shoot, + taskControllerFactory: { id, order, context in + destinationCount += 1 + XCTAssertEqual(id, 501) + XCTAssertEqual(order.orderNumber, "TEST-PREPARATION-001") + XCTAssertEqual(context.scenicID, 128) + return task + }) + let workbench = UIViewController() + workbench.title = "机巢工作台(隔离替身)" + let earlier = UIViewController() + let prefix = hasEarlierRoot ? [earlier, workbench] : [workbench] + let navigation = UINavigationController() + navigation.setViewControllers(prefix + [preparation], animated: false) + let window = makeWindow(navigation) + defer { close(window) } + let summon = try button(in: preparation.view, id: "drone.preparation.summon") + try await settle(window) { summon.isEnabled } + summon.sendActions(for: .touchUpInside) + summon.sendActions(for: .touchUpInside) + try await settle(window) { navigation.topViewController === task && navigation.transitionCoordinator == nil } + XCTAssertEqual(navigation.viewControllers.count, prefix.count + 1) + XCTAssertTrue(navigation.viewControllers.dropLast().elementsEqual(prefix, by: { $0 === $1 })) + XCTAssertFalse(navigation.viewControllers.contains { $0 === preparation }) + XCTAssertEqual(creation.requests.count, 1) + XCTAssertEqual(shoot.requests, [501]) + XCTAssertEqual(destinationCount, 1) + XCTAssertEqual(projects.requests.count, 2) + + XCTAssertTrue(navigation.popViewController(animated: false) === task) + try await settle(window) { navigation.topViewController === workbench } + XCTAssertTrue(navigation.viewControllers.elementsEqual(prefix, by: { $0 === $1 })) + summon.sendActions(for: .touchUpInside) + try await Task.sleep(for: .milliseconds(80)) + XCTAssertTrue(navigation.topViewController === workbench, "已移除准备页的旧按钮不能再次导航") + XCTAssertEqual(destinationCount, 1) + XCTAssertEqual(creation.requests.count, 1) + XCTAssertEqual(shoot.requests, [501]) + XCTAssertEqual(projects.requests.count, 2, "返回工作台不应重新激活已移除准备页的读取") + } + } + + /// 已创建的结束任务仅在用户点击查看时替换准备页,不重发创建或召唤。 + func testExplicitReviewOfCreatedTaskAlsoRemovesPreparation() async throws { + let creation = DroneDockTaskCreationTestService(result: .success(try DroneDockTaskCreationTestData.response())) + let shoot = DroneDockShootTestService(result: .failure(APIError.serverCode(100099, + "任务已结束,无法召唤;失败后请传 restart=true 重新召唤"))) + let task = PreparationRouteTaskStub(taskID: 501) + var destinationCount = 0 + let project = try DroneDockPreparationViewFixtures.projectEnvelope() + let (preparation, _) = try DroneDockPreparationViewFixtures.controller( + context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(), + responses: [project, project], creationService: creation, shootService: shoot, + taskControllerFactory: { id, _, _ in + destinationCount += 1 + XCTAssertEqual(id, 501) + return task + }) + let workbench = UIViewController() + workbench.title = "机巢工作台(隔离替身)" + let navigation = UINavigationController() + navigation.setViewControllers([workbench, preparation], animated: false) + let window = makeWindow(navigation) + defer { close(window) } + let summon = try button(in: preparation.view, id: "drone.preparation.summon") + try await settle(window) { summon.isEnabled } + summon.sendActions(for: .touchUpInside) + try await settle(window) { preparation.viewModel.summonRequiresTaskReview && summon.isEnabled } + XCTAssertTrue(navigation.topViewController === preparation) + XCTAssertEqual(destinationCount, 0) + XCTAssertEqual(summon.title(for: .normal), "查看拍摄任务") + summon.sendActions(for: .touchUpInside) + summon.sendActions(for: .touchUpInside) + try await settle(window) { navigation.topViewController === task && navigation.transitionCoordinator == nil } + XCTAssertTrue(navigation.viewControllers.elementsEqual([workbench, task], by: { $0 === $1 })) + XCTAssertEqual(destinationCount, 1) + XCTAssertEqual(creation.requests.count, 1) + XCTAssertEqual(shoot.requests, [501]) + navigation.popViewController(animated: false) + try await settle(window) { navigation.topViewController === workbench } + XCTAssertEqual(navigation.viewControllers.count, 1) + } + + /// 已离开准备页后返回的迟到召唤回执不能覆盖工作台或再次压入任务页。 + func testLateSummonReceiptAfterLeavingPreparationDoesNotNavigate() async throws { + let creation = DroneDockTaskCreationTestService(result: .success(try DroneDockTaskCreationTestData.response())) + let shoot = PreparationRouteDeferredShoot() + var destinationCount = 0 + let project = try DroneDockPreparationViewFixtures.projectEnvelope() + let (preparation, _) = try DroneDockPreparationViewFixtures.controller( + context: DroneDockPreparationViewFixtures.context(), order: DroneDockPreparationViewFixtures.order(), + responses: [project, project], creationService: creation, shootService: shoot, + taskControllerFactory: { id, _, _ in + destinationCount += 1 + return PreparationRouteTaskStub(taskID: id) + }) + let workbench = UIViewController() + workbench.title = "机巢工作台(隔离替身)" + let navigation = UINavigationController() + navigation.setViewControllers([workbench, preparation], animated: false) + let window = makeWindow(navigation) + defer { shoot.finish(); close(window) } + let summon = try button(in: preparation.view, id: "drone.preparation.summon") + try await settle(window) { summon.isEnabled } + summon.sendActions(for: .touchUpInside) + summon.sendActions(for: .touchUpInside) + try await settle(window) { shoot.isPending } + XCTAssertEqual(creation.requests.count, 1) + XCTAssertEqual(shoot.requests, [501]) + navigation.popViewController(animated: false) + try await settle(window) { navigation.topViewController === workbench } + shoot.finish() + try await Task.sleep(for: .milliseconds(100)) + XCTAssertTrue(navigation.topViewController === workbench) + XCTAssertEqual(navigation.viewControllers.count, 1) + XCTAssertEqual(destinationCount, 0) + XCTAssertEqual(creation.requests.count, 1) + XCTAssertEqual(shoot.requests, [501]) + } + + private func button(in root: UIView, id: String) throws -> UIButton { + try XCTUnwrap(views(root).first { $0.accessibilityIdentifier == id } as? UIButton) + } + + private func views(_ root: UIView) -> [UIView] { [root] + root.subviews.flatMap { self.views($0) } } + + private func makeWindow(_ navigation: UINavigationController) -> UIWindow { + let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first + previousKeyWindow = scene?.windows.first { $0.isKeyWindow } + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + window.rootViewController = navigation + window.makeKeyAndVisible() + return window + } + + private func close(_ window: UIWindow) { + window.rootViewController?.dismiss(animated: false) + window.isHidden = true + window.rootViewController = nil + previousKeyWindow?.makeKeyAndVisible() + } + + private func settle(_ window: UIWindow, until condition: () -> Bool) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(4)) + while ContinuousClock.now < deadline { + window.layoutIfNeeded() + if condition() { + try await Task.sleep(for: .milliseconds(80)) + window.layoutIfNeeded() + if condition() { return } + } + try await Task.sleep(for: .milliseconds(10)) + } + XCTFail("隔离准备页路由未达到预期状态") + throw NSError(domain: "DroneDockPreparationRouteTests", code: 1) + } +} + +/// 只承接任务身份的空任务页,不运行任何状态请求或设备服务。 +@MainActor +private final class PreparationRouteTaskStub: UIViewController { + let taskID: Int + + init(taskID: Int) { + self.taskID = taskID + super.init(nibName: nil, bundle: nil) + title = "拍摄任务(隔离替身)" + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } +} + +/// 故意在页面离开后再完成回执,用于验证取消和导航身份检查,不包含网络传输。 +@MainActor +private final class PreparationRouteDeferredShoot: DroneDockShootServing { + private(set) var requests: [Int] = [] + private var continuation: CheckedContinuation? + var isPending: Bool { continuation != nil } + + func shoot(taskID: Int) async throws -> DroneDockShootResponse { + requests.append(taskID) + return try await withCheckedThrowingContinuation { continuation = $0 } + } + + func finish() { + continuation?.resume(returning: DroneDockShootResponse(dataJSON: #"{"source":"local_mock"}"#)) + continuation = nil + } +} diff --git a/suixinkanTests/DroneDockPreparationViewModelTests.swift b/suixinkanTests/DroneDockPreparationViewModelTests.swift index 7c1af8f..4961ee9 100644 --- a/suixinkanTests/DroneDockPreparationViewModelTests.swift +++ b/suixinkanTests/DroneDockPreparationViewModelTests.swift @@ -312,7 +312,7 @@ final class DroneDockPreparationViewModelTests: XCTestCase { let plane = DroneDockPlaneStatusTestData.plane(status: status, text: label) planes.result = .success(try DroneDockPlaneStatusTestData.response(planes: [plane], recommend: plane, connected: connected)) await model.refreshPlaneStatus() - XCTAssertEqual(model.deviceStatusText, label) + XCTAssertEqual(model.deviceStatusText, "\(label) · 电量 95%") XCTAssertEqual(model.deviceTone, tone) XCTAssertEqual(model.connectionTitle, connection) XCTAssertEqual(model.connectionTone, connected == true ? .green : .gray) @@ -339,6 +339,30 @@ final class DroneDockPreparationViewModelTests: XCTestCase { XCTAssertEqual(model.deviceStatusText, "状态待确认") } + /// 状态文案只有工作状态时补上电量;真实零、百分比边界、未知和已有电量分别处理。 + func testBatteryFieldsSupplementStatusWithoutDuplicatesOrInventedZero() async throws { + let planes = try DroneDockPlaneStatusTestService() + let model = try makeModel(service: ImmediatePreparationService(), planeService: planes) + let cases: [(String, Int?, String?, String)] = [ + ("空闲", 95, nil, "空闲 · 电量 95%"), + ("空闲", 0, nil, "空闲 · 电量 0%"), + ("空闲", 100, "电量 100%", "空闲 · 电量 100%"), + ("空闲 · 电量 95%", 95, "电量 95%", "空闲 · 电量 95%"), + ("空闲 · 电量95%", 95, "电量 95%", "空闲 · 电量95%"), + ("空闲", nil, "电量 88%", "空闲 · 电量 88%"), + ("空闲", nil, "", "空闲"), + ("空闲", -1, nil, "空闲"), + ("空闲", 101, nil, "空闲") + ] + for (state, percent, label, expected) in cases { + var plane = DroneDockPlaneStatusTestData.plane(text: state, battery: percent) + plane["battery_label"] = label + planes.result = .success(try DroneDockPlaneStatusTestData.response(planes: [plane], recommend: plane)) + await model.refreshPlaneStatus() + XCTAssertEqual(model.deviceStatusText, expected) + } + } + /// 无设备与尚无推荐分别展示,不能自行拿列表第一架作为推荐。 func testEmptyPlanesAndMissingRecommendationRemainDistinct() async throws { let planes = try DroneDockPlaneStatusTestService() diff --git a/suixinkanTests/DroneDockRTCPlaybackTests.swift b/suixinkanTests/DroneDockRTCPlaybackTests.swift index 1d5f9b0..2aa410d 100644 --- a/suixinkanTests/DroneDockRTCPlaybackTests.swift +++ b/suixinkanTests/DroneDockRTCPlaybackTests.swift @@ -114,9 +114,23 @@ final class DroneDockRTCPlaybackTests: XCTestCase { event(.firstFrame) view.apply(model) XCTAssertEqual(model.state, .playing) - XCTAssertEqual(view.accessibilityLabel, "无人机摄像头 · 实时图传") + view.layoutIfNeeded() + XCTAssertEqual(view.accessibilityLabel, "实时图传") + XCTAssertNil(model.actionTitle, "已有实时画面时不提供刷新图传按钮") + let badge = try XCTUnwrap(descendants(view).first { $0.accessibilityIdentifier == "drone.task.remote.live.badge" }) + let source = try XCTUnwrap(descendants(view).first { $0.accessibilityIdentifier == "drone.task.remote.live.source" } as? UILabel) + let dot = try XCTUnwrap(descendants(view).first { $0.accessibilityIdentifier == "drone.task.remote.live.dot" }) + let button = try XCTUnwrap(descendants(view).first { $0.accessibilityIdentifier == "drone.task.remote.live.request" } as? UIButton) + XCTAssertFalse(badge.isHidden) + XCTAssertFalse(dot.isHidden) + XCTAssertEqual(source.text, "实时图传") + XCTAssertEqual(dot.backgroundColor, DroneDockStyle.success) + XCTAssertLessThan(badge.bounds.width, 100, "标识按内容宽度排版,不再占用固定 200 点") + XCTAssertTrue(button.isHidden) event(.failed("测试中断")) view.apply(model) + XCTAssertTrue(badge.isHidden, "失败后不能继续显示绿色实时标识") + XCTAssertFalse(button.isHidden, "无画面时仍可主动重试") XCTAssertEqual(player.stops, 1) XCTAssertEqual(view.bounds.size, CGSize(width: 390, height: 219.375)) event(.firstFrame) @@ -269,7 +283,7 @@ final class DroneDockRTCPlaybackTests: XCTestCase { view.apply(model) XCTAssertEqual(model.state, .playing) XCTAssertEqual(model.message, expected) - XCTAssertEqual(view.accessibilityLabel, expected + " · 实时图传") + XCTAssertEqual(view.accessibilityLabel, "实时图传", "切换来源后仍使用简洁实时标识") } selection.setReady(false, role: "airport") player.event?(.sourceChanged(selection.selectedRole)); view.apply(model) @@ -418,6 +432,222 @@ final class DroneDockRTCPlaybackTests: XCTestCase { XCTAssertNil(model.activeRole) } + /// 实测 live 补取会轮换 user_id;机巢凭证未临期时不重建已有房间。 + func testDiscoveryKeepsExistingViewerWhenBackendRotatesUserID() async throws { + let (model, service) = try makeModel(response: dualResponse(droneAvailable: false)) + await model.refresh() + let airport = try XCTUnwrap(model.rtcConfigurations.first) + let session = model.playbackSessionID + var replacement = stream(role: "airport") + replacement["url"] = "app_id=test-app&room_id=TEST-airport&user_id=NEW-VIEWER&token=NEW-TOKEN" + service.response = try DroneDockRTCFixture.response(root: ["airport": replacement, "drone": stream(role: "drone")]) + await model.refresh(keepingPlayback: true) + XCTAssertEqual(model.rtcConfigurations.first, airport) + XCTAssertEqual(model.rtcConfigurations.count, 2) + XCTAssertEqual(model.playbackSessionID, session) + } + + /// 原用户凭证临期时采用新用户凭证,不能因保留健康房间而错过续期。 + func testDiscoveryReplacesViewerAtExpiryWindow() async throws { + var airport = stream(role: "airport") + airport["expire_ts"] = 2_000_000_020 + let (model, service) = try makeModel(response: DroneDockRTCFixture.response(root: ["airport": airport, "drone": ["available": false, "role": "drone"]])) + await model.refresh() + airport["expire_ts"] = 2_000_000_600 + airport["url"] = "app_id=test-app&room_id=TEST-airport&user_id=RENEWED-VIEWER&token=NEW-TOKEN" + service.response = try DroneDockRTCFixture.response(root: ["airport": airport, "drone": stream(role: "drone")]) + await model.refresh(keepingPlayback: true) + XCTAssertEqual(model.rtcConfigurations.first?.userID, "RENEWED-VIEWER") + } + + /// 录制结束时仍在途的 live 回包作废,不能在完成封面上偷偷开始接收。 + func testRecordingCompletionDiscardsPendingLiveResponse() async throws { + let (live, service) = try makeModel() + service.suspend = true + let player = RTCPlayerProbe() + let context = DroneDockShootingTaskTestData.context() + let read = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.response())) + let model = try DroneDockShootingTaskViewModel(context: context, taskID: 501, + order: DroneDockShootingTaskTestData.order(), service: read, currentContext: { context }) + let controller = DroneDockShootingTaskViewController(viewModel: model, liveViewModel: live, livePlayer: player, + shootingPollDelay: { _ in try await Task.sleep(for: .milliseconds(30)) }) + let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + window.rootViewController = UINavigationController(rootViewController: controller) + window.makeKeyAndVisible() + defer { service.finish(); controller.viewWillDisappear(false); window.isHidden = true; window.rootViewController = nil } + try await wait { service.count == 1 } + read.result = .success(try shootDoneReturningResponse()) + try await wait { model.isRecordingFinished } + service.finish() + try await Task.sleep(for: .milliseconds(50)) + XCTAssertEqual(player.starts, 0) + XCTAssertNil(live.playbackSessionID) + XCTAssertEqual(service.count, 1) + } + + /// 录制完成即停止接收并弹出入口;上传仍为 20,旧帧、前后台、重复包均不能重新启动。 + func testRecordingCompletionStopsVideoAndOpensMaterialsOnce() async throws { + let (live, service) = try makeModel() + let player = RTCPlayerProbe() + let context = DroneDockShootingTaskTestData.context() + let read = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.response())) + let model = try DroneDockShootingTaskViewModel(context: context, taskID: 501, + order: DroneDockShootingTaskTestData.order(), service: read, currentContext: { context }) + let destination = UIViewController() + var navigations = 0 + let controller = DroneDockShootingTaskViewController(viewModel: model, liveViewModel: live, livePlayer: player, + materialsControllerFactory: { order, scope in + XCTAssertEqual(order.orderNumber, "TEST-TASK-PAGE-001") + XCTAssertEqual(scope.scenicID, 128) + navigations += 1 + return destination + }, shootingPollDelay: { _ in try await Task.sleep(for: .milliseconds(40)) }) + let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first + let previous = scene?.windows.first { $0.isKeyWindow } + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + window.rootViewController = UINavigationController(rootViewController: controller) + window.makeKeyAndVisible() + defer { window.isHidden = true; window.rootViewController = nil; previous?.makeKeyAndVisible() } + try await wait { player.starts == 1 } + let lateFrame = try XCTUnwrap(player.event) + lateFrame(.firstFrame) + read.result = .success(try shootDoneReturningResponse()) + try await wait { model.isRecordingFinished } + XCTAssertEqual(player.stops, 1) + XCTAssertNil(live.playbackSessionID) + XCTAssertEqual(model.response?.orderFlightTask?.status, 20) + XCTAssertEqual(model.response?.task?.waylineStatus, 24) + XCTAssertTrue(model.isShootCompleteReturning) + XCTAssertTrue(model.presentation.message.contains("无人机正在返航")) + let cover = try XCTUnwrap(descendants(controller.view).first { $0.accessibilityIdentifier == "drone.task.remote.live.cover" }) + XCTAssertFalse(cover.isHidden) + try await Task.sleep(for: .milliseconds(300)) + let attachment = XCTAttachment(image: UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + }) + attachment.name = "录制完成弹窗与静态封面(隔离替身)" + attachment.lifetime = .keepAlways + add(attachment) + let later = try XCTUnwrap(descendants(window).first { $0.accessibilityIdentifier == "drone.task.recordingCompletion.later" } as? UIButton) + later.sendActions(for: .touchUpInside) + window.layoutIfNeeded() + let pageAttachment = XCTAttachment(image: UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + }) + pageAttachment.name = "拍摄完成页面-原型对齐(隔离替身)" + pageAttachment.lifetime = .keepAlways + add(pageAttachment) + var uploading = RealtimeTestData.mediaStagePayload(wayline: 30, version: 2) + uploading["shoot_complete_returning"] = false + read.result = .success(try DroneDockShootingTaskTestData.decode(uploading)) + try await wait { model.response?.stateVersion == 2 } + XCTAssertFalse(model.isShootCompleteReturning) + XCTAssertTrue(model.presentation.message.contains("素材上传中")) + XCTAssertFalse(model.presentation.message.contains("无人机正在返航")) + XCTAssertNil(descendants(window).first { $0.accessibilityIdentifier == "drone.task.recordingCompletion" }) + lateFrame(.firstFrame) + NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil) + NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil) + read.result = .success(try DroneDockShootingTaskTestData.decode(RealtimeTestData.mediaStagePayload(wayline: 50, version: 3))) + try await wait { model.presentation.phase == .completed } + XCTAssertEqual(player.starts, 1) + XCTAssertEqual(service.count, 1) + XCTAssertNil(descendants(window).first { $0.accessibilityIdentifier == "drone.task.recordingCompletion" }) + let primary = try XCTUnwrap(descendants(controller.view).first { $0.accessibilityIdentifier == "drone.task.remote.primary" } as? UIButton) + primary.sendActions(for: .touchUpInside) + primary.sendActions(for: .touchUpInside) + try await wait { controller.navigationController?.topViewController === destination } + XCTAssertEqual(navigations, 1) + } + + /// 已结束任务重新进入时先读状态,不能短暂启动 live;弹窗按钮直达素材库。 + func testEnteringRecordedTaskSkipsLiveAndPopupOpensMaterials() async throws { + let (live, service) = try makeModel() + let context = DroneDockShootingTaskTestData.context() + let read = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.decode( + RealtimeTestData.mediaStagePayload(wayline: 30, version: 1)))) + let model = try DroneDockShootingTaskViewModel(context: context, taskID: 501, + order: DroneDockShootingTaskTestData.order(), service: read, currentContext: { context }) + let destination = UIViewController() + let controller = DroneDockShootingTaskViewController(viewModel: model, liveViewModel: live, livePlayer: RTCPlayerProbe(), + materialsControllerFactory: { _, _ in destination }) + let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + window.rootViewController = UINavigationController(rootViewController: controller) + window.makeKeyAndVisible() + defer { window.isHidden = true; window.rootViewController = nil } + try await wait { model.isRecordingFinished } + XCTAssertEqual(service.count, 0) + let button = try XCTUnwrap(descendants(window).first { $0.accessibilityIdentifier == "drone.task.recordingCompletion.materials" } as? UIButton) + button.sendActions(for: .touchUpInside) + try await wait { controller.navigationController?.topViewController === destination } + } + + /// 直接收到素材上传失败也停止图传、保留素材入口,不能弹成功或因重进页面重新启动 live。 + func testMediaUploadFailureStopsVideoWithoutSuccessPopup() async throws { + let (live, service) = try makeModel() + let player = RTCPlayerProbe() + let context = DroneDockShootingTaskTestData.context() + let read = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.response())) + let model = try DroneDockShootingTaskViewModel(context: context, taskID: 501, + order: DroneDockShootingTaskTestData.order(), service: read, currentContext: { context }) + let controller = DroneDockShootingTaskViewController(viewModel: model, liveViewModel: live, livePlayer: player, + shootingPollDelay: { _ in try await Task.sleep(for: .milliseconds(40)) }) + let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first + let previous = scene?.windows.first { $0.isKeyWindow } + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + window.rootViewController = UINavigationController(rootViewController: controller) + window.makeKeyAndVisible() + defer { window.isHidden = true; window.rootViewController = nil; previous?.makeKeyAndVisible() } + try await wait { player.starts == 1 } + let oldFrame = try XCTUnwrap(player.event) + oldFrame(.firstFrame) + read.result = .success(try DroneDockShootingTaskTestData.response(changes: [ + "task": ["id": 501, "status": 40, "wayline_status": 39], + "order_flight_task": ["id": 501, "status": 40, "result_message": "本地模拟:上传媒体资源出错"], + "ui": ["phase": "post_shoot_upload_failed", "title": "素材上传失败", "commands": []] + ])) + try await wait { model.presentation.phase == .postShootUploadFailed } + window.layoutIfNeeded() + XCTAssertEqual(player.stops, 1) + XCTAssertEqual(service.count, 1) + XCTAssertNil(live.playbackSessionID) + XCTAssertNil(descendants(window).first { $0.accessibilityIdentifier == "drone.task.recordingCompletion" }) + let primary = try XCTUnwrap(descendants(controller.view).first { $0.accessibilityIdentifier == "drone.task.remote.primary" } as? UIButton) + XCTAssertEqual(primary.title(for: .normal), "查看素材") + XCTAssertTrue(primary.isEnabled) + oldFrame(.firstFrame) + controller.viewWillDisappear(false) + controller.viewDidAppear(false) + try await Task.sleep(for: .milliseconds(100)) + XCTAssertEqual(player.starts, 1) + XCTAssertEqual(service.count, 1) + XCTAssertFalse(model.shouldPresentRecordingCompletion) + XCTAssertNil(descendants(window).first { $0.accessibilityIdentifier == "drone.task.recordingCompletion" }) + try await Task.sleep(for: .milliseconds(300)) + window.layoutIfNeeded() + XCTAssertEqual(primary.titleLabel?.text, "查看素材", "实际显示文本与素材动作一致") + let attachment = XCTAttachment(image: UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + }) + attachment.name = "素材上传失败(隔离替身,无成功弹窗)" + attachment.lifetime = .keepAlways + add(attachment) + } + + private func shootDoneReturningResponse() throws -> DroneDockShootingResponse { + var value = RealtimeTestData.mediaStagePayload(wayline: 24, version: 1) + value["shoot_complete_returning"] = true + var task = try XCTUnwrap(value["order_flight_task"] as? [String: Any]) + task["finished_at"] = NSNull() + value["order_flight_task"] = task + value["ui"] = ["phase": "post_shoot_uploading", "title": "拍摄已完成", + "message": "无人机正在返航,请留意现场", "wayline_stage": "shoot_done_returning", + "shoot_complete_returning": true, "commands": []] + return try DroneDockShootingTaskTestData.decode(value) + } + private func stream(role: String, token: String = "TEST-TOKEN") -> [String: Any] { ["available": true, "role": role, "url_type": "volc", "expire_ts": 2_000_000_600, "url": "app_id=test-app&room_id=TEST-\(role)&user_id=TEST-USER&token=\(token)"] diff --git a/suixinkanTests/DroneDockShootDoneReturningTests.swift b/suixinkanTests/DroneDockShootDoneReturningTests.swift new file mode 100644 index 0000000..0a47386 --- /dev/null +++ b/suixinkanTests/DroneDockShootDoneReturningTests.swift @@ -0,0 +1,263 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 验证正常拍完返航标记与真实任务结果独立,HTTP/WS 均只消费隔离快照。 +@MainActor +final class DroneDockShootDoneReturningTests: XCTestCase { + /// 新字段保持缺失、null 和真假语义,手动返航结果码也原样保留。 + func testReturningFieldsDecodeMissingNullTrueAndFalse() throws { + for flag: Bool? in [nil, false, true] { + var value = payload() + var ui = try XCTUnwrap(value["ui"] as? [String: Any]) + if let flag { + value["shoot_complete_returning"] = flag + ui["shoot_complete_returning"] = flag + ui["wayline_stage"] = "shoot_done_returning" + } else { + value.removeValue(forKey: "shoot_complete_returning") + ui.removeValue(forKey: "shoot_complete_returning") + ui.removeValue(forKey: "wayline_stage") + } + value["ui"] = ui + let result = try DroneDockShootingTaskTestData.decode(value) + XCTAssertEqual(result.shootCompleteReturning, flag) + XCTAssertEqual(result.ui?.shootCompleteReturning, flag) + XCTAssertEqual(result.ui?.waylineStage, flag == nil ? nil : "shoot_done_returning") + } + var nullable = payload() + nullable["shoot_complete_returning"] = NSNull() + nullable["ui"] = ["phase": "post_shoot_uploading", "shoot_complete_returning": NSNull(), "wayline_stage": NSNull()] + nullable["task"] = ["id": 501, "status": 20, "result_code": "return_home"] + nullable["order_flight_task"] = ["id": 501, "status": 20, "result_code": "return_home"] + let result = try DroneDockShootingTaskTestData.decode(nullable) + XCTAssertNil(result.shootCompleteReturning) + XCTAssertNil(result.ui?.shootCompleteReturning) + XCTAssertNil(result.ui?.waylineStage) + XCTAssertEqual(result.task?.resultCode, "return_home") + XCTAssertEqual(result.orderFlightTask?.resultCode, "return_home") + } + + /// 顶层、UI 布尔或阶段任一明确标记均能展示正常返航说明,不要求任务终态成功。 + func testExplicitReturningMarkersPreserveExecutingTaskAndExposeMaterials() async throws { + let markers: [(Bool?, Bool?, String?)] = [ + (true, nil, nil), (nil, true, nil), (nil, nil, "shoot_done_returning"), + (true, true, "shoot_done_returning") + ] + for (root, nested, stage) in markers { + for wayline in [20, 24] { + let fixture = try makeFixture(payload(root: root, nested: nested, stage: stage, wayline: wayline)) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .postShootUploading) + XCTAssertEqual(fixture.model.presentation.title, "拍摄已完成") + XCTAssertTrue(fixture.model.presentation.message.contains("无人机正在返航,请留意现场")) + XCTAssertTrue(fixture.model.isShootCompleteReturning) + XCTAssertTrue(fixture.model.isRecordingFinished) + XCTAssertTrue(fixture.model.shouldPresentRecordingCompletion) + XCTAssertEqual(fixture.model.presentation.action, .materials) + XCTAssertTrue(fixture.model.presentation.isActionEnabled) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertFalse(fixture.model.canResummon) + XCTAssertEqual(fixture.model.response?.task?.status, 20) + XCTAssertEqual(fixture.model.response?.orderFlightTask?.status, 20) + XCTAssertEqual(fixture.model.response?.task?.waylineStatus, wayline) + XCTAssertNil(fixture.model.countdownRemainingSeconds) + XCTAssertEqual(fixture.actions.startCount + fixture.actions.resummonCount, 0) + XCTAssertEqual(fixture.service.requests.count, 1) + XCTAssertTrue(fixture.service.requests.allSatisfy { !$0.liveBattery }) + } + } + } + + /// 明确 false 优先于另一处 true、阶段残值和旧设备返航文案,避免继续展示已撤销标记。 + func testExplicitFalseVetoesConflictingReturningMarkers() async throws { + for (root, nested) in [(false, true), (true, false), (false, false)] { + var value = payload(root: root, nested: nested, stage: "shoot_done_returning") + value["current_plane"] = ["id": 58, "work_status": 2, "work_status_label": "正在返航"] + let fixture = try makeFixture(value) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.isShootCompleteReturning) + XCTAssertFalse(fixture.model.presentation.message.contains("无人机正在返航")) + XCTAssertEqual(fixture.model.presentation.phase, .postShootUploading) + XCTAssertEqual(fixture.model.presentation.action, .materials) + } + } + + /// 真实上传或渲染状态覆盖滞留的返航标记,但不会改写拍摄已经完成的页面阶段。 + func testUploadingAndRenderingOverrideStaleReturningFlags() async throws { + for wayline in [30, 40] { + let fixture = try makeFixture(payload(root: true, nested: true, stage: "shoot_done_returning", wayline: wayline)) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.isShootCompleteReturning) + XCTAssertFalse(fixture.model.presentation.message.contains("无人机正在返航")) + XCTAssertEqual(fixture.model.presentation.title, "拍摄已完成") + XCTAssertEqual(fixture.model.presentation.phase, .postShootUploading) + XCTAssertTrue(fixture.model.shouldPresentRecordingCompletion) + XCTAssertEqual(fixture.model.response?.task?.waylineStatus, wayline) + } + } + + /// 同批次切到上传后说明随完整快照更新,旧返航版本不能再次覆盖上传说明。 + func testReturningSnapshotTransitionsToUploadAndRejectsOldVersion() async throws { + let fixture = try makeFixture(payload()) + await fixture.model.refresh() + XCTAssertTrue(fixture.model.isShootCompleteReturning) + fixture.service.result = .success(try DroneDockShootingTaskTestData.decode( + payload(root: false, nested: false, stage: nil, wayline: 30, version: 2))) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.isShootCompleteReturning) + XCTAssertFalse(fixture.model.presentation.message.contains("无人机正在返航")) + XCTAssertEqual(fixture.model.response?.stateVersion, 2) + XCTAssertEqual(fixture.model.response?.task?.waylineStatus, 30) + XCTAssertEqual(fixture.model.applyTaskSnapshot(try DroneDockShootingTaskTestData.decode(payload())), .outdated) + XCTAssertFalse(fixture.model.isShootCompleteReturning) + XCTAssertEqual(fixture.model.response?.task?.waylineStatus, 30) + } + + /// 低电等未拍完返航、任务失败与取消优先于错误残留的完成标记。 + func testPartialFailureAndCancellationNeverBecomeSuccessfulRecording() async throws { + for (status, wayline, phase) in [(40, 29, "failed_restartable"), (40, 91, "failed_restartable"), + (50, 90, "post_shoot_uploading"), (60, 20, "post_shoot_uploading")] { + var value = payload() + value["task"] = ["id": 501, "status": status, "wayline_status": wayline] + value["order_flight_task"] = ["id": 501, "status": status, "result_code": "wayline_\(wayline)", + "result_message": "本地模拟:未拍完提前返航"] + value["ui"] = ["phase": phase, "wayline_stage": "shoot_done_returning", "shoot_complete_returning": true, + "message": "本地模拟:未拍完提前返航", "commands": []] + let fixture = try makeFixture(value) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.isShootCompleteReturning) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + XCTAssertNotEqual(fixture.model.presentation.action, .materials) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertEqual(fixture.model.response?.orderFlightTask?.status, status) + } + } + + /// 手动返航结果码即使伴随残留的运行中摘要或乐观 UI,也必须保持中断失败。 + func testManualReturnHomeResultCodeOverridesResidualCompletedUI() async throws { + for status in [20, 40] { + for field in ["task", "order_flight_task"] { + var value = payload() + value["task"] = ["id": 501, "status": status, "wayline_status": 24] + value["order_flight_task"] = ["id": 501, "status": status] + var task = try XCTUnwrap(value[field] as? [String: Any]) + task["result_code"] = "return_home" + task["result_message"] = "立即返航中断任务" + value[field] = task + let fixture = try makeFixture(value) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .failed) + XCTAssertFalse(fixture.model.isShootCompleteReturning) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + XCTAssertNotEqual(fixture.model.presentation.action, .materials) + XCTAssertFalse(fixture.model.canStartShooting) + } + } + } + + /// 标记只细分可信的录制后阶段,不能凭标记把拍摄中或未知阶段提升为完成。 + func testMarkersDoNotPromoteShootingOrUnknownPhaseToCompletion() async throws { + for phase in ["shooting", "future_phase", "blocked"] { + var value = payload(wayline: 20) + value["ui"] = ["phase": phase, "shoot_complete_returning": true, "wayline_stage": "shoot_done_returning"] + let fixture = try makeFixture(value) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.isShootCompleteReturning) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + XCTAssertFalse(fixture.model.isRecordingFinished) + XCTAssertNotEqual(fixture.model.presentation.action, .materials) + } + } + + /// 缺少新字段的旧快照仍可兼容明确设备返航文案,不凭普通忙碌状态编造返航。 + func testLegacySnapshotsUseOnlyExplicitReturningDeviceLabel() async throws { + for label in ["返航中", "正在返航", "拍摄中", "空闲"] { + var value = payload(root: nil, nested: nil, stage: nil) + value["current_plane"] = ["id": 58, "work_status": 2, "work_status_label": label] + let fixture = try makeFixture(value) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.message.contains("无人机正在返航"), ["返航中", "正在返航"].contains(label)) + } + } + + /// HTTP 和 WS 使用同一个完整快照,在飞行任务仍执行中时呈现一致的返航完成界面。 + func testHTTPAndWebSocketNormalReturningSnapshotsAreEquivalent() async throws { + let value = payload() + let http = try makeFixture(value) + await http.model.refresh() + let socket = try makeFixture(payload(root: nil, nested: nil, stage: nil, wayline: 20)) + guard case .snapshot(let snapshot) = try DroneDockShootingSocketMessage.decode(RealtimeTestData.push(value)) else { + return XCTFail("正常返航完整 WS 快照应可解析") + } + XCTAssertEqual(socket.model.applyTaskSnapshot(snapshot), .applied) + XCTAssertEqual(socket.model.presentation, http.model.presentation) + XCTAssertTrue(socket.model.isShootCompleteReturning) + XCTAssertEqual(socket.model.response?.shootCompleteReturning, true) + XCTAssertEqual(socket.model.response?.ui?.waylineStage, "shoot_done_returning") + XCTAssertTrue(socket.service.requests.isEmpty) + XCTAssertEqual(socket.actions.startCount + socket.actions.resummonCount, 0) + } + + /// 新批次上传阶段不会被旧批次或其他任务的返航标记污染。 + func testOlderBatchAndWrongTaskMarkersCannotRestoreReturningNotice() async throws { + let fixture = try makeFixture(payload(root: false, nested: false, stage: nil, wayline: 30, batch: 101, version: 3)) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.applyTaskSnapshot(try DroneDockShootingTaskTestData.decode( + payload(batch: 100, version: 999))), .outdated) + var wrongTask = payload(batch: 101, version: 4) + wrongTask["order_flight_task_id"] = 502 + XCTAssertEqual(fixture.model.applyTaskSnapshot(try DroneDockShootingTaskTestData.decode(wrongTask)), .invalid) + XCTAssertFalse(fixture.model.isShootCompleteReturning) + XCTAssertEqual(fixture.model.response?.executionBatch, 101) + XCTAssertEqual(fixture.model.response?.stateVersion, 3) + XCTAssertEqual(fixture.model.response?.task?.waylineStatus, 30) + } + + private func payload(root: Bool? = true, nested: Bool? = true, stage: String? = "shoot_done_returning", + wayline: Int = 24, batch: Int = 100, version: Int = 1) -> [String: Any] { + var value = DroneDockShootingTaskTestData.payload() + value["order_flight_task_id"] = 501 + value["execution_batch"] = batch + value["state_version"] = version + value["snapshot_kind"] = "full" + value["task"] = ["id": 501, "status": 20, "wayline_status": wayline] + value["order_flight_task"] = ["id": 501, "status": 20] + value["current_plane"] = ["id": 58, "work_status": 1, "online_status": 1, "work_status_label": "空闲"] + value["execute_gate"] = ["can_execute": false, "primary_action": "blocked"] + if let root { value["shoot_complete_returning"] = root } + var ui: [String: Any] = ["phase": "post_shoot_uploading", "title": "拍摄已完成", "commands": []] + if let nested { ui["shoot_complete_returning"] = nested } + if let stage { ui["wayline_stage"] = stage } + value["ui"] = ui + return value + } + + private func makeFixture(_ payload: [String: Any]) throws -> (model: DroneDockShootingTaskViewModel, + service: DroneDockShootingTaskTestService, actions: ShootDoneReturningActions) { + let context = DroneDockShootingTaskTestData.context() + let service = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.decode(payload))) + let actions = ShootDoneReturningActions() + let model = try DroneDockShootingTaskViewModel(context: context, taskID: 501, + order: DroneDockShootingTaskTestData.order(), service: service, startService: actions, + resummonService: actions, currentContext: { context }) + return (model, service, actions) + } +} + +/// 仅记录潜在误触发的控制调用,不存在真实网络或设备传输。 +@MainActor +private final class ShootDoneReturningActions: DroneDockStartShooting, DroneDockResummonServing { + private(set) var startCount = 0 + private(set) var resummonCount = 0 + + func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse { + startCount += 1 + throw APIError.networkFailed("本地模拟:不应发起开拍") + } + + func resummon(taskID: Int) async throws -> DroneDockShootResponse { + resummonCount += 1 + throw APIError.networkFailed("本地模拟:不应发起重召") + } +} diff --git a/suixinkanTests/DroneDockShootingTaskViewModelTests.swift b/suixinkanTests/DroneDockShootingTaskViewModelTests.swift index 0bf4643..f423980 100644 --- a/suixinkanTests/DroneDockShootingTaskViewModelTests.swift +++ b/suixinkanTests/DroneDockShootingTaskViewModelTests.swift @@ -5,6 +5,70 @@ import XCTest /// 验证真实任务页只读刷新保留快照、同任务重入和身份隔离,不接入飞控。 @MainActor final class DroneDockShootingTaskViewModelTests: XCTestCase { + /// 从召唤进入先展示同任务前往回执,首个明确到达快照可直接替换,不伪造最低等待时长。 + func testSummonReceiptShowsTravelUntilAuthoritativeArrivalSnapshot() async throws { + let service = DeferredShootingTaskService() + let fixture = try ShootingTaskFixture(service: service, initialSummonReceipt: travelReceipt()) + defer { service.cancelAll() } + XCTAssertEqual(fixture.model.presentation.phase, .navigating) + XCTAssertEqual(fixture.model.statusTitle, "无人机正在赶来") + XCTAssertNil(fixture.model.response, "受理回执不能伪造完整状态或触发图传") + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertFalse(fixture.model.presentation.isActionEnabled) + let pending = Task { await fixture.model.refresh() } + await waitForRequests(1, service: service) + XCTAssertTrue(fixture.model.isLoading) + XCTAssertEqual(fixture.model.presentation.title, "无人机正在赶来") + service.resolve(0, with: .success(try DroneDockShootingTaskTestData.response(changes: [ + "ui": ["phase": "arrived_pending_start", "title": "无人机已到达"], + "execute_gate": ["can_execute": true, "primary_action": "start_shoot"] + ]))) + await pending.value + XCTAssertEqual(fixture.model.presentation.phase, .ready) + XCTAssertEqual(fixture.model.presentation.title, "无人机已到达") + fixture.model.invalidate() + XCTAssertNotEqual(fixture.model.presentation.phase, .navigating, "首次回执不能在重入时复活旧的前往阶段") + } + + /// 受理成功、错误任务、缺少身份或非前往阶段都不能凭空生成正在赶来。 + func testTravelReceiptRequiresExplicitPhaseAndMatchingIdentity() throws { + let invalid: [[String: Any]] = [ + ["accepted": false], ["accepted": NSNull()], ["ui": ["phase": "arrived_pending_start"]], + ["ui": ["title": "无人机正在赶来"]], ["order_flight_task": NSNull()], + ["order_flight_task": ["id": 502, "order_number": "TEST-TASK-PAGE-001", "scenic_id": 128]], + ["order_flight_task": ["id": 501, "order_number": "OTHER", "scenic_id": 128]], + ["order_flight_task": ["id": 501, "order_number": "TEST-TASK-PAGE-001", "scenic_id": 129]], + ["order_flight_task_id": 502] + ] + for changes in invalid { + let fixture = try ShootingTaskFixture(initialSummonReceipt: travelReceipt(changes)) + XCTAssertNotEqual(fixture.model.presentation.phase, .navigating) + XCTAssertFalse(fixture.model.canStartShooting) + } + } + + /// 状态读取失败和身份变化优先于首次前往回执,不能掩盖失联或串账号。 + func testTravelReceiptDoesNotHideReadFailureOrIdentityChange() async throws { + let fixture = try ShootingTaskFixture(initialSummonReceipt: travelReceipt()) + fixture.service.result = .failure(APIError.networkFailed("本地模拟断网")) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .readError) + fixture.scope.context = DroneDockShootingTaskTestData.context(scenicID: 129) + fixture.model.invalidate(preservingSnapshot: true) + XCTAssertEqual(fixture.model.presentation.phase, .readError) + XCTAssertFalse(fixture.model.presentation.isActionEnabled) + } + + /// 匿名回执的顶层 task_id 故意不同,验证它不会被误当订单任务 ID。 + private func travelReceipt(_ changes: [String: Any] = [:]) throws -> DroneDockShootResponse { + let base: [String: Any] = [ + "accepted": true, "task_id": 9001, + "order_flight_task": ["id": 501, "order_number": "TEST-TASK-PAGE-001", "scenic_id": 128], + "ui": ["phase": "going_to_spot", "title": "无人机正在前往点位"] + ] + let data = try JSONSerialization.data(withJSONObject: base.merging(changes) { _, new in new }) + return DroneDockShootResponse(dataJSON: String(decoding: data, as: UTF8.self)) + } /// 同一上传快照无论来自 HTTP 还是 WS,均不能被开拍门禁或 finished_at 误判为阻止/完成。 func testPostShootStagesMatchAcrossHTTPAndWebSocket() async throws { for (index, wayline) in [24, 30, 40].enumerated() { @@ -13,8 +77,8 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase { await fixture.model.refresh() let presentation = fixture.model.presentation XCTAssertEqual(presentation.phase, .postShootUploading) - XCTAssertEqual(presentation.title, "拍摄完毕上传中") - XCTAssertEqual(presentation.action, .refresh, "此时仅可刷新,不能提前查看已完成素材") + XCTAssertEqual(presentation.title, "拍摄已完成") + XCTAssertEqual(presentation.action, .materials, "录制结束即可前往素材库查看上传进度") XCTAssertTrue(presentation.isActionEnabled) XCTAssertFalse(fixture.model.canStartShooting) XCTAssertFalse(fixture.model.canResummon) @@ -53,9 +117,9 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase { payload["ui"] = ["phase": "post_shoot_uploading"] let fixture = try ShootingTaskFixture(response: DroneDockShootingTaskTestData.decode(payload)) await fixture.model.refresh() - XCTAssertEqual(fixture.model.presentation.title, "拍摄完毕上传中") - XCTAssertEqual(fixture.model.statusTitle, "拍摄完毕上传中") - XCTAssertEqual(fixture.model.presentation.message, "录制已结束,素材正在处理,请稍候。") + XCTAssertEqual(fixture.model.presentation.title, "拍摄已完成") + XCTAssertEqual(fixture.model.statusTitle, "拍摄已完成") + XCTAssertEqual(fixture.model.presentation.message, "本次拍摄已结束,可前往查看素材。\n素材上传中,可在素材库查看进度。") payload["task"] = ["id": 501, "status": 40, "wayline_status": 91] payload["order_flight_task"] = ["id": 501, "status": 40] payload["state_version"] = 2 @@ -69,6 +133,18 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase { XCTAssertNotEqual(fixture.model.presentation.action, .materials) } + /// 完成文案只在当前设备明确返航时提示返航,不把原型文案当作设备事实。 + func testPostShootReturnNoticeRequiresCurrentPlaneReturningState() async throws { + for label in ["返航中", "正在返航", "空闲", "拍摄中", ""] { + var payload = RealtimeTestData.mediaStagePayload(wayline: 24, version: 1) + payload["current_plane"] = ["id": 22, "work_status_label": label] + let fixture = try ShootingTaskFixture(response: DroneDockShootingTaskTestData.decode(payload)) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.message.contains("无人机正在返航"), ["返航中", "正在返航"].contains(label)) + XCTAssertEqual(fixture.model.presentation.action, .materials) + } + } + /// 缺省/无效间隔回退到五秒,合法建议限制在两至三十秒,避免紧密请求或溢出。 func testPollingIntervalUsesBoundedServerHint() async throws { for (hint, expected) in [(0, 5_000), (-1, 5_000), (1, 2_000), (8_000, 8_000), (Int.max, 30_000)] { @@ -176,7 +252,8 @@ final class DroneDockShootingTaskViewModelTests: XCTestCase { XCTAssertEqual(fixture.model.dataJSON, next.dataJSON) XCTAssertEqual(fixture.model.title, "新的点位摘要") XCTAssertEqual(fixture.model.presentation.phase, .shooting) - XCTAssertEqual(fixture.model.statusMessage, "新的任务说明") + XCTAssertEqual(fixture.model.statusMessage, "请关注现场及实时画面。\n请勿关闭本页或息屏。") + XCTAssertTrue(fixture.model.dataJSON?.contains("新的任务说明") == true, "原始后端说明继续保留在快照中") XCTAssertEqual(fixture.model.deviceStatusText, "拍摄中 · 电量 92%") XCTAssertEqual(fixture.model.telemetry.batteryText, "92%") } @@ -386,12 +463,14 @@ private final class ShootingTaskFixture { let model: DroneDockShootingTaskViewModel init(taskID: Int = 501, context: DroneDockHomeContext = DroneDockShootingTaskTestData.context(), - response: DroneDockShootingResponse? = nil, service customService: (any DroneDockShootingServing)? = nil) throws { + response: DroneDockShootingResponse? = nil, service customService: (any DroneDockShootingServing)? = nil, + initialSummonReceipt: DroneDockShootResponse? = nil) throws { service = DroneDockShootingTaskTestService(result: .success(try response ?? DroneDockShootingTaskTestData.response())) scope = ShootingTaskScope(context: context) let currentScope = scope model = DroneDockShootingTaskViewModel(context: context, taskID: taskID, order: try DroneDockShootingTaskTestData.order(), - service: customService ?? service, currentContext: { currentScope.context }) + service: customService ?? service, initialSummonReceipt: initialSummonReceipt, + currentContext: { currentScope.context }) } } diff --git a/suixinkanTests/DroneDockShootingTaskViewTests.swift b/suixinkanTests/DroneDockShootingTaskViewTests.swift index 73e585d..0e4e7ed 100644 --- a/suixinkanTests/DroneDockShootingTaskViewTests.swift +++ b/suixinkanTests/DroneDockShootingTaskViewTests.swift @@ -7,6 +7,52 @@ import XCTest final class DroneDockShootingTaskViewTests: XCTestCase { private weak var previousKeyWindow: UIWindow? + /// 正常拍摄对齐原型且没有详情/中央刷新动作;导航栏仍能读取同一任务。 + func testShootingMatchesPrototypeAndKeepsNavigationRefresh() async throws { + let clock = TaskViewPollClock() + let service = try TaskViewReadService(response: realtimeViewSnapshot(version: 1, phase: "shooting", title: "后端旧拍摄标题")) + let controller = try makeController(service: service, pollDelay: { try await clock.wait($0) }) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { controller.viewModel.presentation.phase == .shooting && clock.pendingCount == 1 } + XCTAssertNil(find(in: controller.view, id: "drone.task.remote.details")) + XCTAssertNil(find(in: controller.view, id: "drone.task.remote.refresh")) + let title = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.statusTitle") as? UILabel) + let message = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.statusMessage") as? UILabel) + let indicator = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.shootingIndicator") as? UIButton) + XCTAssertEqual(title.text, "无人机正在拍摄中") + XCTAssertEqual(message.text, "请关注现场及实时画面。\n请勿关闭本页或息屏。") + XCTAssertFalse(indicator.isEnabled) + XCTAssertFalse(hidden(indicator)) + let regions = fixedFrames(in: controller.view) + indicator.sendActions(for: .touchUpInside) + XCTAssertEqual(service.requests, [501], "禁用的拍摄中展示不产生操作") + try tapNavigationRefresh(controller) + try await settle(window) { service.requests.count == 2 && !controller.viewModel.isLoading } + XCTAssertEqual(service.requests, [501, 501]) + XCTAssertEqual(fixedFrames(in: controller.view), regions) + XCTAssertEqual(controller.viewModel.presentation.phase, .shooting) + try await Task.sleep(for: .milliseconds(300)) + window.layoutIfNeeded() + capture(window, name: "拍摄中-对齐体验网页(隔离替身)") + } + + /// 首份 shooting 挂起期间保留召唤回执的前往提示,页面加载占位不能覆盖它。 + func testInitialReadKeepsAcceptedTravelReceiptVisible() async throws { + let receipt = DroneDockShootResponse(dataJSON: #"{"accepted":true,"task_id":9001,"order_flight_task":{"id":501,"order_number":"TEST-TASK-501","scenic_id":128},"ui":{"phase":"going_to_spot"}}"#) + let service = try TaskViewReadService(response: realtimeViewSnapshot(version: 1, phase: "arrived_pending_start", title: "本地模拟:无人机已到达")) + service.suspendNext = true + let controller = try makeController(service: service, initialSummonReceipt: receipt) + let window = makeWindow(root: controller) + defer { service.cancelAll(); close(window) } + try await settle(window) { controller.viewModel.isLoading } + XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机正在赶来")) + XCTAssertFalse(visibleTexts(in: controller.view).contains("正在获取任务状态")) + service.finish() + try await settle(window) { controller.viewModel.presentation.phase == .ready } + XCTAssertTrue(visibleTexts(in: controller.view).contains("本地模拟:无人机已到达")) + } + /// 使用模拟 WebSocket 推进任务阶段,断线立即 HTTP 兜底,恢复后停轮询;固定布局不变。 func testRealtimeUpdatesPageAndAutomaticallyFallsBackThenRecovers() async throws { let harness = RealtimeHarness() @@ -41,10 +87,11 @@ final class DroneDockShootingTaskViewTests: XCTestCase { harness.sockets[1].emit(try RealtimeTestData.push(RealtimeTestData.mediaStagePayload(wayline: 30, version: 4, orderNumber: "TEST-TASK-501"))) try await settle(window) { controller.viewModel.response?.stateVersion == 4 && clock.pendingCount == 0 } XCTAssertEqual(controller.viewModel.presentation.phase, .postShootUploading) - XCTAssertTrue(visibleTexts(in: controller.view).contains("拍摄完毕上传中")) - XCTAssertFalse(visibleTexts(in: controller.view).contains("查看素材")) + try await settle(window) { self.visibleTexts(in: controller.view).contains("查看素材") } + XCTAssertTrue(visibleTexts(in: controller.view).contains("拍摄已完成")) + XCTAssertTrue(visibleTexts(in: controller.view).contains("查看素材")) XCTAssertEqual(fixedFrames(in: controller.view), fixedBefore) - capture(window, name: "WebSocket 本地模拟:拍摄完毕上传中(未连接无人机)") + capture(window, name: "WebSocket 本地模拟:拍摄完成提示(未连接无人机)") harness.sockets[1].emit(try RealtimeTestData.push(RealtimeTestData.mediaStagePayload(wayline: 50, version: 5, orderNumber: "TEST-TASK-501"))) try await settle(window) { controller.viewModel.response?.stateVersion == 5 && clock.pendingCount == 0 } XCTAssertEqual(controller.viewModel.presentation.phase, .completed) @@ -397,9 +444,11 @@ final class DroneDockShootingTaskViewTests: XCTestCase { XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "81%") XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.satellite")?.accessibilityValue, "30颗") XCTAssertTrue(visibleTexts(in: controller.view).contains("更新后的点位与航线")) - XCTAssertTrue(visibleTexts(in: controller.view).contains("正在拍摄")) + XCTAssertTrue(visibleTexts(in: controller.view).contains("无人机正在拍摄中")) XCTAssertFalse(visibleTexts(in: controller.view).contains("空闲 · 电量93%")) - XCTAssertTrue(refreshButton.isEnabled) + XCTAssertTrue(hidden(refreshButton)) + let indicator = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.shootingIndicator") as? UIButton) + XCTAssertFalse(indicator.isEnabled) } /// 后台取消后迟到回执不重新展示当前设备或遥测。 @@ -457,12 +506,8 @@ final class DroneDockShootingTaskViewTests: XCTestCase { XCTAssertFalse(visibleTexts(in: controller.view).contains("任务状态读取失败")) XCTAssertTrue(visibleTexts(in: controller.view).contains { $0.contains("刷新失败,当前显示上次数据") }) XCTAssertEqual(find(in: controller.view, id: "drone.task.remote.metric.battery")?.accessibilityValue, "93%") - let details = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.details") as? UIButton) - details.sendActions(for: .touchUpInside) - try await settle(window) { controller.presentedViewController is UIAlertController } - let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController) - XCTAssertTrue(alert.message?.contains("测试刷新断网") == true) - controller.dismiss(animated: false) + XCTAssertNil(find(in: controller.view, id: "drone.task.remote.details")) + XCTAssertNotNil(controller.viewModel.errorMessage) try button(in: controller.view).sendActions(for: .touchUpInside) try await settle(window) { service.requests.count == 3 && controller.viewModel.errorMessage == nil } XCTAssertNotNil(controller.viewModel.response) @@ -524,8 +569,8 @@ final class DroneDockShootingTaskViewTests: XCTestCase { XCTAssertEqual(service.requests, [501, 501]) } - /// 详情展示完整文案,展开本身不会发起任何读取或控制请求。 - func testDetailsKeepFullServerMessageWithoutRequestingAgain() async throws { + /// 移除详情按钮后仍保留原始完整说明,页面不新增读取或控制请求。 + func testFullServerMessageIsPreservedWithoutDetailsButton() async throws { let message = String(repeating: "测试任务等待后端处理,完整原因应在详情保留。", count: 20) var payload = TaskViewData.payload() payload["ui"] = ["phase": "blocked", "title": "任务暂不可执行", "message": message] @@ -535,13 +580,12 @@ final class DroneDockShootingTaskViewTests: XCTestCase { let window = makeWindow(root: controller) defer { close(window) } try await settle(window) { controller.viewModel.response != nil } - let details = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.details") as? UIButton) - details.sendActions(for: .touchUpInside) - try await settle(window) { controller.presentedViewController is UIAlertController } - let alert = try XCTUnwrap(controller.presentedViewController as? UIAlertController) - XCTAssertTrue(alert.message?.contains(message) == true) + XCTAssertNil(find(in: controller.view, id: "drone.task.remote.details")) + XCTAssertNil(controller.presentedViewController) + let label = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.statusMessage") as? UILabel) + XCTAssertEqual(label.text, message) + XCTAssertTrue(controller.viewModel.dataJSON?.contains(message) == true) XCTAssertEqual(service.requests, [501]) - controller.dismiss(animated: false) } /// 明确完成后素材入口沿用当前订单和景区,只跳转一次,不再次创建或召唤。 @@ -564,7 +608,8 @@ final class DroneDockShootingTaskViewTests: XCTestCase { try await settle(window) { controller.viewModel.presentation.phase == .completed } let primary = try XCTUnwrap(find(in: controller.view, id: "drone.task.remote.primary") as? UIButton) XCTAssertTrue(primary.isEnabled) - XCTAssertEqual(primary.title(for: .normal), "查看素材") + XCTAssertEqual(primary.configuration?.title, "查看素材") + XCTAssertTrue(visibleTexts(in: primary).contains("查看素材")) primary.sendActions(for: .touchUpInside) primary.sendActions(for: .touchUpInside) try await settle(window) { controller.navigationController?.topViewController === destination } @@ -573,13 +618,14 @@ final class DroneDockShootingTaskViewTests: XCTestCase { } private func makeController(service: any DroneDockShootingServing, scope: TaskViewScope? = nil, + initialSummonReceipt: DroneDockShootResponse? = nil, pollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }, realtime: DroneDockShootingRealtimeSession? = nil, materialsFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) throws -> DroneDockShootingTaskViewController { let scope = scope ?? TaskViewScope() let order = try JSONDecoder().decode(DroneDockHomeOrder.self, from: Data(#"{"order_number":"TEST-TASK-501","project_id":101,"project_name":"入口五次套餐","user_phone":"130****0501"}"#.utf8)) let model = DroneDockShootingTaskViewModel(context: scope.value, taskID: 501, order: order, - service: service, currentContext: { scope.value }) + service: service, initialSummonReceipt: initialSummonReceipt, currentContext: { scope.value }) return DroneDockShootingTaskViewController(viewModel: model, realtimeSession: realtime, materialsControllerFactory: materialsFactory, shootingPollDelay: pollDelay) } diff --git a/suixinkanTests/DroneDockStatusContractTests.swift b/suixinkanTests/DroneDockStatusContractTests.swift new file mode 100644 index 0000000..a4fd219 --- /dev/null +++ b/suixinkanTests/DroneDockStatusContractTests.swift @@ -0,0 +1,230 @@ +import Foundation +import XCTest +@testable import suixinkan + +/// 验证 9.9.1 设备、订单任务、航线和页面阶段的职责边界;所有响应均为内存快照。 +@MainActor +final class DroneDockStatusContractTests: XCTestCase { + /// 录制后的上传失败单独显示,即使订单任务已失败,也不变成重新飞行入口。 + func testExplicitMediaFailureStopsRecordingWithoutSuccessNoticeOrResummon() async throws { + for status in [20, 40] { + let fixture = try makeFixture(payload(phase: "post_shoot_upload_failed", status: status, wayline: 39)) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .postShootUploadFailed) + XCTAssertTrue(fixture.model.presentation.title.contains("失败")) + XCTAssertEqual(fixture.model.presentation.message, "本地模拟:素材处理失败") + XCTAssertEqual(fixture.model.presentation.action, .materials) + XCTAssertTrue(fixture.model.presentation.isActionEnabled) + XCTAssertTrue(fixture.model.isRecordingFinished) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + XCTAssertFalse(fixture.model.canResummon) + XCTAssertFalse(fixture.model.canStartShooting) + await fixture.model.resummon() + await fixture.model.startShooting() + XCTAssertEqual(fixture.actions.resummonCount, 0) + XCTAssertEqual(fixture.actions.startCount, 0) + } + } + + /// 航线上传和渲染失败可补足缺少 UI 阶段的快照,不从订单“执行中”误报正在拍摄。 + func testUploadAndRenderFailureFallbackRemainRecordedAndDoNotEnableResummon() async throws { + for wayline in [39, 49] { + for phase: String? in [nil, "blocked"] { + let fixture = try makeFixture(payload(phase: phase, status: 20, wayline: wayline)) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .postShootUploadFailed) + XCTAssertTrue(fixture.model.isRecordingFinished) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + XCTAssertEqual(fixture.model.presentation.action, .materials) + XCTAssertFalse(fixture.model.canResummon) + XCTAssertEqual(fixture.model.response?.orderFlightTask?.status, 20, "不得改写后端订单任务状态") + } + } + } + + /// 后端明确返回旧的可重召阶段时保持既有流程,不把新上传失败规则覆盖到它。 + func testExplicitRestartableFailureKeepsExistingResummonFlow() async throws { + let fixture = try makeFixture(payload(phase: "failed_restartable", status: 40, wayline: 39)) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .failed) + XCTAssertEqual(fixture.model.presentation.action, .retry) + XCTAssertTrue(fixture.model.canResummon) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + } + + /// 拍摄与执行失败优先于乐观的拍摄阶段,不能弹出录制完成提示。 + func testShootingAndExecutionFailureOverrideOptimisticShootingPhase() async throws { + for wayline in [29, 91] { + let fixture = try makeFixture(payload(phase: "shooting", status: 20, wayline: wayline)) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .failed) + XCTAssertFalse(fixture.model.isRecordingFinished) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + XCTAssertFalse(fixture.model.canStartShooting) + } + } + + /// 航线取消不因订单摘要仍“执行中”或开拍门禁残留而开放拍摄。 + func testWaylineCancellationBlocksStartAndResummon() async throws { + let fixture = try makeFixture(payload(phase: "arrived_pending_start", status: 20, wayline: 90)) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .blocked) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertFalse(fixture.model.canResummon) + XCTAssertFalse(fixture.model.isRecordingFinished) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + } + + /// 待确认任务不能借旧的开拍门禁或安全指令列表继续操作。 + func testUnconfirmedTaskBlocksFlightActionsDespiteOptimisticUI() async throws { + for phase in ["arrived_pending_start", "shooting", "completed"] { + var value = payload(phase: phase, status: 60, wayline: 20) + value["ui"] = ["phase": phase, "title": "本地模拟:旧阶段", "commands": [["command": "flighttask_pause"]]] + let fixture = try makeFixture(value) + await fixture.model.refresh() + XCTAssertEqual(fixture.model.presentation.phase, .blocked) + XCTAssertTrue(fixture.model.presentation.title.contains("待确认")) + XCTAssertFalse(fixture.model.canStartShooting) + XCTAssertFalse(fixture.model.canResummon) + XCTAssertFalse(fixture.model.canSendCommand(.pause)) + XCTAssertFalse(fixture.model.shouldPresentRecordingCompletion) + await fixture.model.startShooting() + await fixture.model.resummon() + await fixture.model.sendCommand(.pause) + XCTAssertEqual(fixture.actions.startCount, 0) + XCTAssertEqual(fixture.actions.resummonCount, 0) + XCTAssertEqual(fixture.actions.commandCount, 0) + } + } + + /// 当前工作态为空闲时,不让历史在线字段 0/2 错误覆盖它。 + func testIdleWorkStatusTakesPrecedenceOverHistoricalOfflineFlags() async throws { + for online in [0, 2] { + let fixture = try makeFixture(payload(phase: "failed_restartable", status: 40, wayline: 29, + plane: ["id": 58, "work_status": 1, "online_status": online])) + await fixture.model.refresh() + XCTAssertTrue(fixture.model.canResummon) + XCTAssertFalse(fixture.model.presentation.actionNote?.contains("离线") == true) + } + } + + /// 工作态拍摄中属于忙碌,历史在线字段不能将其显示为离线或空闲。 + func testBusyWorkStatusBlocksResummonWithBusyReason() async throws { + for online in [0, 1, 2] { + let fixture = try makeFixture(payload(phase: "failed_restartable", status: 40, wayline: 29, + plane: ["id": 58, "work_status": 2, "online_status": online])) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.canResummon) + XCTAssertEqual(fixture.model.presentation.actionNote, "无人机忙碌,暂不可召唤") + await fixture.model.resummon() + XCTAssertEqual(fixture.actions.resummonCount, 0) + } + } + + /// 工作态明确离线时,即使表字段仍在线也不能重召唤。 + func testOfflineWorkStatusWinsOverOnlineFlag() async throws { + let fixture = try makeFixture(payload(phase: "failed_restartable", status: 40, wayline: 29, + plane: ["id": 58, "work_status": 0, "online_status": 1])) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.canResummon) + XCTAssertEqual(fixture.model.presentation.actionNote, "无人机离线,暂不可召唤") + } + + /// 没有可信工作态时,所有明确非 1 在线标记均保守视为离线,而非仅处理历史值 2。 + func testUnknownWorkStatusUsesNonOnlineFlagAsOfflineFallback() async throws { + for online in [0, 2, 99, -1] { + for work: Int? in [nil, 99] { + var plane: [String: Any] = ["id": 58, "online_status": online] + if let work { plane["work_status"] = work } + let fixture = try makeFixture(payload(phase: "failed_restartable", status: 40, wayline: 29, plane: plane)) + await fixture.model.refresh() + XCTAssertFalse(fixture.model.canResummon) + XCTAssertEqual(fixture.model.presentation.actionNote, "无人机离线,暂不可召唤") + } + } + } + + /// 同一个完整快照从 HTTP 或 WS 进入时得到相同的素材失败展示与动作许可。 + func testMediaFailureMatchesAcrossHTTPAndWebSocket() async throws { + var value = payload(phase: "post_shoot_upload_failed", status: 40, wayline: 39) + value["order_flight_task_id"] = 501 + value["execution_batch"] = 100 + value["state_version"] = 12 + value["snapshot_kind"] = "full" + let http = try makeFixture(value) + await http.model.refresh() + guard case .snapshot(let snapshot) = try DroneDockShootingSocketMessage.decode(RealtimeTestData.push(value)) else { + return XCTFail("完整 WS 快照必须可解析") + } + let socket = try makeFixture(payload(phase: "shooting", status: 20, wayline: 20)) + XCTAssertEqual(socket.model.applyTaskSnapshot(snapshot), .applied) + XCTAssertEqual(socket.model.presentation, http.model.presentation) + XCTAssertTrue(socket.model.isRecordingFinished) + XCTAssertFalse(socket.model.shouldPresentRecordingCompletion) + XCTAssertFalse(socket.model.canResummon) + XCTAssertTrue(http.service.requests.allSatisfy { !$0.liveBattery }) + XCTAssertTrue(socket.service.requests.isEmpty) + } + + /// 成功提示只保留给录制完成和素材就绪,不因新增素材失败阶段扩大弹窗范围。 + func testRecordingSuccessNoticeOnlyAllowsSuccessfulRecordingPhases() async throws { + for (phase, status, wayline) in [("post_shoot_uploading", 20, 30), ("completed", 30, 50)] { + let fixture = try makeFixture(payload(phase: phase, status: status, wayline: wayline)) + await fixture.model.refresh() + XCTAssertTrue(fixture.model.isRecordingFinished) + XCTAssertTrue(fixture.model.shouldPresentRecordingCompletion) + } + } + + 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["task"] = ["id": 501, "status": status, "wayline_status": wayline] + value["order_flight_task"] = ["id": 501, "status": status, "result_message": "本地模拟:素材处理失败"] + value["current_plane"] = plane + value["execute_gate"] = ["can_execute": true, "primary_action": "start_shoot"] + if let phase { + value["ui"] = ["phase": phase, "title": "本地模拟:素材处理失败", "message": "本地模拟:素材处理失败", "commands": []] + } else { + value["ui"] = NSNull() + } + return value + } + + private func makeFixture(_ payload: [String: Any]) throws -> (model: DroneDockShootingTaskViewModel, + service: DroneDockShootingTaskTestService, actions: StatusContractActions) { + let context = DroneDockShootingTaskTestData.context() + let service = DroneDockShootingTaskTestService(result: .success(try DroneDockShootingTaskTestData.decode(payload))) + let actions = StatusContractActions() + let model = DroneDockShootingTaskViewModel(context: context, taskID: 501, + order: try DroneDockShootingTaskTestData.order(), service: service, startService: actions, + commandService: actions, resummonService: actions, currentContext: { context }) + return (model, service, actions) + } +} + +/// 只记录被调用次数并返回本地错误,绝无网络或设备传输能力。 +@MainActor +private final class StatusContractActions: DroneDockStartShooting, DroneDockCommandSending, DroneDockResummonServing { + private(set) var startCount = 0 + private(set) var commandCount = 0 + private(set) var resummonCount = 0 + + /// 任何意外的开拍调用都会留下计数,便于检查门禁。 + func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse { + startCount += 1 + throw APIError.networkFailed("本地模拟,无真实设备") + } + + /// 任何意外的安全指令调用都会留下计数,便于检查门禁。 + func sendCommand(taskID: Int, command: DroneDockSafetyCommand) async throws -> DroneDockCommandResponse { + commandCount += 1 + throw APIError.networkFailed("本地模拟,无真实设备") + } + + /// 任何意外的重召唤调用都会留下计数,便于检查门禁。 + func resummon(taskID: Int) async throws -> DroneDockShootResponse { + resummonCount += 1 + throw APIError.networkFailed("本地模拟,无真实设备") + } +} diff --git a/suixinkanTests/DroneDockTaskFixedLayoutTests.swift b/suixinkanTests/DroneDockTaskFixedLayoutTests.swift index b0449ce..e6cdca5 100644 --- a/suixinkanTests/DroneDockTaskFixedLayoutTests.swift +++ b/suixinkanTests/DroneDockTaskFixedLayoutTests.swift @@ -8,7 +8,7 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { private let compactSize = CGSize(width: 375, height: 146) private let regularSize = CGSize(width: 402, height: 220) private let phases: [DroneDockTaskDisplayPhase] = [ - .loading, .navigating, .ready, .shooting, .postShootUploading, .paused, .returning, + .loading, .navigating, .ready, .shooting, .postShootUploading, .postShootUploadFailed, .paused, .returning, .completed, .failed, .blocked, .unknown, .readError ] @@ -36,6 +36,8 @@ 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) { + XCTAssertTrue(isHidden(device)) } else { XCTAssertFalse(isHidden(device)) XCTAssertEqual(device.text, "空闲 · 电量 93%") @@ -64,25 +66,230 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { } } - /// 长文案可通过至少 44 点高的详情入口查看,截断不影响命中与回调。 - func testCompactLongErrorDetailsRemainTappable() throws { + /// 移除通用详情后,长错误保留完整文本与可点击的整行刷新入口。 + func testCompactLongErrorHasNoDetailsAndKeepsFullWidthRefresh() throws { let status = makeStatus(size: compactSize) - apply(presentation(.readError, longCopy: true), to: status) + let value = presentation(.readError, longCopy: true) + apply(value, to: status) + var actionCalls = 0 var detailsCalls = 0 + status.onPrimaryAction = { actionCalls += 1 } status.onDetails = { detailsCalls += 1 } - let details = try XCTUnwrap(find(in: status, suffix: "details") as? UIButton) - XCTAssertTrue(details.isEnabled) - XCTAssertFalse(isHidden(details)) - XCTAssertGreaterThanOrEqual(details.bounds.height, 44) - XCTAssertGreaterThanOrEqual(details.bounds.width, 44) - let center = details.convert(CGPoint(x: details.bounds.midX, y: details.bounds.midY), to: status) + XCTAssertNil(find(in: status, suffix: "details")) + XCTAssertEqual((find(in: status, suffix: "statusMessage") as? UILabel)?.text, value.message) + let refresh = try XCTUnwrap(find(in: status, suffix: "refresh") as? UIButton) + XCTAssertTrue(refresh.isEnabled) + XCTAssertFalse(isHidden(refresh)) + XCTAssertGreaterThanOrEqual(refresh.bounds.height, 44) + XCTAssertEqual(refresh.bounds.width, compactSize.width - 32, accuracy: 0.5) + let center = refresh.convert(CGPoint(x: refresh.bounds.midX, y: refresh.bounds.midY), to: status) let hit = status.hitTest(center, with: nil) - XCTAssertTrue(hit === details || hit?.isDescendant(of: details) == true) - details.sendActions(for: .touchUpInside) - XCTAssertEqual(detailsCalls, 1) + XCTAssertTrue(hit === refresh || hit?.isDescendant(of: refresh) == true) + refresh.sendActions(for: .touchUpInside) + XCTAssertEqual(actionCalls, 1) + XCTAssertEqual(detailsCalls, 0) try assertReadableContainedContent(in: status) } + /// 拍摄中按原型显示左侧视频状态、右侧两行说明与整行禁用指示,不提供详情或刷新动作。 + func testShootingPanelMatchesPrototypeAndCannotTriggerActions() async throws { + let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first + let previous = scene?.windows.first { $0.isKeyWindow } + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + let host = UIViewController() + window.rootViewController = host + window.makeKeyAndVisible() + defer { window.isHidden = true; window.rootViewController = nil; previous?.makeKeyAndVisible() } + for size in [compactSize, regularSize, CGSize(width: 375, height: 95)] { + let status = makeStatus(size: size) + host.view.addSubview(status) + defer { status.removeFromSuperview() } + var actionCalls = 0 + var detailsCalls = 0 + status.onPrimaryAction = { actionCalls += 1 } + status.onDetails = { detailsCalls += 1 } + apply(presentation(.shooting), to: status) + window.layoutIfNeeded() + try await Task.sleep(for: .milliseconds(50)) + layoutHierarchy(status) + let shooting = try XCTUnwrap(find(in: status, suffix: "shooting")) + let title = try XCTUnwrap(find(in: status, suffix: "statusTitle") as? UILabel) + let message = try XCTUnwrap(find(in: status, suffix: "statusMessage") as? UILabel) + let indicator = try XCTUnwrap(find(in: status, suffix: "shootingIndicator") as? UIButton) + XCTAssertFalse(isHidden(shooting)) + XCTAssertEqual(title.text, "无人机正在拍摄中") + XCTAssertEqual(message.text, "请关注现场及实时画面。\n请勿关闭本页或息屏。") + if size.height >= 120 { + XCTAssertFalse(isHidden(message)) + XCTAssertEqual(title.convert(title.bounds, to: status).minX, message.convert(message.bounds, to: status).minX, accuracy: 0.5) + } + XCTAssertFalse(indicator.isEnabled) + XCTAssertEqual(indicator.configuration?.title, "拍摄中") + XCTAssertNotNil(indicator.configuration?.image) + XCTAssertEqual(indicator.configuration?.background.backgroundColor, UIColor(hex: 0xD7E7FF)) + XCTAssertEqual(indicator.configuration?.baseForegroundColor, UIColor(hex: 0x4D91FF)) + XCTAssertEqual(indicator.bounds.width, size.width - 36, accuracy: 0.5) + XCTAssertGreaterThanOrEqual(indicator.bounds.height, 44) + XCTAssertTrue(isHidden(try XCTUnwrap(find(in: status, suffix: "deviceStatus")))) + XCTAssertNil(find(in: status, suffix: "details")) + if let refresh = find(in: status, suffix: "refresh") { XCTAssertTrue(isHidden(refresh)) } + indicator.sendActions(for: .touchUpInside) + XCTAssertEqual(actionCalls, 0) + XCTAssertEqual(detailsCalls, 0) + try assertReadableContainedContent(in: status) + if size.height >= 120 { capture(status, name: "拍摄中-原型布局-\(Int(size.width))x\(Int(size.height))") } + } + } + + /// 从到达到拍摄中再进入错误/完成状态时,独立面板和通用操作互不留下旧入口。 + func testShootingPanelTransitionsClearOldCountdownAndRestoreAllowedAction() throws { + let status = makeStatus(size: regularSize) + 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)) + 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) + indicator.sendActions(for: .touchUpInside) + XCTAssertEqual(actionCalls, 0) + apply(presentation(.readError), to: status) + XCTAssertTrue(isHidden(indicator)) + let refresh = try XCTUnwrap(find(in: status, suffix: "refresh") as? UIButton) + XCTAssertFalse(isHidden(refresh)) + XCTAssertTrue(refresh.isEnabled) + XCTAssertEqual(refresh.bounds.width, regularSize.width - 32, accuracy: 0.5) + refresh.sendActions(for: .touchUpInside) + XCTAssertEqual(actionCalls, 1) + apply(presentation(.completed), to: status) + XCTAssertTrue(isHidden(indicator)) + let materials = try XCTUnwrap(find(in: status, suffix: "primary") as? UIButton) + XCTAssertFalse(isHidden(materials)) + XCTAssertTrue(materials.isEnabled) + materials.sendActions(for: .touchUpInside) + XCTAssertEqual(actionCalls, 2) + XCTAssertNil(find(in: status, suffix: "details")) + try assertReadableContainedContent(in: status) + } + + /// 倒计时在固定小屏内保持可见,数字更新不重建按钮、不扩大现有动作许可。 + func testArrivalCountdownFitsFixedAreasAndUpdatesOnlyDisplay() throws { + for size in [compactSize, regularSize] { + 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) + var actionCalls = 0 + status.onPrimaryAction = { actionCalls += 1 } + XCTAssertEqual(countdown.text, "自动开拍倒计时:30 秒") + XCTAssertFalse(isHidden(countdown)) + XCTAssertFalse(primary.isEnabled) + try assertReadableContainedContent(in: status) + if !longCopy { capture(status, name: "到达倒计时30秒-\(Int(size.width))x\(Int(size.height))") } + + for seconds in [29, 12, 1, 0, -1] { + status.updateCountdown(seconds: seconds) + layoutHierarchy(status) + XCTAssertEqual(countdown.text, "自动开拍倒计时:\(max(0, seconds)) 秒") + XCTAssertFalse(isHidden(countdown)) + XCTAssertTrue(find(in: status, suffix: "primary") === primary) + XCTAssertEqual(primary.title(for: .normal), initialButtonTitle) + XCTAssertEqual(title.text, initialTitle) + XCTAssertFalse(primary.isEnabled, "倒数到零也不能放开开拍动作") + XCTAssertEqual(actionCalls, 0, "数字更新不能触发开拍或其他主动作") + XCTAssertEqual(status.bounds.size, size) + try assertReadableContainedContent(in: status) + } + 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) + XCTAssertEqual(actionCalls, 0) + try assertReadableContainedContent(in: status) + } + } + } + + /// 未到达及后端切换到其他阶段时清除数字,迟到的界面计时更新也不能重新显示。 + 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)) + for phase in phases where phase != .ready { + apply(presentation(phase, countdownSeconds: 30), to: status) + XCTAssertTrue(isHidden(countdown), "\(phase)") + XCTAssertNil(countdown.text) + status.updateCountdown(seconds: 12) + layoutHierarchy(status) + XCTAssertTrue(isHidden(countdown), "迟到计时不得覆盖 \(phase)") + XCTAssertNil(countdown.text) + } + apply(presentation(.ready), to: status) + XCTAssertTrue(isHidden(countdown), "未提供倒计时时保留既有界面") + XCTAssertNil(countdown.text) + } + + /// 完成态的说明与标题左对齐,素材按钮全宽;刷新或阶段变化不能绕过操作门禁。 + func testCompletionPanelMatchesPrototypeAndKeepsActionGate() async throws { + let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first + let previous = scene?.windows.first { $0.isKeyWindow } + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + let host = UIViewController() + window.rootViewController = host + window.makeKeyAndVisible() + defer { window.isHidden = true; window.rootViewController = nil; previous?.makeKeyAndVisible() } + for size in [compactSize, regularSize] { + let status = makeStatus(size: size) + host.view.addSubview(status) + defer { status.removeFromSuperview() } + let value = DroneDockTaskPresentation(phase: .postShootUploading, title: "拍摄已完成", + message: "本次拍摄已结束,可前往查看素材。\n素材处理中,可在素材库查看进度。", + deviceStatus: "拍摄中 · 电量 90%", action: .materials, actionTitle: "查看素材", isActionEnabled: true) + apply(value, to: status) + window.layoutIfNeeded() + try await Task.sleep(for: .milliseconds(50)) + layoutHierarchy(status) + let title = try XCTUnwrap(find(in: status, suffix: "statusTitle") as? UILabel) + let message = try XCTUnwrap(find(in: status, suffix: "statusMessage") as? UILabel) + let button = try XCTUnwrap(find(in: status, suffix: "primary") as? UIButton) + XCTAssertEqual(title.convert(title.bounds, to: status).minX, message.convert(message.bounds, to: status).minX, accuracy: 0.5) + XCTAssertEqual(button.bounds.width, size.width - 32, accuracy: 0.5) + XCTAssertNotNil(button.configuration?.image) + let text = try XCTUnwrap(button.titleLabel) + let image = try XCTUnwrap(button.imageView) + let contentFrame = text.convert(text.bounds, to: button).union(image.convert(image.bounds, to: button)) + XCTAssertEqual(contentFrame.midX, button.bounds.midX, accuracy: 1, "素材图标与文字整体居中") + XCTAssertTrue(isHidden(try XCTUnwrap(find(in: status, suffix: "deviceStatus")))) + var calls = 0 + status.onPrimaryAction = { calls += 1 } + button.sendActions(for: .touchUpInside) + XCTAssertEqual(calls, 1) + capture(status, name: "拍摄完成-原型布局-\(Int(size.width))x\(Int(size.height))") + status.apply(value, isRefreshing: true) + button.sendActions(for: .touchUpInside) + XCTAssertEqual(calls, 1) + XCTAssertFalse(button.isEnabled) + apply(presentation(.failed), to: status) + XCTAssertTrue(isHidden(button), "上传失败必须显示失败状态,不能保留完成操作面板") + button.sendActions(for: .touchUpInside) + XCTAssertEqual(calls, 1) + XCTAssertTrue(isHidden(try XCTUnwrap(find(in: status, suffix: "completed")))) + try assertReadableContainedContent(in: status) + } + } + /// 失败长原因在固定小屏与真实剩余高度内可展开,主按钮保持全宽且不能触发召唤。 func testFailureReasonDetailsAndDisabledRetryFitFixedAreas() throws { for size in [compactSize, regularSize, CGSize(width: 402, height: 207.875)] { @@ -110,7 +317,7 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { XCTAssertEqual(retry.bounds.width, details.bounds.width, accuracy: 0.5) retry.sendActions(for: .touchUpInside) XCTAssertEqual(actionCalls, 0) - XCTAssertTrue(isHidden(try XCTUnwrap(find(in: status, suffix: "details")))) + XCTAssertNil(find(in: status, suffix: "details")) try assertReadableContainedContent(in: status) } } @@ -227,7 +434,8 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { } } - private func presentation(_ phase: DroneDockTaskDisplayPhase, longCopy: Bool = false) -> DroneDockTaskPresentation { + private func presentation(_ phase: DroneDockTaskDisplayPhase, longCopy: Bool = false, + countdownSeconds: Int? = nil) -> DroneDockTaskPresentation { let title: String let action: DroneDockTaskDisplayAction let actionTitle: String? @@ -236,8 +444,9 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { case .loading: (title, action, actionTitle, enabled) = ("正在获取任务状态", .none, nil, false) case .navigating: (title, action, actionTitle, enabled) = ("无人机正在前往点位", .refresh, "刷新任务状态", true) case .ready: (title, action, actionTitle, enabled) = ("无人机已到达", .start, "开始拍摄", false) - case .shooting: (title, action, actionTitle, enabled) = ("正在拍摄", .refresh, "刷新任务状态", true) - case .postShootUploading: (title, action, actionTitle, enabled) = ("拍摄完毕上传中", .refresh, "刷新任务状态", true) + 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 .completed: (title, action, actionTitle, enabled) = ("本次拍摄已完成", .materials, "查看素材", true) @@ -249,9 +458,11 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { let longTitle = String(repeating: "航线任务状态需要确认,", count: 8) let longMessage = String(repeating: "服务端返回的完整错误说明需要保留供工作人员查看,请检查任务和设备状态。", count: 12) return DroneDockTaskPresentation(phase: phase, title: longCopy && phase != .failed ? longTitle : title, - message: longCopy ? longMessage : phase == .failed ? "拍摄指令执行失败" : "请确认当前状态后继续操作。", + message: longCopy ? longMessage : phase == .failed ? "拍摄指令执行失败" + : phase == .shooting ? "请关注现场及实时画面。\n请勿关闭本页或息屏。" : "请确认当前状态后继续操作。", deviceStatus: "空闲 · 电量 93%", action: action, actionTitle: actionTitle, isActionEnabled: enabled, - actionNote: phase == .failed ? "无人机离线,暂不可召唤" : nil) + actionNote: phase == .failed ? "无人机离线,暂不可召唤" : nil, + countdownSeconds: countdownSeconds) } private func makeController(service: any DroneDockShootingServing, size: CGSize) throws -> DroneDockShootingTaskViewController { @@ -294,10 +505,12 @@ final class DroneDockTaskFixedLayoutTests: XCTestCase { } } } + XCTAssertNil(find(in: status, suffix: "details"), file: file, line: line) let failure = try XCTUnwrap(find(in: status, suffix: "failure"), file: file, line: line) - let detailsSuffix = isHidden(failure) ? "details" : "failureDetails" - let details = try XCTUnwrap(find(in: status, suffix: detailsSuffix) as? UIButton, file: file, line: line) - XCTAssertFalse(isHidden(details), file: file, line: line) + if !isHidden(failure) { + let details = try XCTUnwrap(find(in: status, suffix: "failureDetails") as? UIButton, file: file, line: line) + XCTAssertFalse(isHidden(details), file: file, line: line) + } } private func assertContained(_ view: UIView, in container: UIView, diff --git a/suixinkanTests/DroneDockTaskPresentationTests.swift b/suixinkanTests/DroneDockTaskPresentationTests.swift index 45336da..c47fbde 100644 --- a/suixinkanTests/DroneDockTaskPresentationTests.swift +++ b/suixinkanTests/DroneDockTaskPresentationTests.swift @@ -5,10 +5,10 @@ import XCTest /// 验证任务页展示阶段和动作的保守映射;阶段夹具用于显示测试,不代表全部状态已经后端实测。 @MainActor final class DroneDockTaskPresentationTests: XCTestCase { - /// 显式阶段提供显示语义,保留后端标题和说明,不编造飞行百分比。 + /// 前往阶段使用产品文案,其余标题和阶段说明保留后端内容,不编造飞行百分比。 func testExplicitDisplayPhaseFixturesPreserveBackendText() async throws { let phases: [(String, DroneDockTaskDisplayPhase)] = [ - ("navigating", .navigating), ("shooting", .shooting), ("paused", .paused), + ("going_to_spot", .navigating), ("navigating", .navigating), ("paused", .paused), ("returning", .returning), ("blocked", .blocked) ] for (phase, expected) in phases { @@ -17,7 +17,7 @@ final class DroneDockTaskPresentationTests: XCTestCase { "current_plane": ["status_text": "服务端设备文案"] ]) XCTAssertEqual(result.phase, expected) - XCTAssertEqual(result.title, "服务端阶段标题") + XCTAssertEqual(result.title, expected == .navigating ? "无人机正在赶来" : "服务端阶段标题") XCTAssertEqual(result.message, "服务端完整阶段说明") XCTAssertEqual(result.deviceStatus, "服务端设备文案") XCTAssertEqual(result.action, .refresh) @@ -25,6 +25,21 @@ final class DroneDockTaskPresentationTests: XCTestCase { } } + /// 拍摄中的正常提示采用体验网页文案,中央只显示禁用状态,状态刷新仍走导航栏。 + func testShootingMatchesPrototypeWithoutPrimaryAction() async throws { + let result = try await presentation([ + "ui": ["phase": "shooting", "title": "后端拍摄阶段", "message": "后端旧提示"], + "current_plane": ["status_text": "拍摄中 · 电量95%"] + ]) + XCTAssertEqual(result.phase, .shooting) + XCTAssertEqual(result.title, "无人机正在拍摄中") + XCTAssertEqual(result.message, "请关注现场及实时画面。\n请勿关闭本页或息屏。") + XCTAssertEqual(result.action, .none) + XCTAssertEqual(result.actionTitle, "拍摄中") + XCTAssertFalse(result.isActionEnabled) + XCTAssertEqual(result.deviceStatus, "拍摄中 · 电量95%") + } + /// 后端明确允许开始或恢复时本轮仍禁用,因为尚未对接相应飞控接口。 func testStartAndResumeRemainDisabledEvenWithPermission() async throws { let ready = try await presentation([ diff --git a/机巢工作台页面接口对接记录.md b/机巢工作台页面接口对接记录.md index 50eab86..605fa16 100644 --- a/机巢工作台页面接口对接记录.md +++ b/机巢工作台页面接口对接记录.md @@ -6,6 +6,117 @@ > 核对范围:当前工作区。准备页使用张工 `project-info` 和朱工 `plane-status`;“确认并召唤”按 `project-info → tasks/create → shoot` 执行,召唤业务成功后进入任务页;2026-11-02 按用户要求恢复 `shooting` 前台轮询:进入及回前台立即读取,之后每次请求结束按 `poll_hint_ms` 延时再读,默认 5 秒、限制 2~30 秒;离页/后台停止,刷新保留旧快照。准备页 `plane-status` 保持轮询。最新 2026-10-29 17:18–17:19 模拟器实操新建任务 11,再以 `{id:11,restart:false}` 召唤;两个接口均成功,绑定飞机 61、航线任务 1931。17:19:04 首次查询允许开始,17:19:59 手动回查已为航线执行失败、禁止拍摄,当前待朱工定位 1931 失败原因与自动派机条件(见 7.7.3)。任务 6 / 航线 1926 的先前失败记录保留。召唤回执的“已到达”不是物理验证,本轮未调用开始拍摄或控制接口。任务 2 的参数、订单类型及机场状态失败保留为历史,原因不因新任务成功而作推断。`workbench`、定位请求已停用;`start-shoot` 已实现纯本地模拟(见 7.6.2),真实开拍入口保持禁用;`command` 已实现纯本地模拟(见 7.6.3),真实控制保持禁用;图传已于 2026-11-02 接入火山 RTC 参数与播放器(Release 手动开启,Debug 保持拦截,真实画面待用户联调,见 7.6.5);2026-10-30 已完成真实成片上传、保存及回查,见 9.4。 > 用途:记录每个页面实际调用的接口、提供人、调用时机、请求参数和返回 JSON,供 iOS 与后端持续联调。 +## 2026-11-03:任务页移除详情与拍摄中原型对齐 + +依据用户本轮要求,已对照打开的 [机巢体验交互原型](https://voicestudio.suixinkan.cn/) 调整拍摄任务页;原型核对未执行真实任务创建、飞控或图传操作。 + +- 移除任务页通用“详情”按钮,其他阶段主按钮占整行。失败原因区域仍支持点击展开完整原因。 +- 拍摄中优先使用产品文案“无人机正在拍摄中”,说明分两行显示“请关注现场及实时画面。”和“请勿关闭本页或息屏。”;左侧浅蓝圆形视频图标、右侧标题与说明,下方整行浅蓝禁用“拍摄中”指示按钮,保留相机图标。 +- 拍摄中面板不再展示设备摘要或中央刷新按钮,导航栏刷新保留;禁用状态指示不触发主操作。 +- 展示调整不改写后端阶段、订单或航线任务终态。失败/取消、身份与版本校验、安全门禁、HTTP/WS 读取规则及 Debug 禁飞保护沿用既有约定。 + +验证:157 项相关模拟器隔离测试全部通过,覆盖按钮移除、375/402 点宽及极小高度布局、到达倒计时切换、导航刷新、手动开拍、安全控制和完成/错误状态切换。结果包 `test_sim_2026-11-03T08-28-06-515Z_pid38943_07d96fc4.xcresult`;已检查完整页面及 375×146、402×220 状态区截图,图文及按钮无重叠。Release 无签名编译通过(`/private/tmp/suixinkan-shooting-prototype-release-build.log`)。未执行真实任务创建、飞控或图传,未将原型演示或模拟数据记为后端真实成功。 + +## 2026-11-03:任务页返回直达机巢工作台 + +用户要求工作台进入准备页、再进入任务页时,把准备页从导航栈移除。准备页的自动成功跳转和手动查看任务统一以任务页替换栈顶准备页,保留原工作台及其上游页面;任务页的普通返回与系统侧滑返回直接回到该工作台,不新建工作台、不再次创建或召唤任务。工作台已有任务的直接入口仍沿用原有 push。 + +仅独立模拟/调试启动时,准备页自身就是导航根页面,没有可返回的工作台,此时保留根页回退入口。该兼容不影响工作台正常业务路径。 + +验证:36 项相关模拟器隔离测试全部通过,含新增 3 项路由用例,覆盖完整导航栈替换、返回原工作台、更早页面保留、显式查看已创建任务、连点与迟到回执,以及独立模拟根页兼容。结果包 `test_sim_2026-11-03T08-04-56-551Z_pid38943_09fd825e.xcresult`。Release 无签名编译通过(`/private/tmp/suixinkan-preparation-stack-release-build.log`);不执行真实任务创建、召唤或图传。 + +## 2026-11-03:正常拍完开始返航即显示拍摄完成 + +依据用户补充及 Downloads 中朱工更新的《随心瞰9.9.1-App机巢与素材库接口.md》“正常拍完开始返航”说明和样例 A/B。现有 `post_shoot_uploading` 可直接复用:后端确认司空 `taskDetail.status=success` 后写返航标记并进入航线 24、更新缓存和推送;前端不必等待回到机巢、`finished_at` 或素材全就绪,也不直接查询司空或执行后端内部方法。 + +| 可信快照 | 前端展示与处理 | +| --- | --- | +| `ui.phase=post_shoot_uploading`,顶层/UI `shoot_complete_returning=true` 或 `ui.wayline_stage=shoot_done_returning` | “拍摄已完成”及“无人机正在返航,请留意现场”;停止本机 RTC、显示静态封面、按任务批次去重完成提示,保留查看当前订单素材入口 | +| 航线 30,返航标记已清理 | 完成标题保留,说明切“素材上传中,可在素材库查看进度” | +| 航线 40 | 完成标题保留,说明切“素材渲染中,可在素材库查看进度” | +| `partially_done` 对应航线 29 / 订单任务 40 / `failed_restartable` | 保留失败原因与既有重召流程,不弹拍摄完成 | +| `result_code=return_home` | 明确手动中断,按失败处理,残留完成文案或标记不能覆盖 | + +新增 DTO 分别保留顶层和 UI 布尔以及 UI 子阶段,缺失/null 兼容旧回包;完整快照替换后不沿用旧标记。显式 false 或已进入航线 30/40/50 时不再显示返航说明;旧回包只有明确设备返航文案时保留原有兼容。标记只补充已确认完成阶段的说明,不能单独把失败、取消、待确认、矛盾或未知 UI 阶段改为完成。 + +订单飞行任务仍可为 20、航线仍为后端真实 20/24,`finished_at` 可为 null;不修改终态、不宣告素材就绪、不提前扣次。HTTP `shooting?live_battery=0` 和 WebSocket `app_airport_shooting_updated` 继续共用任务身份、execution_batch、state_version 校验。 + +验证:151 项不同相关隔离用例最终全部通过,其中新增 11 项返航标记合同测试;首轮 150 项通过、一项页面用例误用了无标记旧夹具,修正后所属 28 项播放/页面用例全部复测通过。覆盖正常返航、`finished_at=null`、订单任务20、上传/渲染清标记、提前/手动中断、残留矛盾标记、HTTP/WS、版本/批次/身份,以及完成弹窗去重与本机图传释放。结果包 `test_sim_2026-11-03T07-46-53-966Z_pid38943_c272e6bd.xcresult`、`test_sim_2026-11-03T07-50-16-581Z_pid38943_42691c6c.xcresult`;后者保留正常拍完返航完成页截图。Release 无签名编译通过(`/private/tmp/suixinkan-shoot-done-returning-release-build.log`),未连接真实设备或调用图传/飞控。 + +## 2026-11-03:App 本地到达倒计时(用户最新确认) + +用户已明确倒计时由 App 自行创建、维护,进入已到达状态后仅显示剩余秒数;后端自动开始拍摄后,App 依据接口阶段更新 UI。本节覆盖此前等待后端补充截止时间、剩余秒数和服务端时间字段的提案,无需为当前展示新增接口字段。 + +- 接受身份、批次及版本校验通过的 `arrived_pending_start` 且开拍门禁允许后,以本地单调时钟建立 30 秒期限。相同任务、相同 `execution_batch` 的重复包和新版本到达包不重置;缺少批次的旧回包在当前页面会话按默认批次维护,新执行批次重新计时。 +- 独立秒数标签每秒更新,向上取整显示 30~0;逐秒更新不重建状态或按钮,不发送开拍、飞控、图传或额外状态请求。0 秒继续显示,仍保持后端到达阶段;常规 HTTP/WS 状态读取沿用既有流程。 +- 后端返回 `shooting` 时立即清除秒数并切换拍摄 UI,不等待 App 数完。失败、取消、暂停、返回前往等非到达阶段隐藏数字;同批次再次到达仍沿用原期限,避免显示被刷新重新拉回 30 秒。 +- 离页或后台取消 UI 定时任务,单调时钟期限保留;同一页面会话返回后计算已过去的时间。新建页面的独立 ViewModel 从本地首次可信到达开始,不保存到磁盘或跨账号共享。身份失效、权限终止或清除快照后不继续显示旧倒计时。 +- 数字展示不改变手动开拍门禁、防重复提交、结果未知锁、设备状态或后端任务结果。Debug 拦截和代理仅使用隔离替身/模拟器验证的约定继续保持。 +- 用户补充确认手动“开始拍摄”和倒计时并行:已到达、后端门禁允许且没有提交/未知结果锁时,30 秒、倒数中和 0 秒均可手动点击。手动提交只发送一次同任务开拍,受理后仍等接口返回阶段;倒计时不是按钮禁用条件。现有 Release 入口和按钮流程已符合此规则,本次补充实际点击回归验证。 + +手动开拍补测:18 项相关隔离测试全部通过,覆盖 30/18/0 秒时按钮实际触发开拍替身、连点仅提交一次、受理后按后端切换,以及业务拒绝/结果未知保护。结果包 `test_sim_2026-11-03T07-23-59-050Z_pid38943_49c0435f.xcresult`。本次无需修改生产按钮或倒计时逻辑,未调用真实设备接口。 + +验证:124 项相关模拟器测试全部通过,含 12 项倒计时逻辑、2 项页面生命周期及 2 项数字显示/固定布局新用例;覆盖 30~0 秒取整、到零零请求、提前开拍、同批次刷新/新批次、后台/离页和身份权限清理。结果包 `test_sim_2026-11-03T07-14-26-247Z_pid38943_e9f1673f.xcresult`;页面截图单项复测 `test_sim_2026-11-03T07-19-36-432Z_pid38943_8cdd56cb.xcresult`,等待按钮文字过渡结束后核对 30/0 秒实际显示。375/402 点宽截图已检查,倒计时与至少 44 点按钮不重叠。Release 无签名编译通过(`/private/tmp/suixinkan-local-countdown-release-build.log`)。未调用真实开拍、图传或其他设备接口。 + +## 2026-11-03:无人机状态枚举补充与客户端修正 + +来源为用户本次直接提供的 9.9.1 合同,适用于同名接口字段;不把不同状态域的数字互相转换。 + +| 字段域 | 已确认取值 | 使用职责 | +| --- | --- | --- | +| `work_status` | 0 离线、1 空闲、2 拍摄中 | 工作台/列表的忙闲;不表示已到首点或具体拍摄页进度 | +| `online_status` | 1 在线;0、2 等非 1 为离线 | 飞机表在线标记;明确工作态优先,缺失或未知工作态才作保守兜底 | +| `is_receive_order` | 1 可接单、2 暂停接单 | 接单配置,不等同于起飞许可 | +| `order_flight_task.status` / `task.status` | 10 待执行、20 执行中、30 成功、40 失败、50 取消、60 待确认 | 订单飞行任务结果,不从 20 推断正在拍摄 | +| `task.wayline_status` | 10 待拍摄、20 拍摄中、24 下载中、29 拍摄失败、30 上传媒体、39 上传失败、40 渲染中、49 渲染失败、50 已完成、90 取消、91 执行失败 | 具体航线阶段;与订单任务 status 独立 | +| `ui.phase` | `waiting_summon`、`going_to_spot`、`arrived_pending_start`、`shooting`、`post_shoot_uploading`、`post_shoot_upload_failed`、`completed`、`failed_restartable`、`blocked` | 拍摄页主要展示依据;兼容原有 `paused` / `returning` 等既有阶段 | + +本次修正此前漏掉的 `post_shoot_upload_failed`,独立显示素材上传/渲染失败与当前订单的素材入口,保留具体失败原因;停止本机图传并使用静态封面,不弹“拍摄已完成”成功提示。航线 39/49 在缺少明确 UI 阶段时可回退到素材处理失败;后端明确 `failed_restartable` 则保留既有失败重召流程,不用上传失败码自行新增重召许可。航线 29/91 按拍摄/执行失败,90 按取消处理;订单任务 60 显示“任务待确认”,仅允许刷新核对。 + +设备重召校验先使用工作态:明确 0 离线、2 忙碌时禁止;明确 1 不受历史 `online_status=0/2` 覆盖;工作态缺失或未知时,已提供的非 1 在线标记保守视为离线。准备页原本使用 `work_status` 展示忙闲,仍由后端门禁决定是否允许提交,未根据“在线/可接单”新增可飞许可。 + +这份枚举没有定义自动开拍时间字段;后续用户已确认使用 App 本地显示倒计时,见本页顶部最新约定,无需等待时间字段。 + +验证:140 项相关模拟器测试全部通过,包含新增 12 项状态合同测试与素材失败图传/页面测试,覆盖 HTTP/WS 同义、工作态优先、忙碌/离线限制、待确认门禁、旧重召流程及固定区域布局。结果包 `test_sim_2026-11-03T06-59-06-641Z_pid38943_a7568fa4.xcresult`;页面单项复测包 `test_sim_2026-11-03T07-02-58-767Z_pid38943_ced185fe.xcresult` 等待按钮标题过渡结束后再次核对实际“查看素材”文字,并保留上传失败且无成功弹窗的稳定截图。Release 无签名编译通过(`/private/tmp/suixinkan-status-contract-release-build.log`)。使用隔离网络、播放器及操作替身,未执行真实设备请求。 + +## 2026-11-03:任务页原型对齐与倒计时历史排查 + +用户补充任务 8 / 执行批次 2418 的日志。首个 `arrived_pending_start` 为 14:27:09,14:28:34 首次出现 `shooting`,观测间隔约 85 秒。`started_at`、`state_updated_at` 和 `estimated_fly_time` 不用于倒计时。此前曾建议后端增加精确期限,现已按用户最新确认改为首次可信到达后的 App 本地 30 秒显示,实际开拍仍以接口为准。 + +旧时间字段增量提案已撤销,不再作为接入前置条件;实现规则以本页顶部的 App 本地倒计时为准。 + +任务页已按 [机巢体验原型](https://voicestudio.suixinkan.cn/) 调整:播放中隐藏“刷新图传”,左上只显示小绿点和“实时图传”;首帧前/失败不显示实时标识,无画面时保留显式重试。拍摄完成面板使用浅绿圆形勾、右侧标题与说明、下方整行带图片图标的“查看素材”,移除该面板内的设备摘要和“详情”。“正在返航”仅在当前设备明确返回返航状态时显示;素材处理中不宣告素材已就绪。任务初次读取时也保留已校验召唤回执的“无人机正在赶来”。 + +本段日志最后是 `status=40` / `wayline_status=39` / `result_code=wayline_39`,后端明确报“上传媒体资源出错”。完成面板不覆盖后续失败状态;具体上传失败原因仍需后端核查。WebSocket 本段仍仅见 Opened 与发送 310,不能据此认定订阅/推送成功。 + +验证:本轮共 107 项不同相关用例最终通过,覆盖简洁图传标识、首帧/失败与切源、完成态及失败态切换、当前订单素材跳转、防重与刷新禁用、首份读取期间的前往回执;另在真实模拟器窗口内复核 375/402 点宽完成面板的图文居中和操作尺寸,截图无重叠。首轮旧来源标识断言及改用 UIButton.Configuration 后的旧标题读取断言已同步更新并重测。结果包为 `test_sim_2026-11-03T06-43-42-509Z_pid38943_c7ead8cc.xcresult`、`test_sim_2026-11-03T06-46-41-073Z_pid38943_2fe4d45b.xcresult`,最终单项复测分别为 `test_sim_2026-11-03T06-48-30-678Z_pid38943_68f5cd2f.xcresult`、`test_sim_2026-11-03T06-49-56-081Z_pid38943_b343e4e5.xcresult`。Release 无签名编译通过,日志 `/private/tmp/suixinkan-task-prototype-final-release-build.log`。全部验证使用隔离替身,不连接真实飞控或图传;该轮尚未包含 App 本地数字倒计时,后续实现见本页顶部最新约定。 + +## 2026-11-03:准备页电量与“无人机正在赶来” + +本节依据用户提供的任务 7 / 航线任务 2417 日志及 Downloads 中朱工最新版接口文档;没有由代理执行真实设备请求。 + +- 准备页 `plane-status` 的服务原已请求 `live_battery=1`,但网络保护对 Debug/Release 一律改为 0。这次日志的推荐设备 `battery_percent=null`、`battery_label=""`,因此没有电量可展示。现按用户要求,仅 Release 准备页保留实时电量参数;Debug 继续读缓存,任务页 `shooting=0` 和 `status` 的 `live_metrics=0` 不变。底栏在 `status_text` 只有工作状态时补充返回的电量字段,真实 0% 可显示,不编造缺失读数。 +- 13:42:53 `shoot` 返回 `accepted=true`、`ui.phase=going_to_spot`;13:42:55 首份 `shooting` 已返回 `arrived_pending_start`、`execute_gate.can_execute=true`。客户端直接显示到达的依据是这份后端快照,并非根据任务状态 20 推断。 +- 现将匹配任务、订单和景区的前往回执带入页面,首份状态返回前显示“无人机正在赶来”,不开放开拍或伪造完整快照。后续 HTTP/WS 前往阶段使用同一文案,收到明确到达状态才切换,不增加人为最低等待时间。 + +**给朱工的核查事项(未发送):**现有 `going_to_spot` / `arrived_pending_start` 已足够区分界面阶段,无需为文案新增接口。如果现场在 13:42:55 尚未到达,请核查航线任务 2417 的到达首点判定。文档写明 `RealtimeChecker` 根据 `paused_at` 更新阶段,应确认该值来自本次航线执行、确为首点到达等待开拍,而非起飞前暂停、旧设备/旧批次缓存或一般暂停;HTTP、WS 和 `execute_gate` 应使用同一可信判定。仅业务受理、订单任务 20 或航线状态 20 均不能作为到达依据。若底层拿不到可靠到达事件,应保持前往/待确认且禁止开拍,再补充可靠的到达来源;可补充批次绑定的 `arrived_at` / 原因供诊断,但 App 无法从现有快照独立验证物理到达。根因待朱工核实,不能仅凭两秒间隔断定具体哪条判断有误。 + +验证:137 项相关模拟器测试全部通过,覆盖电量补充与去重、真实零值、缺失/越界值、首次前往回执的身份校验、读取失败和后续到达切换、准备页及任务页生命周期。结果包 `test_sim_2026-11-03T06-14-43-559Z_pid38943_55e0a9b1.xcresult`。另以仅构造 URLRequest 的隔离检查分别验证 Debug/Release 各 10 项网络策略,未创建任何网络传输。Release 无签名编译通过,日志 `/private/tmp/suixinkan-battery-arrival-release-build.log`;实际电量与物理到达由用户后续真机复测,未记为真实联调成功。 + +## 2026-11-03:图传无画面排查与录制完成交互 + +用户提供任务 7 / 批次 2417 的运行日志:首次 live 只有机巢可用,约 34 秒后机巢、无人机均返回火山参数;可用凭证不等于已收到视频帧。13:46:30 的 shooting 首次进入 post_shoot_uploading,航线为 24,订单任务仍为 20;13:47:59 转为航线 30。日志末尾仍未素材就绪,不能认定上传已完成。 + +- 修正接收端首帧等待超时误走致命失败的问题:超时只开放第二路,保留房间等待晚到的视频发布。订阅按新版 SDK 返回的 streamId,不再额外要求 streamIndex 为 0。SDK 入房/订阅失败在页面保留错误码;不增加控制台事件噪声。 +- live 补流会生成新 user_id,原入房凭证未临期时保留当前房间;新无人机参数独立增补,临期再换身份。SDK 适配器和接收协调器分离,后者可直接用内存房间验证,不初始化 SDK。 +- 按用户最新产品要求,可信 post_shoot_uploading 即提示“拍摄已完成”,显示原型样式的“稍后再去 / 去查看”弹窗;去查看进入当前订单素材库查看上传进度,不修改状态、扣次或伪造就绪。此约定覆盖下表旧的任务页上传文案。 +- 录制结束后释放本地 RTC、取消 live 补流/续期及在途请求,覆盖静态点位封面;缺少封面时使用中性图案。重复包、前后台及旧播放回调不能恢复图传。打开已有结束任务时先读 shooting,不先启动 live。 +- 本段日志的 WebSocket 只有 Opened 与已发送的 310,未见订阅 ack 或完整推送;HTTP 兜底持续更新。尚不能确认服务端订阅成功,且该状态通道不承载 RTC 视频。 + +验证仅使用模拟器、隔离网络及 RTC 房间替身和无签名 Release 编译;不复用日志凭证,不调用真实 live 或飞控。真实设备视频效果仍需用户复测。 + +验证结果:共 93 项不同相关用例最终通过;首轮 91 项中一项旧按钮文案断言早于动画结束,补充等待后受影响的 51 项(含新增两项)全部通过。结果包分别为 `test_sim_2026-11-03T06-02-18-041Z_pid38943_bb5083a4.xcresult`、`test_sim_2026-11-03T06-06-15-587Z_pid38943_daa4cc56.xcresult`。后者保留完成弹窗/封面截图,已核对无文字重叠。Release 无签名编译通过,日志 `/private/tmp/suixinkan-recording-completion-release-build.log`。 + ## 2026-11-03:朱工 WebSocket 订阅顺序与拍摄后上传阶段 依据 Downloads 中最新版《随心瞰9.9.1-App机巢与素材库接口.md》§9.1 和朱工补充说明。以下为协议示意与本地模拟验证范围,不代表真实环境已完成联调。 @@ -35,7 +146,7 @@ | 后端阶段 | 订单任务状态 | App 显示及操作 | | --- | --- | --- | | `shooting` / wayline 20 | 20 | 正在拍摄 | -| `post_shoot_uploading` / wayline 24、30、40 | 20,finished_at 可有值 | 拍摄完毕上传中;采用后端标题/说明,提供刷新,不提供开拍、重召唤或已完成素材入口 | +| `post_shoot_uploading` / wayline 24、30、40 | 20,finished_at 可有值 | 按最新产品要求显示拍摄已完成并提示前往订单素材库;停止本机图传,不提供开拍或重召唤,不宣告素材就绪 | | `completed` / wayline 50 | 30 | 素材就绪,显示查看素材 | `execute_gate.can_execute=false` 仅表示不能再次开拍,不能覆盖明确的上传阶段。也不以 finished_at 判断素材就绪;真正失败、取消和矛盾字段仍按原有保守规则处理。新阶段沿用任务页中间固定区域,顶部图传/读数和底部安全模块位置不变。