diff --git a/crates/server/src/host/workspace_files.rs b/crates/server/src/host/workspace_files.rs index f016c924b..67f7ae6a9 100644 --- a/crates/server/src/host/workspace_files.rs +++ b/crates/server/src/host/workspace_files.rs @@ -167,9 +167,11 @@ impl ServerApplicationDomains { return Ok(Value::Array(Vec::new())); } let root = self.primary_worktree(args.workspace_id, None).await?; + let root_for_untracked = root.clone(); let mut diffs = self.git_read(root, git::GitService::get_file_diffs).await?; if let Some(entries) = diffs.as_array_mut() { for entry in entries { + populate_missing_diff(&root_for_untracked, entry); bound_diff(entry); } } @@ -177,6 +179,64 @@ impl ServerApplicationDomains { } } +/// Populates a synthetic unified diff (`@@ -0,0 +1,N @@`) for untracked (`?`) or newly added (`A`) +/// text files whose `diff` payload from `git diff HEAD` is empty, so Companion devices can always +/// display their line-by-line additions. +fn populate_missing_diff(root: &Path, entry: &mut Value) { + let Some(object) = entry.as_object_mut() else { + return; + }; + let is_binary = object + .get("is_binary") + .and_then(Value::as_bool) + .unwrap_or(false); + if is_binary { + return; + } + let diff_empty = object + .get("diff") + .and_then(Value::as_str) + .map(|s| s.trim().is_empty()) + .unwrap_or(true); + if !diff_empty { + return; + } + let status = object.get("status").and_then(Value::as_str).unwrap_or(""); + if status == "D" { + return; + } + let Some(path) = object.get("path").and_then(Value::as_str) else { + return; + }; + let Ok(file) = read_text_file(root, path) else { + return; + }; + if file.binary { + object.insert("is_binary".to_string(), Value::Bool(true)); + return; + } + let Some(content) = file.content else { + return; + }; + let mut lines: Vec<&str> = content.split('\n').collect(); + if lines.last() == Some(&"") { + lines.pop(); + } + if lines.is_empty() { + return; + } + let mut synth = format!("@@ -0,0 +1,{} @@\n", lines.len()); + for line in lines { + synth.push('+'); + synth.push_str(line.trim_end_matches('\r')); + synth.push('\n'); + if synth.len() > MAX_DIFF_BYTES { + break; + } + } + object.insert("diff".to_string(), Value::String(synth)); +} + /// Keeps a phone-sized payload: an oversized diff is cut at a line boundary and flagged. fn bound_diff(entry: &mut Value) { let Some(object) = entry.as_object_mut() else { @@ -205,11 +265,19 @@ fn forbidden(reason: &str) -> ApplicationError { const VISIBLE_DOT_NAMES: &[&str] = &[ ".github", ".vscode", + ".claude", + ".agents", + ".cursor", + ".codex", + ".vibex-plugin", ".gitignore", ".gitattributes", ".editorconfig", ".prettierrc", ".eslintrc", + ".babelrc", + ".npmrc", + ".yarnrc", ".nvmrc", ".node-version", ]; diff --git a/mobile/ios/App/CompanionAttentionCenter.swift b/mobile/ios/App/CompanionAttentionCenter.swift index 9066deba7..3667d6108 100644 --- a/mobile/ios/App/CompanionAttentionCenter.swift +++ b/mobile/ios/App/CompanionAttentionCenter.swift @@ -52,7 +52,7 @@ struct CompanionAttentionToast: Identifiable, Equatable { @MainActor @Observable -final class CompanionAttentionCenter { +final class CompanionAttentionCenter: NSObject, UNUserNotificationCenterDelegate { var activeToast: CompanionAttentionToast? var pendingNavigationConversation: ConversationListItem? var actionBusy = false @@ -61,18 +61,133 @@ final class CompanionAttentionCenter { @ObservationIgnored private var eventsByConversation: [String: [RemoteEvent]] = [:] @ObservationIgnored private var lastSequenceByConversation: [String: Int64] = [:] @ObservationIgnored private var sessionsByConversation: [String: SessionState] = [:] + @ObservationIgnored private var conversationsByID: [String: ConversationListItem] = [:] @ObservationIgnored private var wasRunningByConversation: [String: Bool] = [:] @ObservationIgnored private var initializedConversations: Set = [] @ObservationIgnored private var handledEventIDs: Set = [] @ObservationIgnored private var didRequestNotificationPermission = false + @ObservationIgnored private var currentClient: HostClient? + @ObservationIgnored private var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid + @ObservationIgnored private var lifecycleObservers: [NSObjectProtocol] = [] + + override init() { + super.init() + setupNotificationCategoriesAndDelegate() + setupBackgroundKeepAliveObservers() + } + + private func setupNotificationCategoriesAndDelegate() { + let center = UNUserNotificationCenter.current() + center.delegate = self + + let allowOnce = UNNotificationAction( + identifier: "VIBEX_ALLOW_ONCE", + title: "允许本次", + options: [.authenticationRequired] + ) + let allowSession = UNNotificationAction( + identifier: "VIBEX_ALLOW_SESSION", + title: "本会话允许", + options: [.authenticationRequired] + ) + let rejectPerm = UNNotificationAction( + identifier: "VIBEX_REJECT_PERM", + title: "拒绝", + options: [.destructive] + ) + let permCategory = UNNotificationCategory( + identifier: "VIBEX_PERMISSION_CATEGORY", + actions: [allowOnce, allowSession, rejectPerm], + intentIdentifiers: [], + options: [.customDismissAction] + ) + + let confirmQuestion = UNNotificationAction( + identifier: "VIBEX_CONFIRM_QUESTION", + title: "批准执行", + options: [.authenticationRequired] + ) + let replyQuestion = UNTextInputNotificationAction( + identifier: "VIBEX_REPLY_QUESTION", + title: "快捷回复…", + options: [.authenticationRequired], + textInputButtonTitle: "发送", + textInputPlaceholder: "输入给 Agent 的回复…" + ) + let rejectQuestion = UNNotificationAction( + identifier: "VIBEX_REJECT_QUESTION", + title: "拒绝", + options: [.destructive] + ) + let questionCategory = UNNotificationCategory( + identifier: "VIBEX_QUESTION_CATEGORY", + actions: [confirmQuestion, replyQuestion, rejectQuestion], + intentIdentifiers: [], + options: [.customDismissAction] + ) + + let openSession = UNNotificationAction( + identifier: "VIBEX_OPEN_SESSION", + title: "打开对话", + options: [.foreground] + ) + let completedCategory = UNNotificationCategory( + identifier: "VIBEX_COMPLETED_CATEGORY", + actions: [openSession], + intentIdentifiers: [], + options: [] + ) + + center.setNotificationCategories([permCategory, questionCategory, completedCategory]) + } + + private func setupBackgroundKeepAliveObservers() { + let bgObs = NotificationCenter.default.addObserver( + forName: UIApplication.didEnterBackgroundNotification, + object: nil, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + self?.beginBackgroundPollingGuard() + } + } + let fgObs = NotificationCenter.default.addObserver( + forName: UIApplication.willEnterForegroundNotification, + object: nil, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + self?.endBackgroundPollingGuard() + } + } + lifecycleObservers = [bgObs, fgObs] + } + + private func beginBackgroundPollingGuard() { + guard backgroundTaskID == .invalid else { return } + backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "VibeXBackgroundAttentionMonitor") { [weak self] in + Task { @MainActor in + self?.endBackgroundPollingGuard() + } + } + } + + private func endBackgroundPollingGuard() { + guard backgroundTaskID != .invalid else { return } + UIApplication.shared.endBackgroundTask(backgroundTaskID) + backgroundTaskID = .invalid + } func requestNotificationPermissionIfNeeded() { guard !didRequestNotificationPermission else { return } didRequestNotificationPermission = true - UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { _, _ in } + UNUserNotificationCenter.current().requestAuthorization( + options: [.alert, .sound, .badge] + ) { _, _ in } } func poll(client: HostClient) async { + currentClient = client requestNotificationPermissionIfNeeded() async let conversationsTask = try? client.call( @@ -96,7 +211,10 @@ final class CompanionAttentionCenter { } let candidates = Array(conversations.prefix(6)) + var syncedLiveActivityInThisPoll = false + for conv in candidates { + conversationsByID[conv.id] = conv let isFirstSnapshot = !initializedConversations.contains(conv.id) let previouslyRunning = wasRunningByConversation[conv.id] ?? false let seq = lastSequenceByConversation[conv.id] ?? 0 @@ -124,6 +242,33 @@ final class CompanionAttentionCenter { $0.isEmpty ? nil : $0 } ?? "未命名对话" + let hasPendingApproval = !state.pendingPermissions.isEmpty || !state.pendingQuestions.isEmpty + if !syncedLiveActivityInThisPoll && (state.isTurnRunning || hasPendingApproval) { + syncedLiveActivityInThisPoll = true + let approvalSummary: String? = if let perm = state.pendingPermissions.first { + perm.title + } else if let q = state.pendingQuestions.first { + Self.questionSummary(q, fallback: "等待确认执行方案") + } else { + nil + } + let recentToolKind = Self.inferLatestToolKind(from: allEvents) + let stepCount = max(1, allEvents.count / 6) + TaskActivityController.shared.sync( + conversationID: conv.id, + projectName: project, + title: sessionTitle, + tasks: [], + latestToolName: recentToolKind, + stepCount: stepCount, + hasThinking: true, + hasTextOutput: false, + hasPendingApproval: hasPendingApproval, + approvalSummary: approvalSummary, + running: state.isTurnRunning + ) + } + // Auto-clear active toast if its permission/question was resolved on desktop or detail view if let current = activeToast, current.conversation.id == conv.id { switch current.kind { @@ -194,6 +339,7 @@ final class CompanionAttentionCenter { handledEventIDs.insert(eventKey) if lastTerminal.kind == "turn_failed" { let err = Self.extractFailureMessage(from: lastTerminal.payload) + TaskActivityController.shared.finish(failedMessage: err) presentToast( CompanionAttentionToast( id: eventKey, @@ -206,6 +352,7 @@ final class CompanionAttentionCenter { ) ) } else { + TaskActivityController.shared.finish() presentToast( CompanionAttentionToast( id: eventKey, @@ -223,6 +370,7 @@ final class CompanionAttentionCenter { let eventKey = "done:\(conv.id):\(confirmedSeq)" if !handledEventIDs.contains(eventKey) { handledEventIDs.insert(eventKey) + TaskActivityController.shared.finish() presentToast( CompanionAttentionToast( id: eventKey, @@ -240,6 +388,22 @@ final class CompanionAttentionCenter { } } + private static func inferLatestToolKind(from events: [RemoteEvent]) -> String? { + for event in events.suffix(12).reversed() { + if case let .object(dict) = event.payload { + if case let .string(tool)? = dict["tool_name"] ?? dict["name"] ?? dict["title"] { + return tool + } + if case let .object(data)? = dict["data"], + case let .string(tool)? = data["tool_name"] ?? data["name"] ?? data["title"] + { + return tool + } + } + } + return nil + } + private static func extractFailureMessage(from payload: JSONValue) -> String { if case let .object(dict) = payload { if case let .string(err)? = dict["error"], !err.isEmpty { return err } @@ -421,7 +585,33 @@ final class CompanionAttentionCenter { content.title = toast.title content.body = toast.subtitle content.sound = .default - content.userInfo = ["conversationId": toast.conversation.id] + content.interruptionLevel = .timeSensitive + content.relevanceScore = 1.0 + + var info: [String: String] = [ + "conversationId": toast.conversation.id, + "projectName": toast.projectName, + ] + switch toast.kind { + case let .permission(prompt): + content.categoryIdentifier = "VIBEX_PERMISSION_CATEGORY" + info["permissionId"] = prompt.id + if let allowOnce = prompt.resolveAllowOption(for: .once)?.id { + info["allowOnceOptionId"] = allowOnce + } + if let allowSession = prompt.resolveAllowOption(for: .session)?.id { + info["allowSessionOptionId"] = allowSession + } + if let reject = prompt.rejectOption?.id { + info["rejectOptionId"] = reject + } + case let .question(question): + content.categoryIdentifier = "VIBEX_QUESTION_CATEGORY" + info["questionId"] = question.id + case .completed, .failed: + content.categoryIdentifier = "VIBEX_COMPLETED_CATEGORY" + } + content.userInfo = info let request = UNNotificationRequest( identifier: "vibex.attention.\(toast.id)", @@ -430,6 +620,113 @@ final class CompanionAttentionCenter { ) UNUserNotificationCenter.current().add(request) } + + nonisolated func userNotificationCenter( + _ center: UNUserNotificationCenter, + willPresent notification: UNNotification, + withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void + ) { + // When app is in foreground we already show CompanionToastOverlay; only play sound/list + completionHandler([.list]) + } + + nonisolated func userNotificationCenter( + _ center: UNUserNotificationCenter, + didReceive response: UNNotificationResponse, + withCompletionHandler completionHandler: @escaping () -> Void + ) { + let userInfo = response.notification.request.content.userInfo + let convID = userInfo["conversationId"] as? String + let permID = userInfo["permissionId"] as? String + let allowOnceID = userInfo["allowOnceOptionId"] as? String + let allowSessionID = userInfo["allowSessionOptionId"] as? String + let rejectID = userInfo["rejectOptionId"] as? String + let questionID = userInfo["questionId"] as? String + let actionID = response.actionIdentifier + let textReply = (response as? UNTextInputNotificationResponse)?.userText + + Task { @MainActor in + guard let convID else { + completionHandler() + return + } + if let client = self.currentClient { + switch actionID { + case "VIBEX_ALLOW_ONCE": + if let permID { + try? await client.respondPermission( + conversationID: convID, + permissionID: permID, + optionID: allowOnceID + ) + self.dismiss() + } + case "VIBEX_ALLOW_SESSION": + if let permID { + try? await client.respondPermission( + conversationID: convID, + permissionID: permID, + optionID: allowSessionID ?? allowOnceID + ) + self.dismiss() + } + case "VIBEX_REJECT_PERM": + if let permID { + try? await client.respondPermission( + conversationID: convID, + permissionID: permID, + optionID: rejectID + ) + self.dismiss() + } + case "VIBEX_CONFIRM_QUESTION": + if let questionID, + let state = self.sessionsByConversation[convID], + let q = state.pendingQuestions.first(where: { $0.id == questionID }) + { + let forms = QuestionForm.questions(for: q) + let firstChoice = forms.first?.choices.first + await self.respondQuestion( + client: client, + conversationID: convID, + question: q, + choice: firstChoice, + fallbackText: firstChoice == nil ? "Yes" : nil + ) + } + case "VIBEX_REPLY_QUESTION": + if let questionID, + let textReply, + !textReply.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + let state = self.sessionsByConversation[convID], + let q = state.pendingQuestions.first(where: { $0.id == questionID }) + { + await self.respondQuestion( + client: client, + conversationID: convID, + question: q, + choice: nil, + fallbackText: textReply + ) + } + case "VIBEX_REJECT_QUESTION": + if let questionID { + try? await client.respondQuestion( + conversationID: convID, + questionID: questionID, + content: nil + ) + self.dismiss() + } + default: + if let conv = self.conversationsByID[convID] { + self.openConversation(conv) + } + } + } + completionHandler() + } + } } struct CompanionToastOverlay: View { diff --git a/mobile/ios/App/ConversationDetailView.swift b/mobile/ios/App/ConversationDetailView.swift index 9496c73c2..10a6e9868 100644 --- a/mobile/ios/App/ConversationDetailView.swift +++ b/mobile/ios/App/ConversationDetailView.swift @@ -9,6 +9,19 @@ struct ConversationDetailView: View { @State private var created: ConversationListItem? @State private var diffChange: FileChangeItem? + // Scroll safe-zone & floating bottom indicator state + @State private var distanceFromBottom: CGFloat = 0 + @State private var userDetachedFromBottom = false + @State private var isUserDraggingScroll = false + @State private var unreadMessageUpdates = 0 + @State private var hasPerformedInitialScroll = false + + private let bottomSafeZoneThreshold: CGFloat = 56 + + private var isInBottomSafeZone: Bool { + !userDetachedFromBottom && !isUserDraggingScroll && distanceFromBottom <= bottomSafeZoneThreshold + } + var onToggleSidebar: (() -> Void)? var onReturnToLanding: (() -> Void)? @@ -255,6 +268,8 @@ struct ConversationDetailView: View { openFiles: { panel = .files }, send: { let text = draft + userDetachedFromBottom = false + unreadMessageUpdates = 0 Task { if await model.send(text) { draft = "" } } }, stop: { Task { await model.cancelTurn() } }, @@ -340,47 +355,143 @@ struct ConversationDetailView: View { if model.items.isEmpty { ContentUnavailableView("还没有消息", systemImage: "text.bubble") } else { - ScrollViewReader { proxy in - ScrollView { - LazyVStack(alignment: .leading, spacing: 16) { - ForEach(model.items) { item in - MessageRow( - item: item, - agentID: model.conversation.agent_id, - modelName: model.currentModelLabel, - isLast: item.id == model.items.last?.id, - running: model.session.isTurnRunning, - openDiff: { diffChange = $0 } + GeometryReader { scrollGeo in + let containerWidth = max(0, scrollGeo.size.width) + let viewportHeight = max(0, scrollGeo.size.height) + let contentWidth = max(0, containerWidth - 28) + ScrollViewReader { proxy in + ZStack(alignment: .bottom) { + ScrollView(.vertical, showsIndicators: true) { + VStack(alignment: .leading, spacing: 16) { + ForEach(model.items) { item in + MessageRow( + item: item, + agentID: model.conversation.agent_id, + modelName: model.currentModelLabel, + isLast: item.id == model.items.last?.id, + running: model.session.isTurnRunning, + openDiff: { diffChange = $0 } + ) + .frame(width: contentWidth, alignment: .leading) + .id(item.id) + } + if model.session.isTurnRunning && model.items.last?.role != .assistant { + LoadingState(label: "正在思考").id("loading") + } + Color.clear + .frame(height: 1) + .id("conversation-bottom") + } + .padding(.horizontal, 14) + .padding(.vertical, 12) + .frame(width: containerWidth, alignment: .leading) + .background( + GeometryReader { contentGeo in + let frame = contentGeo.frame(in: .named("conversationScroll")) + let rawDist = max(0, frame.maxY - viewportHeight) + Color.clear + .onAppear { + handleScrollMetrics( + distance: rawDist, + contentHeight: frame.height, + viewportHeight: viewportHeight + ) + } + .onChange(of: Int(rawDist.rounded())) { _, _ in + handleScrollMetrics( + distance: rawDist, + contentHeight: frame.height, + viewportHeight: viewportHeight + ) + } + } ) - .id(item.id) } - if model.session.isTurnRunning && model.items.last?.role != .assistant { - LoadingState(label: "正在思考").id("loading") + .coordinateSpace(name: "conversationScroll") + .scrollDismissesKeyboard(.interactively) + .simultaneousGesture( + DragGesture(minimumDistance: 5) + .onChanged { value in + isUserDraggingScroll = true + // Finger pulling down (positive translation.height) = scrolling upward away from bottom + if value.translation.height > 10 { + if !userDetachedFromBottom { + userDetachedFromBottom = true + } + } else if value.translation.height < -18 && distanceFromBottom <= bottomSafeZoneThreshold { + userDetachedFromBottom = false + unreadMessageUpdates = 0 + } + } + .onEnded { value in + isUserDraggingScroll = false + if value.translation.height > 14 { + userDetachedFromBottom = true + } else if value.translation.height < -24 && distanceFromBottom <= bottomSafeZoneThreshold { + userDetachedFromBottom = false + unreadMessageUpdates = 0 + } + } + ) + .onAppear { + scrollToBottomImmediately(proxy: proxy) } - Color.clear - .frame(height: 1) - .id("conversation-bottom") - } - .padding(.horizontal, 14) - .padding(.vertical, 12) - } - .scrollDismissesKeyboard(.interactively) - .onChange(of: model.items.count) { _, _ in - withAnimation(.smooth(duration: 0.22)) { - proxy.scrollTo("conversation-bottom", anchor: .bottom) - } - } - .onChange(of: model.items.last?.text.count) { _, _ in - if model.isActivelyStreaming { - proxy.scrollTo("conversation-bottom", anchor: .bottom) - } - } - .onChange(of: model.items.last?.segments.count) { _, _ in - if model.isActivelyStreaming { - withAnimation(.smooth(duration: 0.18)) { - proxy.scrollTo("conversation-bottom", anchor: .bottom) + .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in + Task { + await model.reload() + if isInBottomSafeZone { + proxy.scrollTo("conversation-bottom", anchor: .bottom) + } + } + } + .onReceive(NotificationCenter.default.publisher(for: Notification.Name("vibex.didReturnToConversationsTab"))) { _ in + Task { + await model.reload() + if isInBottomSafeZone { + proxy.scrollTo("conversation-bottom", anchor: .bottom) + } + } + } + .onChange(of: model.items.count) { oldCount, newCount in + guard newCount > oldCount else { return } + if !hasPerformedInitialScroll { + scrollToBottomImmediately(proxy: proxy) + } else if isInBottomSafeZone { + withAnimation(.smooth(duration: 0.2)) { + proxy.scrollTo("conversation-bottom", anchor: .bottom) + } + } else { + unreadMessageUpdates += max(1, newCount - oldCount) + } + } + .onChange(of: model.items.last?.text.count) { _, _ in + guard model.isActivelyStreaming else { return } + if isInBottomSafeZone { + proxy.scrollTo("conversation-bottom", anchor: .bottom) + } else if unreadMessageUpdates == 0 { + unreadMessageUpdates = 1 + } + } + .onChange(of: model.items.last?.segments.count) { oldSegs, newSegs in + guard model.isActivelyStreaming else { return } + if isInBottomSafeZone { + withAnimation(.smooth(duration: 0.16)) { + proxy.scrollTo("conversation-bottom", anchor: .bottom) + } + } else if (newSegs ?? 0) > (oldSegs ?? 0) { + unreadMessageUpdates += 1 + } + } + + if shouldShowScrollToBottomButton { + scrollToBottomButton(proxy: proxy) + .padding(.bottom, 12) + .transition(.scale(scale: 0.88, anchor: .bottom).combined(with: .opacity)) + .zIndex(10) } } + .animation(.spring(response: 0.24, dampingFraction: 0.84), value: shouldShowScrollToBottomButton) + .animation(.spring(response: 0.24, dampingFraction: 0.84), value: unreadMessageUpdates) } } } @@ -390,6 +501,109 @@ struct ConversationDetailView: View { ProgressView().frame(maxHeight: .infinity) } } + + private func handleScrollMetrics( + distance: CGFloat, + contentHeight: CGFloat, + viewportHeight: CGFloat + ) { + guard viewportHeight > 0 else { return } + distanceFromBottom = distance + if contentHeight <= viewportHeight + 20 { + if userDetachedFromBottom && !isUserDraggingScroll { + userDetachedFromBottom = false + unreadMessageUpdates = 0 + } + return + } + if distance <= 36 && !isUserDraggingScroll { + if userDetachedFromBottom { + userDetachedFromBottom = false + } + if unreadMessageUpdates != 0 { + unreadMessageUpdates = 0 + } + } else if distance > bottomSafeZoneThreshold { + if !userDetachedFromBottom { + userDetachedFromBottom = true + } + } + } + + private var shouldShowScrollToBottomButton: Bool { + userDetachedFromBottom || distanceFromBottom > bottomSafeZoneThreshold || unreadMessageUpdates > 0 + } + + private func scrollToBottomImmediately(proxy: ScrollViewProxy) { + userDetachedFromBottom = false + unreadMessageUpdates = 0 + proxy.scrollTo("conversation-bottom", anchor: .bottom) + Task { @MainActor in + try? await Task.sleep(for: .milliseconds(50)) + if !userDetachedFromBottom { + proxy.scrollTo("conversation-bottom", anchor: .bottom) + } + try? await Task.sleep(for: .milliseconds(120)) + if !userDetachedFromBottom { + proxy.scrollTo("conversation-bottom", anchor: .bottom) + hasPerformedInitialScroll = true + } + } + } + + @ViewBuilder + private func scrollToBottomButton(proxy: ScrollViewProxy) -> some View { + let showExtendedLabel = unreadMessageUpdates > 0 || model.session.isTurnRunning || distanceFromBottom > 180 + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + userDetachedFromBottom = false + isUserDraggingScroll = false + distanceFromBottom = 0 + unreadMessageUpdates = 0 + withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { + proxy.scrollTo("conversation-bottom", anchor: .bottom) + } + } label: { + HStack(spacing: 6) { + if model.session.isTurnRunning || unreadMessageUpdates > 0 { + Circle() + .fill(Color.orange) + .frame(width: 7, height: 7) + } + + if showExtendedLabel { + if unreadMessageUpdates > 0 { + Text("\(unreadMessageUpdates) 条新动态") + .font(.system(size: 12.5, weight: .semibold)) + .monospacedDigit() + } else if model.session.isTurnRunning { + Text("跟随最新回答") + .font(.system(size: 12.5, weight: .semibold)) + } else { + Text("回到底部") + .font(.system(size: 12.5, weight: .medium)) + } + } + + Image(systemName: "arrow.down") + .font(.system(size: 13, weight: .bold)) + } + .foregroundStyle(.primary) + .padding(.horizontal, showExtendedLabel ? 14 : 11) + .frame(height: 36) + .background( + Capsule(style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + .overlay( + Capsule(style: .continuous) + .strokeBorder(Color.accentColor.opacity(0.35), lineWidth: 1) + ) + .shadow(color: .black.opacity(0.24), radius: 10, x: 0, y: 4) + } + .buttonStyle(.plain) + .accessibilityLabel("滚动到最底部") + } } extension String: @retroactive Identifiable { diff --git a/mobile/ios/App/ConversationModel.swift b/mobile/ios/App/ConversationModel.swift index d9a138260..64c81066a 100644 --- a/mobile/ios/App/ConversationModel.swift +++ b/mobile/ios/App/ConversationModel.swift @@ -10,7 +10,7 @@ final class ConversationModel { private(set) var items: [TimelineItem] = [] private var transcript: TranscriptState - private let activity = TaskActivityController() + private let activity = TaskActivityController.shared private var events: [RemoteEvent] = [] private var lastSequence: Int64 = 0 private(set) var session = SessionState() @@ -82,13 +82,38 @@ final class ConversationModel { } await applyLiveControls() if agents.isEmpty { await refreshCatalog() } - let step = items.last?.tools.last.map { tool in - tool.preview.map { "\(tool.name) \($0)" } ?? tool.name + let lastAssistant = items.last { $0.role == .assistant } + let latestToolName = lastAssistant?.tools.last?.name + let totalSteps = (lastAssistant?.tools.count ?? 0) + (lastAssistant?.thinking.isEmpty == false ? 1 : 0) + let hasPendingApproval = !session.pendingPermissions.isEmpty || !session.pendingQuestions.isEmpty + let approvalSummary: String? = if let perm = session.pendingPermissions.first { + perm.title + } else if let q = session.pendingQuestions.first { + q.prompt + } else { + nil } - activity.sync(title: conversation.title ?? "对话", tasks: items.currentPlan, step: step, running: session.isTurnRunning) + activity.sync( + conversationID: conversation.id, + projectName: "VibeX", + title: conversation.title ?? "未命名对话", + tasks: items.currentPlan, + latestToolName: latestToolName, + stepCount: totalSteps, + hasThinking: !(lastAssistant?.thinking.isEmpty ?? true), + hasTextOutput: !(lastAssistant?.text.isEmpty ?? true), + hasPendingApproval: hasPendingApproval, + approvalSummary: approvalSummary, + running: session.isTurnRunning + ) } - func stopActivity() { activity.stop() } + func stopActivity() { + // Keep Live Activity alive in the Dynamic Island & Lock Screen if the turn is still running + if !session.isTurnRunning && session.pendingPermissions.isEmpty && session.pendingQuestions.isEmpty { + activity.stop() + } + } /// Brings the Agent session up (once per visit) so its modes and options exist even before the first message. private func applyLiveControls() async { diff --git a/mobile/ios/App/ConversationTools.swift b/mobile/ios/App/ConversationTools.swift index ba4f788f6..5737835b6 100644 --- a/mobile/ios/App/ConversationTools.swift +++ b/mobile/ios/App/ConversationTools.swift @@ -239,9 +239,11 @@ struct DiffListView: View { Text((diff.path as NSString).lastPathComponent).lineLimit(1) HStack(spacing: 8) { Text(label(for: diff.change)).foregroundStyle(.secondary) - if !diff.isBinary && diff.change != .untracked { + if !diff.isBinary && (diff.additions > 0 || diff.deletions > 0 || diff.change != .untracked) { Text("+\(diff.additions)").foregroundStyle(.green) - Text("−\(diff.deletions)").foregroundStyle(.red) + if diff.deletions > 0 || diff.change != .untracked { + Text("−\(diff.deletions)").foregroundStyle(.red) + } } Text(diff.path).foregroundStyle(.tertiary).lineLimit(1).truncationMode(.head) } @@ -280,20 +282,32 @@ struct DiffFileView: View { let diff: FileDiff @State private var hunks: [DiffHunk] @State private var loadingContent = false + @State private var isEmptyFile = false + @State private var detectedBinary = false + @State private var loadError: String? init(client: HostClient, workspaceID: String, diff: FileDiff) { self.client = client self.workspaceID = workspaceID self.diff = diff _hunks = State(initialValue: diff.hunks) + _loadingContent = State(initialValue: diff.needsContent && diff.hunks.isEmpty) + _detectedBinary = State(initialValue: diff.isBinary) } var body: some View { Group { - if diff.isBinary { - ContentUnavailableView("二进制文件没有文本差异", systemImage: "doc.zipper") - } else if hunks.isEmpty && !loadingContent { - ContentUnavailableView("没有可显示的文本差异", systemImage: "plus.forwardslash.minus") + if loadingContent { + ProgressView("正在读取文件变更…") + } else if detectedBinary { + ContentUnavailableView("二进制或图片资源文件,无文本行差异", systemImage: "doc.zipper") + } else if isEmptyFile { + ContentUnavailableView("这是一个空文件(0 行内容)", systemImage: "doc") + } else if hunks.isEmpty { + ContentUnavailableView( + loadError ?? "没有可显示的文本差异", + systemImage: "plus.forwardslash.minus" + ) } else { ScrollView([.vertical, .horizontal]) { LazyVStack(alignment: .leading, spacing: 0) { @@ -319,13 +333,28 @@ struct DiffFileView: View { .navigationTitle((diff.path as NSString).lastPathComponent) .navigationBarTitleDisplayMode(.inline) .task { - guard diff.needsContent, hunks.isEmpty else { return } + guard diff.needsContent, hunks.isEmpty else { + loadingContent = false + return + } loadingContent = true defer { loadingContent = false } - if let file = try? await client.workspaceFile(workspaceID: workspaceID, path: diff.path), - let content = file.content - { - hunks = FileDiff.additions(of: content) + do { + let file = try await client.workspaceFile(workspaceID: workspaceID, path: diff.path) + if file.binary { + detectedBinary = true + } else if let content = file.content { + let parsed = FileDiff.additions(of: content) + if parsed.isEmpty { + isEmptyFile = true + } else { + hunks = parsed + } + } else { + isEmptyFile = file.size == 0 + } + } catch { + loadError = describeHostFailure(error) } } } diff --git a/mobile/ios/App/ConversationsView.swift b/mobile/ios/App/ConversationsView.swift index 3b63947da..f75e60c01 100644 --- a/mobile/ios/App/ConversationsView.swift +++ b/mobile/ios/App/ConversationsView.swift @@ -21,6 +21,7 @@ struct ConversationsView: View { let client: HostClient var onChromeHiddenChange: ((Bool) -> Void)? = nil var onLaunchRevealedChange: ((Bool) -> Void)? = nil + var onSelectTab: ((AppTab) -> Void)? = nil @Environment(CompanionAttentionCenter.self) private var attentionCenter: CompanionAttentionCenter? @State private var list = RemoteList() @@ -212,18 +213,15 @@ struct ConversationsView: View { } .onAppear { consumePendingNavigationIfNeeded() - onChromeHiddenChange?(activeConversation != nil || isSidebarOpen) + onChromeHiddenChange?(isSidebarOpen) if !launchLogoEntered { withAnimation(.easeOut(duration: 0.36)) { launchLogoEntered = true } } } - .onChange(of: activeConversation) { _, _ in - onChromeHiddenChange?(activeConversation != nil || isSidebarOpen) - } .onChange(of: isSidebarOpen) { _, _ in - onChromeHiddenChange?(activeConversation != nil || isSidebarOpen) + onChromeHiddenChange?(isSidebarOpen) } .onChange(of: attentionCenter?.pendingNavigationConversation) { _, _ in consumePendingNavigationIfNeeded() @@ -557,6 +555,31 @@ struct ConversationsView: View { .refreshable { await reload() } + + Divider().opacity(0.45) + + HStack(spacing: 4) { + sidebarQuickNavButton(title: "新工作台", icon: "sparkles") { + withAnimation(.spring(response: 0.26, dampingFraction: 0.86)) { + activeConversation = nil + isSidebarOpen = false + } + } + sidebarQuickNavButton(title: "看板", icon: "square.grid.2x2") { + isSidebarOpen = false + onSelectTab?(.board) + } + sidebarQuickNavButton(title: "协作空间", icon: "person.2") { + isSidebarOpen = false + onSelectTab?(.space) + } + sidebarQuickNavButton(title: "设置", icon: "gearshape") { + isSidebarOpen = false + onSelectTab?(.settings) + } + } + .padding(.horizontal, 10) + .padding(.vertical, 8) } .frame(width: 304) .frame(maxHeight: .infinity) @@ -573,6 +596,32 @@ struct ConversationsView: View { .shadow(color: .black.opacity(0.18), radius: 18, x: 5, y: 0) } + private func sidebarQuickNavButton( + title: String, + icon: String, + action: @escaping () -> Void + ) -> some View { + Button(action: action) { + VStack(spacing: 4) { + Image(systemName: icon) + .font(.system(size: 14.5, weight: .medium)) + .frame(height: 18) + Text(title) + .font(.system(size: 10.5, weight: .medium)) + .lineLimit(1) + } + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity) + .padding(.vertical, 6) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color(.tertiarySystemFill).opacity(0.65)) + ) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + // MARK: Sidebar Tab 1: 最近对话 private var sidebarConversationsContent: some View { diff --git a/mobile/ios/App/PairView.swift b/mobile/ios/App/PairView.swift index aa1b8e21a..db8f615eb 100644 --- a/mobile/ios/App/PairView.swift +++ b/mobile/ios/App/PairView.swift @@ -5,54 +5,189 @@ import UIKit struct PairView: View { @Environment(ServerStore.self) private var servers @Environment(\.dismiss) private var dismiss + + var startWithScanner: Bool = false + var initialOrigin: String? = nil + @State private var code = "" @State private var origin = "" @State private var deviceName = UIDevice.current.name @State private var busy = false @State private var scanning = false + @State private var didApplyInitialState = false @State private var errorMessage: String? - private var isInvitation: Bool { PairingInvitation.looksLikeInvitation(code) } + private var trimmedCode: String { + code.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var isInvitation: Bool { + PairingInvitation.looksLikeInvitation(trimmedCode) + } + + private var parsedInvitationHost: String? { + guard isInvitation, + let invitation = try? PairingInvitation.parse(trimmedCode), + let firstOrigin = invitation.candidateOrigins.first?.value + else { return nil } + return firstOrigin + } private var canSubmit: Bool { - guard !busy, !code.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { - return false + guard !busy, !trimmedCode.isEmpty else { return false } + return isInvitation || !origin.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + private var recentOrigins: [String] { + var seen = Set() + var result: [String] = [] + for profile in servers.profiles.reversed() { + if seen.insert(profile.origin).inserted { + result.append(profile.origin) + } } - return isInvitation || !origin.trimmingCharacters(in: .whitespaces).isEmpty + return result } var body: some View { NavigationStack { Form { + // 1. Primary QR Scan Action + Section { + Button { + errorMessage = nil + scanning = true + } label: { + HStack(spacing: 12) { + ZStack { + RoundedRectangle(cornerRadius: 10, style: .continuous) + .fill(Color.accentColor.opacity(0.15)) + .frame(width: 40, height: 40) + Image(systemName: "qrcode.viewfinder") + .font(.system(size: 19, weight: .semibold)) + .foregroundStyle(Color.accentColor) + } + VStack(alignment: .leading, spacing: 2) { + Text("扫码配对") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.primary) + Text("对准桌面端二维码即可自动识别连接") + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + Image(systemName: "chevron.right") + .font(.caption.weight(.semibold)) + .foregroundStyle(.tertiary) + } + .padding(.vertical, 2) + } + } + + // 2. Connection Code Input Section("连接码") { - TextField("粘贴连接码", text: $code) - .textInputAutocapitalization(.never) - .autocorrectionDisabled() - HStack { - Button("粘贴", systemImage: "doc.on.clipboard") { - if let text = UIPasteboard.general.string { code = text } + HStack(spacing: 8) { + TextField("输入 8 位连接码或粘贴完整邀请码", text: $code) + .textInputAutocapitalization(.characters) + .autocorrectionDisabled() + .font(.subheadline.monospaced()) + + if !code.isEmpty { + Button { + code = "" + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(.tertiary) + } + .buttonStyle(.borderless) + } + + Button { + pasteFromClipboard() + } label: { + HStack(spacing: 4) { + Image(systemName: "doc.on.clipboard") + Text("粘贴") + } + .font(.caption.weight(.semibold)) + .padding(.horizontal, 10) + .padding(.vertical, 5) + .background(Capsule().fill(Color.accentColor.opacity(0.14))) + .foregroundStyle(Color.accentColor) + } + .buttonStyle(.borderless) + } + + if let host = parsedInvitationHost { + LabeledContent("识别到的电脑地址") { + Text(host) + .font(.caption.monospaced()) + .foregroundStyle(.secondary) } - Spacer() - Button("扫码", systemImage: "qrcode.viewfinder") { scanning = true } } - .buttonStyle(.borderless) } - Section("电脑地址") { - if isInvitation { - Text("已包含在连接码中").foregroundStyle(.secondary) - } else { - TextField("http://192.168.1.2:17891", text: $origin) + + // 3. Host Address (Only needed when using a short code instead of a full invitation) + if !isInvitation { + Section("电脑地址") { + TextField("例如 192.168.1.2 或 http://192.168.1.2:17891", text: $origin) .keyboardType(.URL) .textContentType(.URL) .textInputAutocapitalization(.never) .autocorrectionDisabled() + .font(.subheadline.monospaced()) + + if !recentOrigins.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + ForEach(recentOrigins, id: \.self) { savedOrigin in + let isSelected = ServerStore.normalizeOrigin(origin) == savedOrigin + Button { + origin = savedOrigin + } label: { + HStack(spacing: 4) { + Image(systemName: isSelected ? "checkmark.circle.fill" : "clock.arrow.circlepath") + .font(.system(size: 11, weight: .semibold)) + Text(savedOrigin) + .font(.caption2.monospaced()) + } + .padding(.horizontal, 10) + .padding(.vertical, 5) + .background( + Capsule() + .fill( + isSelected + ? Color.accentColor.opacity(0.16) + : Color.secondary.opacity(0.12) + ) + ) + .foregroundStyle(isSelected ? Color.accentColor : Color.secondary) + } + .buttonStyle(.plain) + } + } + .padding(.vertical, 2) + } + } } } - Section("设备名称") { + + // 4. Device Name + Section("本机名称") { TextField("设备名称", text: $deviceName) + .font(.subheadline) } + if let errorMessage { - Section { Text(errorMessage).foregroundStyle(.red) } + Section { + HStack(spacing: 8) { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(.red) + Text(errorMessage) + .font(.footnote) + .foregroundStyle(.red) + } + } } } .navigationTitle("配对电脑") @@ -65,12 +200,26 @@ struct PairView: View { if busy { ProgressView() } else { - Button("配对", action: submit).disabled(!canSubmit) + Button("配对", action: submit) + .fontWeight(.semibold) + .disabled(!canSubmit) } } } .interactiveDismissDisabled(busy) .fullScreenCover(isPresented: $scanning) { scanner } + .onAppear { + guard !didApplyInitialState else { return } + didApplyInitialState = true + if let initialOrigin, !initialOrigin.isEmpty { + origin = initialOrigin + } else if origin.isEmpty, let lastOrigin = servers.activeProfile?.origin { + origin = lastOrigin + } + if startWithScanner { + scanning = true + } + } } } @@ -78,35 +227,60 @@ struct PairView: View { NavigationStack { QRScannerView( onCode: { text in - code = text + let cleaned = text.trimmingCharacters(in: .whitespacesAndNewlines) + code = cleaned scanning = false - if PairingInvitation.looksLikeInvitation(text) { submit() } + if PairingInvitation.looksLikeInvitation(cleaned) || !origin.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + submit() + } }, onFailure: { message in errorMessage = message scanning = false + }, + onManualInputTap: { + scanning = false } ) .ignoresSafeArea() - .navigationTitle("扫描二维码") + .navigationTitle("扫码配对") .navigationBarTitleDisplayMode(.inline) + .toolbarBackground(.hidden, for: .navigationBar) + .toolbarColorScheme(.dark, for: .navigationBar) .toolbar { ToolbarItem(placement: .cancellationAction) { - Button("取消") { scanning = false } + Button("关闭") { + scanning = false + } + .foregroundStyle(.white) } } } } + private func pasteFromClipboard() { + guard let pasted = UIPasteboard.general.string?.trimmingCharacters(in: .whitespacesAndNewlines), + !pasted.isEmpty + else { return } + code = pasted + errorMessage = nil + if PairingInvitation.looksLikeInvitation(pasted) { + submit() + } + } + private func submit() { + guard canSubmit else { return } busy = true errorMessage = nil - let input = code.trimmingCharacters(in: .whitespacesAndNewlines) + let input = trimmedCode Task { do { try await servers.pair(input: input, manualOrigin: origin, deviceName: deviceName) + UINotificationFeedbackGenerator().notificationOccurred(.success) dismiss() } catch { + UINotificationFeedbackGenerator().notificationOccurred(.error) errorMessage = error.localizedDescription busy = false } diff --git a/mobile/ios/App/QRScannerView.swift b/mobile/ios/App/QRScannerView.swift index 86143851d..5beea70db 100644 --- a/mobile/ios/App/QRScannerView.swift +++ b/mobile/ios/App/QRScannerView.swift @@ -1,7 +1,240 @@ import AVFoundation +import PhotosUI import SwiftUI +import UIKit +import Vision -struct QRScannerView: UIViewControllerRepresentable { +struct QRScannerView: View { + let onCode: (String) -> Void + let onFailure: (String) -> Void + var onManualInputTap: (() -> Void)? = nil + + @State private var selectedZoom: CGFloat = 1.5 + @State private var torchOn = false + @State private var selectedPhotoItem: PhotosPickerItem? + @State private var photoErrorMessage: String? + + var body: some View { + ZStack { + QRScannerCameraRepresentable( + zoomFactor: $selectedZoom, + torchOn: $torchOn, + onCode: { code in + let generator = UINotificationFeedbackGenerator() + generator.notificationOccurred(.success) + onCode(code) + }, + onFailure: onFailure + ) + .ignoresSafeArea() + + // Viewfinder & Controls Overlay + VStack(spacing: 0) { + Spacer() + + // Target Reticle + ZStack { + RoundedRectangle(cornerRadius: 24, style: .continuous) + .strokeBorder(Color.white.opacity(0.22), lineWidth: 1.5) + .frame(width: 260, height: 260) + + ScannerCornerBrackets() + .stroke(Color.accentColor, style: StrokeStyle(lineWidth: 4, lineCap: .round, lineJoin: .round)) + .frame(width: 260, height: 260) + } + + // Zoom Pills (1x / 1.5x / 2.5x) + HStack(spacing: 10) { + ForEach([1.0, 1.5, 2.5], id: \.self) { factor in + let isSelected = abs(selectedZoom - factor) < 0.2 + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + selectedZoom = factor + } label: { + Text(factor == 1.0 ? "1x" : String(format: "%.1fx", factor)) + .font(.system(size: 13, weight: .bold, design: .rounded)) + .foregroundStyle(isSelected ? Color.black : Color.white) + .frame(width: 44, height: 32) + .background( + Capsule() + .fill(isSelected ? Color.white : Color.black.opacity(0.5)) + ) + .overlay( + Capsule() + .strokeBorder(Color.white.opacity(0.25), lineWidth: 0.8) + ) + } + .buttonStyle(.plain) + } + } + .padding(.top, 24) + + if let photoErrorMessage { + Text(photoErrorMessage) + .font(.caption.weight(.medium)) + .foregroundStyle(.white) + .padding(.horizontal, 14) + .padding(.vertical, 8) + .background(Capsule().fill(Color.red.opacity(0.85))) + .padding(.top, 14) + } + + Spacer() + + // Bottom Quick Actions Bar + HStack(spacing: 16) { + PhotosPicker(selection: $selectedPhotoItem, matching: .images) { + VStack(spacing: 6) { + ZStack { + Circle() + .fill(.ultraThinMaterial) + .frame(width: 50, height: 50) + Image(systemName: "photo.on.rectangle") + .font(.system(size: 19, weight: .semibold)) + .foregroundStyle(.white) + } + Text("相册") + .font(.caption2.weight(.medium)) + .foregroundStyle(.white.opacity(0.9)) + } + } + .buttonStyle(.plain) + + if let onManualInputTap { + Button { + onManualInputTap() + } label: { + HStack(spacing: 8) { + Image(systemName: "keyboard") + .font(.system(size: 16, weight: .semibold)) + Text("使用连接码配对") + .font(.subheadline.weight(.semibold)) + } + .foregroundStyle(.white) + .padding(.horizontal, 20) + .frame(height: 50) + .background( + Capsule() + .fill(.ultraThinMaterial) + .overlay( + Capsule() + .strokeBorder(Color.white.opacity(0.24), lineWidth: 0.8) + ) + ) + } + .buttonStyle(.plain) + } + + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + torchOn.toggle() + } label: { + VStack(spacing: 6) { + ZStack { + Circle() + .fill(torchOn ? AnyShapeStyle(Color.yellow) : AnyShapeStyle(.ultraThinMaterial)) + .frame(width: 50, height: 50) + Image(systemName: torchOn ? "flashlight.on.fill" : "flashlight.off.fill") + .font(.system(size: 19, weight: .semibold)) + .foregroundStyle(torchOn ? .black : .white) + } + Text("手电筒") + .font(.caption2.weight(.medium)) + .foregroundStyle(.white.opacity(0.9)) + } + } + .buttonStyle(.plain) + } + .padding(.bottom, 36) + } + } + .onChange(of: selectedPhotoItem) { _, newValue in + guard let item = newValue else { return } + photoErrorMessage = nil + Task { + await detectQRCode(from: item) + } + } + } + + @MainActor + private func detectQRCode(from item: PhotosPickerItem) async { + guard let data = try? await item.loadTransferable(type: Data.self), + let image = UIImage(data: data), + let cgImage = image.cgImage + else { + photoErrorMessage = "无法读取所选图片" + return + } + + let detected = await Task.detached(priority: .userInitiated) { () -> String? in + let request = VNDetectBarcodesRequest() + request.symbologies = [.qr] + let handler = VNImageRequestHandler(cgImage: cgImage, options: [:]) + try? handler.perform([request]) + return request.results?.compactMap(\.payloadStringValue).first(where: { !$0.isEmpty }) + }.value + + if let detected { + let generator = UINotificationFeedbackGenerator() + generator.notificationOccurred(.success) + onCode(detected) + } else { + UINotificationFeedbackGenerator().notificationOccurred(.error) + photoErrorMessage = "未在图片中识别到二维码" + } + } +} + +private struct ScannerCornerBrackets: Shape { + func path(in rect: CGRect) -> Path { + var path = Path() + let len: CGFloat = 28 + let r: CGFloat = 24 + + // Top-left + path.move(to: CGPoint(x: rect.minX, y: rect.minY + len + r / 2)) + path.addLine(to: CGPoint(x: rect.minX, y: rect.minY + r)) + path.addQuadCurve( + to: CGPoint(x: rect.minX + r, y: rect.minY), + control: CGPoint(x: rect.minX, y: rect.minY) + ) + path.addLine(to: CGPoint(x: rect.minX + len + r / 2, y: rect.minY)) + + // Top-right + path.move(to: CGPoint(x: rect.maxX - len - r / 2, y: rect.minY)) + path.addLine(to: CGPoint(x: rect.maxX - r, y: rect.minY)) + path.addQuadCurve( + to: CGPoint(x: rect.maxX, y: rect.minY + r), + control: CGPoint(x: rect.maxX, y: rect.minY) + ) + path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY + len + r / 2)) + + // Bottom-right + path.move(to: CGPoint(x: rect.maxX, y: rect.maxY - len - r / 2)) + path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY - r)) + path.addQuadCurve( + to: CGPoint(x: rect.maxX - r, y: rect.maxY), + control: CGPoint(x: rect.maxX, y: rect.maxY) + ) + path.addLine(to: CGPoint(x: rect.maxX - len - r / 2, y: rect.maxY)) + + // Bottom-left + path.move(to: CGPoint(x: rect.minX + len + r / 2, y: rect.maxY)) + path.addLine(to: CGPoint(x: rect.minX + r, y: rect.maxY)) + path.addQuadCurve( + to: CGPoint(x: rect.minX, y: rect.maxY - r), + control: CGPoint(x: rect.minX, y: rect.maxY) + ) + path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY - len - r / 2)) + + return path + } +} + +private struct QRScannerCameraRepresentable: UIViewControllerRepresentable { + @Binding var zoomFactor: CGFloat + @Binding var torchOn: Bool let onCode: (String) -> Void let onFailure: (String) -> Void @@ -9,22 +242,49 @@ struct QRScannerView: UIViewControllerRepresentable { let controller = ScannerController() controller.onCode = onCode controller.onFailure = onFailure + controller.onZoomChanged = { newZoom in + DispatchQueue.main.async { + zoomFactor = newZoom + } + } return controller } - func updateUIViewController(_ controller: ScannerController, context: Context) {} + func updateUIViewController(_ controller: ScannerController, context: Context) { + controller.applyUserZoom(zoomFactor) + controller.applyTorch(torchOn) + } } -final class ScannerController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { +final class ScannerController: UIViewController, + AVCaptureMetadataOutputObjectsDelegate, + AVCaptureVideoDataOutputSampleBufferDelegate +{ var onCode: ((String) -> Void)? var onFailure: ((String) -> Void)? + var onZoomChanged: ((CGFloat) -> Void)? + private let session = AVCaptureSession() + private let sessionQueue = DispatchQueue(label: "com.vibex.qrscanner.session", qos: .userInitiated) + private let visionQueue = DispatchQueue(label: "com.vibex.qrscanner.vision", qos: .userInitiated) + private var captureDevice: AVCaptureDevice? private var previewLayer: AVCaptureVideoPreviewLayer? + private var baseZoomFactor: CGFloat = 1.0 + private var currentRelativeZoom: CGFloat = 1.5 + private var pinchStartZoom: CGFloat = 1.5 private var delivered = false + private var lastVisionSampleTime: CFTimeInterval = 0 override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black + + let pinch = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:))) + view.addGestureRecognizer(pinch) + + let tap = UITapGestureRecognizer(target: self, action: #selector(handleTapToFocus(_:))) + view.addGestureRecognizer(tap) + switch AVCaptureDevice.authorizationStatus(for: .video) { case .authorized: configure() @@ -46,43 +306,243 @@ final class ScannerController: UIViewController, AVCaptureMetadataOutputObjectsD override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) - if session.isRunning { session.stopRunning() } + sessionQueue.async { [weak self] in + guard let self, self.session.isRunning else { return } + self.session.stopRunning() + } + } + + private static func bestBackCamera() -> AVCaptureDevice? { + let discovery = AVCaptureDevice.DiscoverySession( + deviceTypes: [ + .builtInTripleCamera, + .builtInDualWideCamera, + .builtInDualCamera, + .builtInWideAngleCamera, + ], + mediaType: .video, + position: .back + ) + return discovery.devices.first ?? AVCaptureDevice.default(for: .video) } private func configure() { - guard let device = AVCaptureDevice.default(for: .video), - let input = try? AVCaptureDeviceInput(device: device), - session.canAddInput(input) + guard let device = Self.bestBackCamera(), + let input = try? AVCaptureDeviceInput(device: device) else { onFailure?("此设备无法使用相机") return } - session.addInput(input) - let output = AVCaptureMetadataOutput() - guard session.canAddOutput(output) else { - onFailure?("此设备无法使用相机") - return - } - session.addOutput(output) - output.setMetadataObjectsDelegate(self, queue: .main) - output.metadataObjectTypes = [.qr] + captureDevice = device + + // On multi-camera iPhones (Triple/DualWide), virtualDeviceSwitchOverVideoZoomFactors.first + // represents the main 1x wide camera (while 1.0 is the 0.5x ultra-wide macro camera). + let switchOver = device.virtualDeviceSwitchOverVideoZoomFactors.first?.doubleValue ?? 1.0 + baseZoomFactor = CGFloat(max(1.0, switchOver)) + let layer = AVCaptureVideoPreviewLayer(session: session) layer.videoGravity = .resizeAspectFill layer.frame = view.bounds view.layer.addSublayer(layer) previewLayer = layer - DispatchQueue.global(qos: .userInitiated).async { self.session.startRunning() } + + sessionQueue.async { [weak self] in + guard let self else { return } + self.session.beginConfiguration() + if self.session.canSetSessionPreset(.hd1920x1080) { + self.session.sessionPreset = .hd1920x1080 + } + if self.session.canAddInput(input) { + self.session.addInput(input) + } + + let metadataOutput = AVCaptureMetadataOutput() + if self.session.canAddOutput(metadataOutput) { + self.session.addOutput(metadataOutput) + metadataOutput.setMetadataObjectsDelegate(self, queue: .main) + if metadataOutput.availableMetadataObjectTypes.contains(.qr) { + metadataOutput.metadataObjectTypes = [.qr] + } + } + + let videoOutput = AVCaptureVideoDataOutput() + videoOutput.alwaysDiscardsLateVideoFrames = true + if self.session.canAddOutput(videoOutput) { + self.session.addOutput(videoOutput) + videoOutput.setSampleBufferDelegate(self, queue: self.visionQueue) + } + + self.session.commitConfiguration() + self.configureCameraFocusAndZoom(device: device, relativeZoom: self.currentRelativeZoom, animated: false) + self.session.startRunning() + } + } + + private func configureCameraFocusAndZoom(device: AVCaptureDevice, relativeZoom: CGFloat, animated: Bool) { + do { + try device.lockForConfiguration() + if device.isFocusPointOfInterestSupported { + device.focusPointOfInterest = CGPoint(x: 0.5, y: 0.5) + } + if device.isFocusModeSupported(.continuousAutoFocus) { + device.focusMode = .continuousAutoFocus + } + if device.isAutoFocusRangeRestrictionSupported { + device.autoFocusRangeRestriction = .near + } + if device.isExposurePointOfInterestSupported { + device.exposurePointOfInterest = CGPoint(x: 0.5, y: 0.5) + } + if device.isExposureModeSupported(.continuousAutoExposure) { + device.exposureMode = .continuousAutoExposure + } + if device.isSmoothAutoFocusSupported { + device.isSmoothAutoFocusEnabled = true + } + + let targetDeviceZoom = min( + max(device.minAvailableVideoZoomFactor, baseZoomFactor * relativeZoom), + min(device.maxAvailableVideoZoomFactor, baseZoomFactor * 4.0) + ) + if animated { + device.ramp(toVideoZoomFactor: targetDeviceZoom, withRate: 8.0) + } else { + device.videoZoomFactor = targetDeviceZoom + } + device.unlockForConfiguration() + } catch {} + } + + func applyUserZoom(_ relativeZoom: CGFloat) { + let clamped = min(max(1.0, relativeZoom), 4.0) + guard abs(clamped - currentRelativeZoom) > 0.05, let device = captureDevice else { return } + currentRelativeZoom = clamped + sessionQueue.async { [weak self] in + self?.configureCameraFocusAndZoom(device: device, relativeZoom: clamped, animated: true) + } + } + + func applyTorch(_ on: Bool) { + guard let device = captureDevice, device.hasTorch else { return } + sessionQueue.async { + do { + try device.lockForConfiguration() + let targetMode: AVCaptureDevice.TorchMode = on ? .on : .off + if device.torchMode != targetMode, device.isTorchModeSupported(targetMode) { + device.torchMode = targetMode + } + device.unlockForConfiguration() + } catch {} + } + } + + @objc private func handlePinch(_ gesture: UIPinchGestureRecognizer) { + guard let device = captureDevice else { return } + switch gesture.state { + case .began: + pinchStartZoom = currentRelativeZoom + case .changed: + let next = min(max(1.0, pinchStartZoom * gesture.scale), 4.0) + currentRelativeZoom = next + onZoomChanged?(next) + sessionQueue.async { [weak self] in + self?.configureCameraFocusAndZoom(device: device, relativeZoom: next, animated: false) + } + default: + break + } + } + + @objc private func handleTapToFocus(_ gesture: UITapGestureRecognizer) { + guard let previewLayer, let device = captureDevice else { return } + let location = gesture.location(in: view) + let devicePoint = previewLayer.captureDevicePointConverted(fromLayerPoint: location) + sessionQueue.async { + do { + try device.lockForConfiguration() + if device.isFocusPointOfInterestSupported { + device.focusPointOfInterest = devicePoint + } + if device.isFocusModeSupported(.continuousAutoFocus) { + device.focusMode = .continuousAutoFocus + } + if device.isExposurePointOfInterestSupported { + device.exposurePointOfInterest = devicePoint + } + if device.isExposureModeSupported(.continuousAutoExposure) { + device.exposureMode = .continuousAutoExposure + } + device.unlockForConfiguration() + } catch {} + } } + private func deliverCodeOnMain(_ raw: String) { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + DispatchQueue.main.async { [weak self] in + guard let self, !self.delivered else { return } + self.delivered = true + self.sessionQueue.async { + if self.session.isRunning { + self.session.stopRunning() + } + } + self.onCode?(trimmed) + } + } + + // Engine 1: Hardware Metadata Decoder func metadataOutput( _ output: AVCaptureMetadataOutput, didOutput objects: [AVMetadataObject], from connection: AVCaptureConnection ) { guard !delivered, - let text = (objects.first as? AVMetadataMachineReadableCodeObject)?.stringValue + let codeObject = objects.first as? AVMetadataMachineReadableCodeObject, + let text = codeObject.stringValue, + !text.isEmpty else { return } - delivered = true - onCode?(text) + deliverCodeOnMain(text) + } + + // Engine 2: Vision Framework VNDetectBarcodesRequest (excels on angled/glare LCD/OLED screens) + func captureOutput( + _ output: AVCaptureOutput, + didOutput sampleBuffer: CMSampleBuffer, + from connection: AVCaptureConnection + ) { + guard !delivered else { return } + let now = CACurrentMediaTime() + guard now - lastVisionSampleTime >= 0.12 else { return } + lastVisionSampleTime = now + + guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } + let request = VNDetectBarcodesRequest { [weak self] req, _ in + guard let self, !self.delivered, + let results = req.results as? [VNBarcodeObservation] + else { return } + + if let match = results.first(where: { ($0.payloadStringValue?.isEmpty == false) }), + let payload = match.payloadStringValue + { + self.deliverCodeOnMain(payload) + } else if let candidate = results.first, + candidate.boundingBox.width > 0.01, + candidate.boundingBox.width < 0.18, + let device = self.captureDevice + { + // Auto-zoom in when a distant/small QR code is detected but too small to decode + let boosted = min(self.currentRelativeZoom * 1.35, 3.0) + if boosted > self.currentRelativeZoom + 0.15 { + self.currentRelativeZoom = boosted + self.onZoomChanged?(boosted) + self.configureCameraFocusAndZoom(device: device, relativeZoom: boosted, animated: true) + } + } + } + request.symbologies = [.qr] + let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .right, options: [:]) + try? handler.perform([request]) } } diff --git a/mobile/ios/App/RequiresServer.swift b/mobile/ios/App/RequiresServer.swift index d24137c75..08e02d420 100644 --- a/mobile/ios/App/RequiresServer.swift +++ b/mobile/ios/App/RequiresServer.swift @@ -7,25 +7,54 @@ struct RequiresServer: View { @Binding var selection: AppTab @ViewBuilder let content: (HostClient) -> Content + @State private var showingScannerPair = false + @State private var showingManualPair = false + var body: some View { - if let profile = servers.activeProfile { - if let client = servers.client(for: profile) { - content(client) + Group { + if let profile = servers.activeProfile { + if let client = servers.client(for: profile) { + content(client) + } else { + ContentUnavailableView { + Label("连接凭据已失效", systemImage: "key.slash") + } actions: { + HStack(spacing: 12) { + Button("扫码重新配对", systemImage: "qrcode.viewfinder") { + showingScannerPair = true + } + .buttonStyle(.borderedProminent) + + Button("连接码配对") { + showingManualPair = true + } + .buttonStyle(.bordered) + } + } + } } else { ContentUnavailableView { - Label("连接凭据已失效", systemImage: "key.slash") + Label("尚未连接电脑", systemImage: "desktopcomputer") } actions: { - Button("重新配对") { selection = .settings } + HStack(spacing: 12) { + Button("扫码配对", systemImage: "qrcode.viewfinder") { + showingScannerPair = true + } .buttonStyle(.borderedProminent) + + Button("连接码配对") { + showingManualPair = true + } + .buttonStyle(.bordered) + } } } - } else { - ContentUnavailableView { - Label("尚未连接电脑", systemImage: "desktopcomputer") - } actions: { - Button("去配对") { selection = .settings } - .buttonStyle(.borderedProminent) - } + } + .sheet(isPresented: $showingScannerPair) { + PairView(startWithScanner: true, initialOrigin: servers.activeProfile?.origin) + } + .sheet(isPresented: $showingManualPair) { + PairView(startWithScanner: false, initialOrigin: servers.activeProfile?.origin) } } } diff --git a/mobile/ios/App/RootTabView.swift b/mobile/ios/App/RootTabView.swift index f4e9bd8a0..82fb17ac0 100644 --- a/mobile/ios/App/RootTabView.swift +++ b/mobile/ios/App/RootTabView.swift @@ -77,6 +77,11 @@ struct RootTabView: View { withAnimation(.spring(response: 1.05, dampingFraction: 0.86, blendDuration: 0.2)) { isLaunchRevealed = revealed } + }, + onSelectTab: { targetTab in + withAnimation(.smooth(duration: 0.16)) { + selection = targetTab + } } ) } @@ -141,8 +146,11 @@ struct RootTabView: View { .onAppear { appearance.applyInterfaceStyleToAllWindows(appearance.themeMode.uiInterfaceStyle) } - .onChange(of: selection) { _, _ in + .onChange(of: selection) { _, newTab in dismissKeyboard() + if newTab == .conversations { + NotificationCenter.default.post(name: Notification.Name("vibex.didReturnToConversationsTab"), object: nil) + } } .background( GlobalInteractionInstaller() diff --git a/mobile/ios/App/ServerDetailView.swift b/mobile/ios/App/ServerDetailView.swift index 93e05348d..9081a357e 100644 --- a/mobile/ios/App/ServerDetailView.swift +++ b/mobile/ios/App/ServerDetailView.swift @@ -5,31 +5,70 @@ struct ServerDetailView: View { @Environment(\.dismiss) private var dismiss let profile: ServerProfile @State private var confirmingForget = false + @State private var showingRepairSheet = false + + private var isActive: Bool { + servers.activeProfile?.id == profile.id + } var body: some View { List { - Section("电脑") { - LabeledContent("地址", value: profile.origin) - LabeledContent("VibeX 版本", value: profile.serverVersion) - LabeledContent("协议版本", value: profile.protocolVersion) - LabeledContent("设备名称", value: profile.deviceName) - } - Section("权限") { - ForEach(profile.scopes, id: \.self) { Text($0).font(.footnote.monospaced()) } + Section("连接信息") { + LabeledContent("状态") { + HStack(spacing: 5) { + Circle() + .fill(isActive ? Color.green : Color.secondary.opacity(0.4)) + .frame(width: 7, height: 7) + Text(isActive ? "当前连接" : "已保存") + .foregroundStyle(isActive ? .primary : .secondary) + } + } + LabeledContent("电脑名称", value: profile.serverName) + LabeledContent("地址") { + Text(profile.origin) + .font(.footnote.monospaced()) + .foregroundStyle(.secondary) + } + LabeledContent("桌面端版本", value: "v\(profile.serverVersion)") + LabeledContent("通讯协议", value: "v\(profile.protocolVersion)") + LabeledContent("本机标识", value: profile.deviceName) } + Section { - Button("忘记此电脑", role: .destructive) { confirmingForget = true } + if !isActive { + Button { + servers.setActive(profile.id) + dismiss() + } label: { + Label("设为当前连接电脑", systemImage: "checkmark.circle") + } + } + + Button { + showingRepairSheet = true + } label: { + Label("重新配对更新凭据", systemImage: "qrcode.viewfinder") + } + + Button(role: .destructive) { + confirmingForget = true + } label: { + Label("移除此电脑", systemImage: "trash") + } } } - .navigationTitle("电脑详情") + .navigationTitle(profile.displayHost) .navigationBarTitleDisplayMode(.inline) - .confirmationDialog("忘记此电脑?", isPresented: $confirmingForget, titleVisibility: .visible) { - Button("忘记", role: .destructive) { + .sheet(isPresented: $showingRepairSheet) { + PairView(startWithScanner: false, initialOrigin: profile.origin) + } + .confirmationDialog("移除此电脑?", isPresented: $confirmingForget, titleVisibility: .visible) { + Button("移除", role: .destructive) { servers.forget(profile) dismiss() } } message: { - Text("需要重新配对才能再次连接") + Text("移除后需重新扫码或输入连接码才能再次连接") } } } diff --git a/mobile/ios/App/ServerStore.swift b/mobile/ios/App/ServerStore.swift index d003a7645..89ed5c2bd 100644 --- a/mobile/ios/App/ServerStore.swift +++ b/mobile/ios/App/ServerStore.swift @@ -39,8 +39,9 @@ final class ServerStore { let invitation = try PairingInvitation.parse(input) session = try await client.redeem(invitation: invitation, deviceName: deviceName) } else { + let normalizedOrigin = Self.normalizeOrigin(manualOrigin) session = try await client.redeem( - origin: try HostOrigin.parse(manualOrigin), + origin: try HostOrigin.parse(normalizedOrigin), pairingToken: input, deviceName: deviceName ) @@ -60,6 +61,28 @@ final class ServerStore { persist() } + static func normalizeOrigin(_ raw: String) -> String { + var text = raw.trimmingCharacters(in: .whitespacesAndNewlines) + while text.hasSuffix("/") { text.removeLast() } + guard !text.isEmpty else { return text } + if !text.lowercased().hasPrefix("http://"), !text.lowercased().hasPrefix("https://") { + text = "http://\(text)" + } + if let components = URLComponents(string: text), + components.scheme == "http", + components.port == nil, + let host = components.host, + !host.isEmpty + { + var updated = components + updated.port = 17891 + if let built = updated.string { + return built + } + } + return text + } + /// The most recently paired computer is the one the tabs read from. var activeProfile: ServerProfile? { profiles.last } diff --git a/mobile/ios/App/SettingsView.swift b/mobile/ios/App/SettingsView.swift index 82271aaa7..a7d8f1b4f 100644 --- a/mobile/ios/App/SettingsView.swift +++ b/mobile/ios/App/SettingsView.swift @@ -4,6 +4,8 @@ import SwiftUI struct SettingsView: View { @Environment(ServerStore.self) private var servers @Environment(AppAppearanceStore.self) private var appearance + @State private var showingQuickScanner = false + @State private var showingManualPair = false var body: some View { NavigationStack { @@ -16,34 +18,24 @@ struct SettingsView: View { HStack(spacing: 12) { MemberBotAvatarView( config: appearance.avatarConfig, - size: 42, + size: 44, animated: true ) - VStack(alignment: .leading, spacing: 1) { - HStack(spacing: 6) { - Text(appearance.userName) - .font(.subheadline.weight(.semibold)) - .foregroundStyle(.primary) - Text(appearance.userHandle) - .font(.caption2) - .foregroundStyle(.secondary) - } - Text(appearance.userRoleTitle) + VStack(alignment: .leading, spacing: 2) { + Text(appearance.userName) + .font(.body.weight(.semibold)) + .foregroundStyle(.primary) + Text("\(appearance.userHandle) · \(appearance.userRoleTitle)") .font(.caption) .foregroundStyle(.secondary) - if !appearance.userBio.isEmpty { - Text(appearance.userBio) - .font(.caption2) - .foregroundStyle(.tertiary) - .lineLimit(1) - } + .lineLimit(1) } } } - .listRowInsets(EdgeInsets(top: 6, leading: 14, bottom: 6, trailing: 14)) + .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) } - // 2. 已配对的电脑 & 3. 技能 + // 2. 工作站与扩展 Section { NavigationLink { PairedComputersSettingsView() @@ -53,32 +45,27 @@ struct SettingsView: View { systemImage: "desktopcomputer", tint: .blue ) - VStack(alignment: .leading, spacing: 1) { - Text("已配对的电脑") - .font(.subheadline.weight(.medium)) - Text(pairedComputerSubtitle) - .font(.caption2) - .foregroundStyle(.secondary) - .lineLimit(1) - } + Text("配对的电脑") + .font(.subheadline.weight(.medium)) Spacer(minLength: 6) - if servers.activeProfile != nil { - HStack(spacing: 4) { + if let active = servers.activeProfile { + HStack(spacing: 5) { Circle() .fill(Color.green) .frame(width: 6.5, height: 6.5) - Text("已连接") - .font(.caption2.weight(.medium)) + Text(active.displayHost) + .font(.caption.monospaced()) .foregroundStyle(.secondary) + .lineLimit(1) } } else { - Text("去配对") - .font(.caption2) + Text("未连接") + .font(.caption) .foregroundStyle(.secondary) } } } - .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) NavigationLink { SkillsHubSettingsView() @@ -88,20 +75,18 @@ struct SettingsView: View { systemImage: "sparkles.rectangle.stack.fill", tint: .purple ) - VStack(alignment: .leading, spacing: 1) { - Text("技能") - .font(.subheadline.weight(.medium)) - Text("技能 · MCP · 插件 · 子代理") - .font(.caption2) - .foregroundStyle(.secondary) - } + Text("技能与扩展") + .font(.subheadline.weight(.medium)) Spacer() + Text("技能 · MCP · 插件") + .font(.caption) + .foregroundStyle(.secondary) } } - .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) } - // 4. 主题 & 5. 字体 & 6. 通知 + // 3. 外观与提醒 Section { HStack(spacing: 10) { settingsIconBadge( @@ -133,20 +118,15 @@ struct SettingsView: View { systemImage: "textformat.size", tint: .orange ) - VStack(alignment: .leading, spacing: 1) { - Text("字体") - .font(.subheadline.weight(.medium)) - Text("字号大小与字体样式") - .font(.caption2) - .foregroundStyle(.secondary) - } + Text("字体") + .font(.subheadline.weight(.medium)) Spacer() Text("\(appearance.fontStylePreset.shortTitle) · \(appearance.fontSizePreset.title)") - .font(.caption2) + .font(.caption) .foregroundStyle(.secondary) } } - .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) NavigationLink { NotificationSettingsDetailView() @@ -156,23 +136,18 @@ struct SettingsView: View { systemImage: "bell.badge.fill", tint: .red ) - VStack(alignment: .leading, spacing: 1) { - Text("通知") - .font(.subheadline.weight(.medium)) - Text("任务完成、审批与协作消息提醒") - .font(.caption2) - .foregroundStyle(.secondary) - } + Text("通知") + .font(.subheadline.weight(.medium)) Spacer() Text(appearance.systemNotificationStatusText) - .font(.caption2) + .font(.caption) .foregroundStyle(.secondary) } } - .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) } - // 7. 关于 VibeX & 当前版本 + // 4. 关于 VibeX Section { NavigationLink { AboutVibeXDetailView() @@ -185,45 +160,46 @@ struct SettingsView: View { Text("关于 VibeX") .font(.subheadline.weight(.medium)) Spacer() - Text("本地优先 AI 研发平台") - .font(.caption2) + Text(currentVersionLabel) + .font(.caption.monospacedDigit()) .foregroundStyle(.secondary) } } - .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) - - HStack(spacing: 10) { - settingsIconBadge( - systemImage: "checkmark.seal.fill", - tint: .green - ) - Text("当前版本") - .font(.subheadline.weight(.medium)) - Spacer() - Text(currentVersionLabel) - .font(.caption.monospacedDigit()) - .foregroundStyle(.secondary) - } - .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) } } - .listSectionSpacing(8) - .contentMargins(.top, 2, for: .scrollContent) + .listSectionSpacing(10) + .contentMargins(.top, 4, for: .scrollContent) .navigationTitle("设置") .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Menu { + Button("扫码配对电脑", systemImage: "qrcode.viewfinder") { + showingQuickScanner = true + } + Button("输入连接码配对", systemImage: "keyboard") { + showingManualPair = true + } + } label: { + Image(systemName: "qrcode.viewfinder") + .font(.system(size: 16, weight: .semibold)) + } + .accessibilityLabel("扫码配对") + } + } + .sheet(isPresented: $showingQuickScanner) { + PairView(startWithScanner: true, initialOrigin: servers.activeProfile?.origin) + } + .sheet(isPresented: $showingManualPair) { + PairView(startWithScanner: false, initialOrigin: servers.activeProfile?.origin) + } } } - private var pairedComputerSubtitle: String { - if let active = servers.activeProfile { - return "\(active.serverName) · 共 \(servers.profiles.count) 台历史设备" - } - return "查看历史配对电脑或配对新的电脑" - } - private var currentVersionLabel: String { if let active = servers.activeProfile { - return "v\(active.serverVersion) (协议 v\(active.protocolVersion))" + return "v\(active.serverVersion)" } return "v0.4.2" } @@ -325,56 +301,72 @@ struct ProfileSettingsDetailView: View { } } -// MARK: - 2. 已配对的电脑(历史配对 + 配对新的电脑) +// MARK: - 2. 配对的电脑(已保存电脑 + 1-Tap 扫码/连接码配对) struct PairedComputersSettingsView: View { @Environment(ServerStore.self) private var servers - @State private var showingPairSheet = false + @State private var showingScannerPair = false + @State private var showingManualPair = false var body: some View { List { - Section { + Section("新增连接") { Button { - showingPairSheet = true + showingScannerPair = true } label: { HStack(spacing: 12) { ZStack { - RoundedRectangle(cornerRadius: 10, style: .continuous) + RoundedRectangle(cornerRadius: 9, style: .continuous) .fill(Color.accentColor.opacity(0.14)) - .frame(width: 40, height: 40) + .frame(width: 34, height: 34) Image(systemName: "qrcode.viewfinder") - .font(.system(size: 18, weight: .semibold)) + .font(.system(size: 16, weight: .semibold)) .foregroundStyle(Color.accentColor) } - VStack(alignment: .leading, spacing: 3) { - Text("配对新的电脑") - .font(.headline) - .foregroundStyle(.primary) - Text("扫描桌面端二维码、粘贴邀请码或手动输入地址") - .font(.caption) - .foregroundStyle(.secondary) + Text("扫码配对电脑") + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.primary) + Spacer() + Image(systemName: "chevron.right") + .font(.caption.weight(.semibold)) + .foregroundStyle(.tertiary) + } + .padding(.vertical, 2) + } + + Button { + showingManualPair = true + } label: { + HStack(spacing: 12) { + ZStack { + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(Color.indigo.opacity(0.14)) + .frame(width: 34, height: 34) + Image(systemName: "keyboard") + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(Color.indigo) } + Text("使用连接码配对") + .font(.subheadline.weight(.medium)) + .foregroundStyle(.primary) Spacer() - Image(systemName: "plus.circle.fill") - .font(.title3) - .foregroundStyle(Color.accentColor) + Image(systemName: "chevron.right") + .font(.caption.weight(.semibold)) + .foregroundStyle(.tertiary) } - .padding(.vertical, 4) + .padding(.vertical, 2) } - } header: { - Text("新增连接") } - Section { + Section("已保存的电脑 (\(servers.profiles.count))") { if servers.profiles.isEmpty { ContentUnavailableView( - "暂无历史配对电脑", - systemImage: "desktopcomputer.trianglebadge.exclamationmark", - description: Text("点击上方「配对新的电脑」连接你的 VibeX 桌面端。") + "尚未配对电脑", + systemImage: "desktopcomputer" ) .padding(.vertical, 16) } else { - ForEach(servers.profiles) { profile in + ForEach(servers.profiles.reversed()) { profile in let isActive = servers.activeProfile?.id == profile.id NavigationLink { ServerDetailView(profile: profile) @@ -383,16 +375,16 @@ struct PairedComputersSettingsView: View { ZStack { Circle() .fill(isActive ? Color.green.opacity(0.15) : Color.secondary.opacity(0.12)) - .frame(width: 38, height: 38) + .frame(width: 36, height: 36) Image(systemName: isActive ? "laptopcomputer.and.iphone" : "desktopcomputer") - .font(.system(size: 16, weight: .semibold)) + .font(.system(size: 15, weight: .semibold)) .foregroundStyle(isActive ? Color.green : Color.secondary) } - VStack(alignment: .leading, spacing: 4) { + VStack(alignment: .leading, spacing: 3) { HStack(spacing: 6) { Text(profile.serverName) - .font(.body.weight(.semibold)) + .font(.subheadline.weight(.semibold)) if isActive { Text("当前连接") .font(.caption2.weight(.semibold)) @@ -404,25 +396,23 @@ struct PairedComputersSettingsView: View { .foregroundStyle(Color.green) } } - Text(profile.origin) + Text("\(profile.origin) · v\(profile.serverVersion)") .font(.caption.monospaced()) .foregroundStyle(.secondary) - Text("设备:\(profile.deviceName) · VibeX v\(profile.serverVersion)") - .font(.caption2) - .foregroundStyle(.tertiary) + .lineLimit(1) } Spacer() if !isActive { - Button("连接") { + Button("切换") { servers.setActive(profile.id) } .buttonStyle(.bordered) .controlSize(.small) } } - .padding(.vertical, 4) + .padding(.vertical, 3) } .swipeActions(edge: .trailing, allowsFullSwipe: true) { Button(role: .destructive) { @@ -433,23 +423,20 @@ struct PairedComputersSettingsView: View { } } } - } header: { - Text("历史配对的电脑 (\(servers.profiles.count))") - } footer: { - Text("点击任意电脑可查看连接诊断详情,左滑可移除历史配对记录。") } } - .navigationTitle("已配对的电脑") + .navigationTitle("配对的电脑") .navigationBarTitleDisplayMode(.inline) - .sheet(isPresented: $showingPairSheet) { - NavigationStack { - PairView() - } + .sheet(isPresented: $showingScannerPair) { + PairView(startWithScanner: true, initialOrigin: servers.activeProfile?.origin) + } + .sheet(isPresented: $showingManualPair) { + PairView(startWithScanner: false, initialOrigin: servers.activeProfile?.origin) } } } -// MARK: - 3. 技能中心(技能 / MCP / 插件 / 子代理) +// MARK: - 3. 技能与扩展(技能 / MCP / 插件 / 子代理) enum SkillsHubSegment: String, CaseIterable, Identifiable { case skills = "技能" @@ -469,6 +456,19 @@ enum SkillsHubSegment: String, CaseIterable, Identifiable { } } +struct SubagentDisplayRole: Identifiable, Equatable { + let id: String + let backendRoleId: String? + let isDefaultAgentRole: Bool + let name: String + let agentId: String + let agentLabel: String + let modeId: String? + let configValues: [String: String] + let personaPrompt: String + let teamId: String? +} + struct SkillsHubSettingsView: View { @Environment(ServerStore.self) private var servers @State private var selectedSegment: SkillsHubSegment = .skills @@ -480,17 +480,21 @@ struct SkillsHubSettingsView: View { @State private var mcpServers: [LocalMcpServerItem] = [] @State private var plugins: [PluginCatalogItem] = [] @State private var roles: [CollabRole] = [] - @State private var agents: [CatalogAgent] = [] + @State private var barAgents: [ManagedAgentBarItem] = [] @State private var isLoading = false + @State private var authExpired = false @State private var errorMessage: String? @State private var selectedSkillForDetail: LocalSkillItem? + @State private var editingSubagentRole: SubagentDisplayRole? + @State private var showingNewSubagentRole = false + @State private var showingRepairSheet = false var body: some View { VStack(spacing: 0) { - // Top 4-tab segment bar: 技能 · MCP · 插件 · 子代理 + // Top 4-tab segment bar: 技能 · MCP · 插件 · 子代理 (single-line, uniform height) VStack(spacing: 10) { - HStack(spacing: 8) { + HStack(spacing: 6) { ForEach(SkillsHubSegment.allCases) { segment in let isSelected = selectedSegment == segment Button { @@ -498,14 +502,16 @@ struct SkillsHubSettingsView: View { selectedSegment = segment } } label: { - HStack(spacing: 5) { + HStack(spacing: 4) { Image(systemName: segment.icon) - .font(.system(size: 12, weight: .semibold)) + .font(.system(size: 11, weight: .semibold)) Text(segment.rawValue) - .font(.subheadline.weight(.semibold)) + .font(.system(size: 13, weight: .semibold)) + .lineLimit(1) + .fixedSize(horizontal: true, vertical: false) Text("\(count(for: segment))") - .font(.caption2.monospacedDigit()) - .padding(.horizontal, 5) + .font(.system(size: 11, weight: .semibold).monospacedDigit()) + .padding(.horizontal, 4.5) .padding(.vertical, 1) .background( Capsule().fill( @@ -515,8 +521,10 @@ struct SkillsHubSettingsView: View { ) ) } + .minimumScaleFactor(0.85) .frame(maxWidth: .infinity) - .padding(.vertical, 8) + .frame(height: 36) + .padding(.horizontal, 4) .background( RoundedRectangle(cornerRadius: 10, style: .continuous) .fill(isSelected ? Color.accentColor : Color(.secondarySystemGroupedBackground)) @@ -578,9 +586,33 @@ struct SkillsHubSettingsView: View { .padding(.vertical, 10) .background(Color(.systemGroupedBackground)) - if isLoading && skills.isEmpty && mcpServers.isEmpty && plugins.isEmpty && roles.isEmpty { + if isLoading && skills.isEmpty && mcpServers.isEmpty && plugins.isEmpty && displaySubagentRoles.isEmpty { Spacer() - ProgressView("正在同步\(selectedSegment.rawValue)目录...") + ProgressView("正在同步\(selectedSegment.rawValue)...") + Spacer() + } else if authExpired { + Spacer() + ContentUnavailableView { + Label("连接凭据已失效", systemImage: "key.slash") + } description: { + Text("桌面端配对已更新或过期,请重新扫码配对。") + } actions: { + HStack(spacing: 12) { + Button("重新配对", systemImage: "qrcode.viewfinder") { + showingRepairSheet = true + } + .buttonStyle(.borderedProminent) + + Button("重试") { + Task { await reloadAll() } + } + .buttonStyle(.bordered) + } + } + Spacer() + } else if isCurrentSegmentEmpty { + Spacer() + currentSegmentEmptyView Spacer() } else { List { @@ -613,6 +645,22 @@ struct SkillsHubSettingsView: View { .background(Color(.systemGroupedBackground)) .navigationTitle("技能与扩展") .navigationBarTitleDisplayMode(.inline) + .toolbar { + if selectedSegment == .subagents && !authExpired { + ToolbarItem(placement: .topBarTrailing) { + Button { + showingNewSubagentRole = true + } label: { + HStack(spacing: 4) { + Image(systemName: "plus") + .font(.system(size: 13, weight: .bold)) + Text("新建角色") + .font(.subheadline.weight(.semibold)) + } + } + } + } + } .onDisappear { dismissKeyboard() } @@ -629,7 +677,7 @@ struct SkillsHubSettingsView: View { } } } - .task { + .task(id: servers.activeProfile?.id) { await reloadAll() } .sheet(item: $selectedSkillForDetail) { skill in @@ -637,6 +685,33 @@ struct SkillsHubSettingsView: View { LocalSkillDetailSheet(skill: skill, client: client) } } + .sheet(item: $editingSubagentRole) { role in + if let client = servers.activeClient() { + SubagentRoleEditorSheet( + existingRole: role, + availableAgents: barAgents, + client: client, + onSaved: { + Task { await reloadAll() } + } + ) + } + } + .sheet(isPresented: $showingNewSubagentRole) { + if let client = servers.activeClient() { + SubagentRoleEditorSheet( + existingRole: nil, + availableAgents: barAgents, + client: client, + onSaved: { + Task { await reloadAll() } + } + ) + } + } + .sheet(isPresented: $showingRepairSheet) { + PairView(startWithScanner: true, initialOrigin: servers.activeProfile?.origin) + } } private func count(for segment: SkillsHubSegment) -> Int { @@ -644,121 +719,154 @@ struct SkillsHubSettingsView: View { case .skills: return skills.count case .mcp: return mcpServers.count case .plugins: return plugins.count - case .subagents: return roles.count + agents.count + case .subagents: return displaySubagentRoles.count + } + } + + private var isCurrentSegmentEmpty: Bool { + switch selectedSegment { + case .skills: return filteredSkills.isEmpty + case .mcp: return filteredMcpServers.isEmpty + case .plugins: return filteredPlugins.isEmpty + case .subagents: return filteredSubagentRoles.isEmpty } } @ViewBuilder - private var skillsListContent: some View { - let filtered = filteredSkills - if filtered.isEmpty { - ContentUnavailableView( - "暂无匹配的技能", - systemImage: "sparkles", - description: Text("桌面端安装的本地与全局 Agent 技能将在此显示。") - ) - } else { - Section("已安装技能 (\(filtered.count))") { - ForEach(filtered) { skill in - Button { - selectedSkillForDetail = skill - } label: { - VStack(alignment: .leading, spacing: 6) { - HStack(spacing: 8) { - Image(systemName: "sparkles") - .font(.caption.weight(.bold)) - .foregroundStyle(.purple) - Text(skill.name) - .font(.body.weight(.semibold)) - .foregroundStyle(.primary) - Spacer() - if skill.global { - Text("全局") - .font(.caption2.weight(.semibold)) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(Capsule().fill(Color.purple.opacity(0.14))) - .foregroundStyle(.purple) - } - Image(systemName: "chevron.right") - .font(.caption2) - .foregroundStyle(.tertiary) - } - if let desc = skill.description, !desc.isEmpty { - Text(desc) - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(2) - } - if !skill.apps.isEmpty { - ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 6) { - ForEach(skill.apps, id: \.self) { app in - Text(app) - .font(.caption2.monospaced()) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background( - RoundedRectangle(cornerRadius: 5, style: .continuous) - .fill(Color.secondary.opacity(0.12)) - ) - .foregroundStyle(.secondary) - } - } - } - } - } - .padding(.vertical, 4) - } - .buttonStyle(.plain) + private var currentSegmentEmptyView: some View { + switch selectedSegment { + case .skills: + ContentUnavailableView("暂无匹配的技能", systemImage: "sparkles") + case .mcp: + ContentUnavailableView("暂无 MCP 服务", systemImage: "server.rack") + case .plugins: + ContentUnavailableView("暂无已安装插件", systemImage: "puzzlepiece.extension") + case .subagents: + ContentUnavailableView { + Label("暂无子代理角色", systemImage: "person.2.badge.gearshape") + } actions: { + Button("新建子代理角色", systemImage: "plus") { + showingNewSubagentRole = true } + .buttonStyle(.borderedProminent) } } } - @ViewBuilder - private var mcpListContent: some View { - let filtered = filteredMcpServers - if filtered.isEmpty { - ContentUnavailableView( - "暂无 MCP 服务", - systemImage: "server.rack", - description: Text("在桌面端配置的本地或远程 MCP 服务器会同步显示在此处。") + /// Synthesizes the exact same Subagent Role list as desktop `MultiAgentSettings.tsx`: + /// 1. Built-in `{Agent} · 默认配置` default subagent delegation roles for each enabled agent + /// 2. User-created custom subagent roles (`CollabRole`) + private var displaySubagentRoles: [SubagentDisplayRole] { + var matchedBackendIds = Set() + var defaultRoles: [SubagentDisplayRole] = [] + + for agent in barAgents { + let normalizedKey = agent.agentId.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + let label = AgentBrand.displayName(agent.agentId, hostName: agent.displayName) + let defaultName = "\(label) · 默认配置" + let defaultId = "default-agent:\(agent.agentId)" + + let matchedBackend = roles.first { role in + role.id == defaultId || + (role.agentId.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == normalizedKey && + (role.name == defaultName || role.name == "\(agent.displayName) · 默认配置")) + } + if let matchedBackend { + matchedBackendIds.insert(matchedBackend.id) + } + + let persona = matchedBackend.map { + $0.personaPrompt.isEmpty ? $0.summary : $0.personaPrompt + } ?? "" + + defaultRoles.append( + SubagentDisplayRole( + id: defaultId, + backendRoleId: matchedBackend?.id, + isDefaultAgentRole: true, + name: defaultName, + agentId: agent.agentId, + agentLabel: label, + modeId: matchedBackend?.modeId, + configValues: matchedBackend?.configValues ?? [:], + personaPrompt: persona, + teamId: matchedBackend?.teamId + ) ) - } else { - Section("已配置 MCP 服务 (\(filtered.count))") { - ForEach(filtered) { server in + } + + let customRoles: [SubagentDisplayRole] = roles + .filter { !matchedBackendIds.contains($0.id) } + .map { role in + let label = AgentBrand.displayName(role.agentId) + let persona = role.personaPrompt.isEmpty ? role.summary : role.personaPrompt + return SubagentDisplayRole( + id: role.id, + backendRoleId: role.id, + isDefaultAgentRole: false, + name: role.name, + agentId: role.agentId, + agentLabel: label, + modeId: role.modeId, + configValues: role.configValues, + personaPrompt: persona, + teamId: role.teamId + ) + } + + return customRoles + defaultRoles + } + + private var filteredSubagentRoles: [SubagentDisplayRole] { + let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !q.isEmpty else { return displaySubagentRoles } + return displaySubagentRoles.filter { + $0.name.lowercased().contains(q) + || $0.agentLabel.lowercased().contains(q) + || $0.agentId.lowercased().contains(q) + || $0.personaPrompt.lowercased().contains(q) + } + } + + @ViewBuilder + private var skillsListContent: some View { + let filtered = filteredSkills + Section("已安装技能 (\(filtered.count))") { + ForEach(filtered) { skill in + Button { + selectedSkillForDetail = skill + } label: { VStack(alignment: .leading, spacing: 6) { HStack(spacing: 8) { - Image(systemName: "server.rack") + Image(systemName: "sparkles") .font(.caption.weight(.bold)) - .foregroundStyle(.blue) - Text(server.id) - .font(.body.weight(.semibold)) + .foregroundStyle(.purple) + Text(skill.name) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.primary) Spacer() - Text(server.transportLabel) - .font(.caption2.monospaced().weight(.semibold)) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(Capsule().fill(Color.blue.opacity(0.14))) - .foregroundStyle(.blue) - if server.global { + if skill.global { Text("全局") .font(.caption2.weight(.semibold)) .padding(.horizontal, 6) .padding(.vertical, 2) - .background(Capsule().fill(Color.green.opacity(0.14))) - .foregroundStyle(.green) + .background(Capsule().fill(Color.purple.opacity(0.14))) + .foregroundStyle(.purple) } + Image(systemName: "chevron.right") + .font(.caption2) + .foregroundStyle(.tertiary) } - Text(server.commandSummary) - .font(.caption.monospaced()) - .foregroundStyle(.secondary) - .lineLimit(2) - if !server.apps.isEmpty { + if let desc = skill.description, !desc.isEmpty { + Text(desc) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + } + if !skill.apps.isEmpty { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 6) { - ForEach(server.apps, id: \.self) { app in + ForEach(skill.apps, id: \.self) { app in Text(app) .font(.caption2.monospaced()) .padding(.horizontal, 6) @@ -773,160 +881,229 @@ struct SkillsHubSettingsView: View { } } } - .padding(.vertical, 4) + .padding(.vertical, 3) } + .buttonStyle(.plain) } } } @ViewBuilder - private var pluginsListContent: some View { - let filtered = filteredPlugins - if filtered.isEmpty { - ContentUnavailableView( - "暂无已安装插件", - systemImage: "puzzlepiece.extension", - description: Text("在 VibeX 桌面端插件中心安装的插件将显示在此处。") - ) - } else { - Section("已安装插件 (\(filtered.count))") { - ForEach(filtered) { plugin in - VStack(alignment: .leading, spacing: 6) { - HStack(spacing: 8) { - Image(systemName: "puzzlepiece.extension.fill") - .font(.caption.weight(.bold)) - .foregroundStyle(plugin.enabled ? .orange : .secondary) - Text(plugin.name) - .font(.body.weight(.semibold)) - Text("v\(plugin.version)") - .font(.caption2.monospaced()) - .foregroundStyle(.secondary) - Spacer() - Text(plugin.enabled ? "已启用" : "已停用") + private var mcpListContent: some View { + let filtered = filteredMcpServers + Section("已配置 MCP 服务 (\(filtered.count))") { + ForEach(filtered) { server in + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 8) { + Image(systemName: "server.rack") + .font(.caption.weight(.bold)) + .foregroundStyle(.blue) + Text(server.id) + .font(.subheadline.weight(.semibold)) + Spacer() + Text(server.transportLabel) + .font(.caption2.monospaced().weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Capsule().fill(Color.blue.opacity(0.14))) + .foregroundStyle(.blue) + if server.global { + Text("全局") .font(.caption2.weight(.semibold)) .padding(.horizontal, 6) .padding(.vertical, 2) - .background( - Capsule().fill( - plugin.enabled - ? Color.green.opacity(0.15) - : Color.secondary.opacity(0.14) - ) - ) - .foregroundStyle(plugin.enabled ? .green : .secondary) + .background(Capsule().fill(Color.green.opacity(0.14))) + .foregroundStyle(.green) } - if let desc = plugin.description, !desc.isEmpty { - Text(desc) - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(2) + } + Text(server.commandSummary) + .font(.caption.monospaced()) + .foregroundStyle(.secondary) + .lineLimit(2) + if !server.apps.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 6) { + ForEach(server.apps, id: \.self) { app in + Text(app) + .font(.caption2.monospaced()) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(Color.secondary.opacity(0.12)) + ) + .foregroundStyle(.secondary) + } + } } - HStack(spacing: 10) { - Label(plugin.builtin ? "内置插件" : plugin.sourceKind, systemImage: "shippingbox") + } + } + .padding(.vertical, 3) + } + } + } + + @ViewBuilder + private var pluginsListContent: some View { + let filtered = filteredPlugins + Section("已安装插件 (\(filtered.count))") { + ForEach(filtered) { plugin in + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 8) { + Image(systemName: "puzzlepiece.extension.fill") + .font(.caption.weight(.bold)) + .foregroundStyle(plugin.enabled ? .orange : .secondary) + Text(plugin.name) + .font(.subheadline.weight(.semibold)) + Text("v\(plugin.version)") + .font(.caption2.monospaced()) + .foregroundStyle(.secondary) + Spacer() + Text(plugin.enabled ? "已启用" : "已停用") + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + Capsule().fill( + plugin.enabled + ? Color.green.opacity(0.15) + : Color.secondary.opacity(0.14) + ) + ) + .foregroundStyle(plugin.enabled ? .green : .secondary) + } + if let desc = plugin.description, !desc.isEmpty { + Text(desc) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + } + HStack(spacing: 10) { + Label(plugin.builtin ? "内置插件" : plugin.sourceKind, systemImage: "shippingbox") + .font(.caption2) + .foregroundStyle(.tertiary) + if !plugin.skills.isEmpty { + Label("\(plugin.skills.count) 项技能", systemImage: "sparkles") + .font(.caption2) + .foregroundStyle(.tertiary) + } + if plugin.mcpCount > 0 { + Label("\(plugin.mcpCount) 个 MCP", systemImage: "server.rack") .font(.caption2) .foregroundStyle(.tertiary) - if !plugin.skills.isEmpty { - Label("\(plugin.skills.count) 项技能", systemImage: "sparkles") - .font(.caption2) - .foregroundStyle(.tertiary) - } - if plugin.mcpCount > 0 { - Label("\(plugin.mcpCount) 个 MCP", systemImage: "server.rack") - .font(.caption2) - .foregroundStyle(.tertiary) - } } } - .padding(.vertical, 4) } + .padding(.vertical, 3) } } } @ViewBuilder private var subagentsListContent: some View { - let matchedRoles = filteredRoles - let matchedAgents = filteredAgents - - if matchedRoles.isEmpty && matchedAgents.isEmpty { - ContentUnavailableView( - "暂无子代理与角色", - systemImage: "person.2.badge.gearshape", - description: Text("协作空间角色与已启用的子代理执行器将在此展示。") - ) - } else { - if !matchedRoles.isEmpty { - Section("子代理角色预设 (\(matchedRoles.count))") { - ForEach(matchedRoles) { role in - VStack(alignment: .leading, spacing: 6) { - HStack(spacing: 8) { - Image(systemName: "person.crop.circle.badge.Checkmark") - .foregroundStyle(.indigo) - Text(role.name) - .font(.body.weight(.semibold)) - if let team = role.teamId, !team.isEmpty { - Text(team) - .font(.caption2.weight(.medium)) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(Capsule().fill(Color.indigo.opacity(0.14))) - .foregroundStyle(.indigo) - } - Spacer() - AgentModelLabel(agent: role.agentId, model: AgentBrand.displayName(role.agentId), iconSize: 12) - .font(.caption2) - .foregroundStyle(.secondary) - } - let desc = role.summary.isEmpty ? role.personaPrompt : role.summary - if !desc.isEmpty { - Text(desc) - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(2) + let customList = filteredSubagentRoles.filter { !$0.isDefaultAgentRole } + let defaultList = filteredSubagentRoles.filter(\.isDefaultAgentRole) + + Section { + if customList.isEmpty { + Button { + showingNewSubagentRole = true + } label: { + HStack(spacing: 10) { + Image(systemName: "plus.circle.fill") + .foregroundStyle(Color.accentColor) + Text("新建自定义子代理角色") + .font(.subheadline.weight(.medium)) + .foregroundStyle(.primary) + Spacer() + } + .padding(.vertical, 2) + } + } else { + ForEach(customList) { role in + subagentRoleRow(role) + .swipeActions(edge: .trailing, allowsFullSwipe: true) { + Button(role: .destructive) { + deleteSubagentRole(role) + } label: { + Label("删除", systemImage: "trash") } } - .padding(.vertical, 4) - } } } + } header: { + Text("自定义角色 (\(customList.count))") + } - if !matchedAgents.isEmpty { - Section("可用 Agent 执行引擎 (\(matchedAgents.count))") { - ForEach(matchedAgents) { agent in - HStack(spacing: 10) { - AgentIconView(agent: agent.id, size: 22) - .overlay(alignment: .bottomTrailing) { - Circle() - .fill(agent.usable ? Color.green : Color.orange) - .frame(width: 7, height: 7) - .overlay(Circle().stroke(Color(.secondarySystemGroupedBackground), lineWidth: 1.5)) - .offset(x: 2, y: 2) - } - VStack(alignment: .leading, spacing: 2) { - Text(AgentBrand.displayName(agent.id, hostName: agent.displayName)) - .font(.body.weight(.medium)) - Text(agent.id) - .font(.caption2.monospaced()) - .foregroundStyle(.secondary) - } - Spacer() - Text(agent.usable ? "就绪" : "未就绪") - .font(.caption2.weight(.semibold)) - .padding(.horizontal, 7) - .padding(.vertical, 3) - .background( - Capsule().fill( - agent.usable - ? Color.green.opacity(0.15) - : Color.orange.opacity(0.15) - ) - ) - .foregroundStyle(agent.usable ? .green : .orange) - } + if !defaultList.isEmpty { + Section("默认委派配置 (\(defaultList.count))") { + ForEach(defaultList) { role in + subagentRoleRow(role) + } + } + } + } + + private func subagentRoleRow(_ role: SubagentDisplayRole) -> some View { + Button { + editingSubagentRole = role + } label: { + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 8) { + AgentIconView(agent: role.agentId, size: 18) + Text(role.name) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.primary) + .lineLimit(1) + + Spacer(minLength: 4) + + Text(role.agentLabel) + .font(.caption2.weight(.medium)) + .padding(.horizontal, 6) .padding(.vertical, 2) + .background( + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(Color.secondary.opacity(0.12)) + ) + .foregroundStyle(.secondary) + + if let mode = role.modeId, !mode.isEmpty { + Text(mode) + .font(.caption2.monospaced()) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(Color.accentColor.opacity(0.12)) + ) + .foregroundStyle(Color.accentColor) } + + Image(systemName: "pencil") + .font(.caption) + .foregroundStyle(.tertiary) + } + + if !role.personaPrompt.isEmpty { + Text(role.personaPrompt) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) } } + .padding(.vertical, 3) + } + .buttonStyle(.plain) + } + + private func deleteSubagentRole(_ role: SubagentDisplayRole) { + guard !role.isDefaultAgentRole, let client = servers.activeClient() else { return } + let targetId = role.backendRoleId ?? role.id + roles.removeAll { $0.id == targetId } + Task { + try? await client.collabDeleteRole(roleID: targetId) + await reloadAll() } } @@ -959,45 +1136,154 @@ struct SkillsHubSettingsView: View { } } - private var filteredRoles: [CollabRole] { - let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - guard !q.isEmpty else { return roles } - return roles.filter { - $0.name.lowercased().contains(q) - || $0.personaPrompt.lowercased().contains(q) - || $0.agentId.lowercased().contains(q) - } - } - - private var filteredAgents: [CatalogAgent] { - let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - guard !q.isEmpty else { return agents } - return agents.filter { - $0.displayName.lowercased().contains(q) - || $0.id.lowercased().contains(q) - } - } - private func reloadAll() async { guard let client = servers.activeClient() else { - errorMessage = "当前未连接电脑,请先配对电脑后查看技能与扩展。" + authExpired = true return } isLoading = true + authExpired = false errorMessage = nil defer { isLoading = false } - async let fetchedSkills = try? client.localSkills() - async let fetchedMcp = try? client.localMcpServers() - async let fetchedPlugins = try? client.pluginCatalog() - async let fetchedRoles = try? client.collabRoles() - async let fetchedCatalog = try? client.agentCatalog() - - if let s = await fetchedSkills { skills = s } - if let m = await fetchedMcp { mcpServers = m } - if let p = await fetchedPlugins { plugins = p } - if let r = await fetchedRoles { roles = r } - if let c = await fetchedCatalog { agents = c } + do { + async let fetchedSkills = client.localSkills() + async let fetchedMcp = try? client.localMcpServers() + async let fetchedPlugins = try? client.pluginCatalog() + async let fetchedRoles = try? client.collabRoles() + async let fetchedBarAgents = try? client.managedAgentBar() + + skills = try await fetchedSkills + if let m = await fetchedMcp { mcpServers = m } + if let p = await fetchedPlugins { plugins = p } + if let r = await fetchedRoles { roles = r } + if let b = await fetchedBarAgents { barAgents = b } + } catch let HostError.server(status, _) where status == 401 || status == 403 { + authExpired = true + } catch { + errorMessage = error.localizedDescription + } + } +} + +struct SubagentRoleEditorSheet: View { + let existingRole: SubagentDisplayRole? + let availableAgents: [ManagedAgentBarItem] + let client: HostClient + let onSaved: () -> Void + + @Environment(\.dismiss) private var dismiss + @State private var roleName = "" + @State private var selectedAgentId = "" + @State private var modeId = "" + @State private var personaPrompt = "" + @State private var isSaving = false + @State private var errorMessage: String? + + private var isDefaultRole: Bool { + existingRole?.isDefaultAgentRole == true + } + + private var canSave: Bool { + !isSaving + && !roleName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + && !selectedAgentId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + var body: some View { + NavigationStack { + Form { + Section("角色名称") { + TextField("例如:前端工程师", text: $roleName) + .disabled(isDefaultRole) + .foregroundStyle(isDefaultRole ? .secondary : .primary) + } + + Section("选择角色 Agent") { + if availableAgents.isEmpty { + TextField("Agent ID (例如 codex / claude_code)", text: $selectedAgentId) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .disabled(isDefaultRole) + } else { + Picker("Agent", selection: $selectedAgentId) { + ForEach(availableAgents) { agent in + Text(AgentBrand.displayName(agent.agentId, hostName: agent.displayName)) + .tag(agent.agentId) + } + } + .disabled(isDefaultRole) + } + + TextField("默认模式 / 模型(可选)", text: $modeId) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .font(.subheadline.monospaced()) + } + + Section("人设(可选)") { + TextField("定义此子代理角色的职责边界与输出要求...", text: $personaPrompt, axis: .vertical) + .lineLimit(3...6) + } + + if let errorMessage { + Section { + Text(errorMessage) + .font(.footnote) + .foregroundStyle(.red) + } + } + } + .navigationTitle(existingRole == nil ? "新建角色" : "编辑角色") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("取消") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + if isSaving { + ProgressView() + } else { + Button("保存", action: save) + .fontWeight(.semibold) + .disabled(!canSave) + } + } + } + .onAppear { + if let role = existingRole { + roleName = role.name + selectedAgentId = role.agentId + modeId = role.modeId ?? "" + personaPrompt = role.personaPrompt + } else { + selectedAgentId = availableAgents.first?.agentId ?? "claude_code" + } + } + } + } + + private func save() { + guard canSave else { return } + isSaving = true + errorMessage = nil + Task { + do { + try await client.collabSaveRole( + id: existingRole?.backendRoleId, + name: roleName.trimmingCharacters(in: .whitespacesAndNewlines), + agentId: selectedAgentId.trimmingCharacters(in: .whitespacesAndNewlines), + modeId: modeId.trimmingCharacters(in: .whitespacesAndNewlines), + personaPrompt: personaPrompt.trimmingCharacters(in: .whitespacesAndNewlines), + teamId: existingRole?.teamId ?? "" + ) + onSaved() + dismiss() + } catch { + errorMessage = error.localizedDescription + isSaving = false + } + } } } diff --git a/mobile/ios/App/StreamingText.swift b/mobile/ios/App/StreamingText.swift index 99db5c717..7d31521bd 100644 --- a/mobile/ios/App/StreamingText.swift +++ b/mobile/ios/App/StreamingText.swift @@ -931,6 +931,7 @@ struct StreamingMessageText: View { .padding(.top, 2) } } + .frame(maxWidth: .infinity, alignment: .leading) .textSelection(.enabled) .onChange(of: text) { _, newValue in targetText = newValue @@ -1370,26 +1371,25 @@ private struct MarkdownBlockView: View { var body: some View { switch block { case .heading(let level, let text): - HStack(alignment: .lastTextBaseline, spacing: 4) { - Text(Self.inlineAttributed(text)) - .font(.system(size: headingSize(level), weight: .semibold)) - .tracking(0.1) - .foregroundStyle(.primary) - if showCursor { StreamingCursorPill() } - } - .padding(.top, level <= 2 ? 3 : 1) + Text(Self.inlineAttributed(text, appendCursor: showCursor)) + .font(.system(size: headingSize(level), weight: .semibold)) + .tracking(0.1) + .foregroundStyle(.primary) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.top, level <= 2 ? 3 : 1) case .paragraph(let text): - HStack(alignment: .lastTextBaseline, spacing: 3) { - Text(Self.inlineAttributed(text)) - .font(.system(size: 14.5)) - .lineSpacing(4.5) - .foregroundStyle(.primary) - if showCursor { StreamingCursorPill() } - } + Text(Self.inlineAttributed(text, appendCursor: showCursor)) + .font(.system(size: 14.5)) + .lineSpacing(4.5) + .foregroundStyle(.primary) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) case .codeBlock(let language, let code): VibeXMarkdownCodeSwitch(language: language, code: code) + .frame(maxWidth: .infinity, alignment: .leading) case .bulletList(let items): VStack(alignment: .leading, spacing: 5) { @@ -1399,18 +1399,16 @@ private struct MarkdownBlockView: View { .font(.system(size: 14.5, weight: .bold)) .foregroundStyle(.secondary) .frame(width: 10, alignment: .center) - HStack(alignment: .lastTextBaseline, spacing: 3) { - Text(Self.inlineAttributed(item)) - .font(.system(size: 14.5)) - .lineSpacing(4) - .foregroundStyle(.primary) - if showCursor && idx == items.count - 1 { - StreamingCursorPill() - } - } + Text(Self.inlineAttributed(item, appendCursor: showCursor && idx == items.count - 1)) + .font(.system(size: 14.5)) + .lineSpacing(4) + .foregroundStyle(.primary) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) } } } + .frame(maxWidth: .infinity, alignment: .leading) .padding(.vertical, 2) case .numberedList(let items): @@ -1420,18 +1418,16 @@ private struct MarkdownBlockView: View { Text("\(entry.number).") .font(.system(size: 13.5, weight: .medium, design: .monospaced)) .foregroundStyle(.secondary) - HStack(alignment: .lastTextBaseline, spacing: 3) { - Text(Self.inlineAttributed(entry.text)) - .font(.system(size: 14.5)) - .lineSpacing(4) - .foregroundStyle(.primary) - if showCursor && idx == items.count - 1 { - StreamingCursorPill() - } - } + Text(Self.inlineAttributed(entry.text, appendCursor: showCursor && idx == items.count - 1)) + .font(.system(size: 14.5)) + .lineSpacing(4) + .foregroundStyle(.primary) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) } } } + .frame(maxWidth: .infinity, alignment: .leading) .padding(.vertical, 2) case .taskList(let items): @@ -1441,19 +1437,17 @@ private struct MarkdownBlockView: View { Image(systemName: item.checked ? "checkmark.square.fill" : "square") .font(.system(size: 14, weight: .medium)) .foregroundStyle(item.checked ? Color.accentColor : .secondary) - HStack(alignment: .lastTextBaseline, spacing: 3) { - Text(Self.inlineAttributed(item.text)) - .font(.system(size: 14.5)) - .lineSpacing(4) - .strikethrough(item.checked, color: .secondary) - .foregroundStyle(item.checked ? .secondary : .primary) - if showCursor && idx == items.count - 1 { - StreamingCursorPill() - } - } + Text(Self.inlineAttributed(item.text, appendCursor: showCursor && idx == items.count - 1)) + .font(.system(size: 14.5)) + .lineSpacing(4) + .strikethrough(item.checked, color: .secondary) + .foregroundStyle(item.checked ? .secondary : .primary) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) } } } + .frame(maxWidth: .infinity, alignment: .leading) .padding(.vertical, 2) case .blockquote(let text): @@ -1463,6 +1457,7 @@ private struct MarkdownBlockView: View { .font(.system(size: 14)) .lineSpacing(4) .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity, alignment: .leading) .padding(.horizontal, 10) .padding(.vertical, 7) @@ -1490,6 +1485,8 @@ private struct MarkdownBlockView: View { .font(.system(size: 13.5)) .lineSpacing(3.5) .foregroundStyle(.primary.opacity(0.9)) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) } } .frame(maxWidth: .infinity, alignment: .leading) @@ -1546,14 +1543,12 @@ private struct MarkdownBlockView: View { /// Parses inline Markdown (`**bold**`, `*italic*`, `` `code` ``, `[label](url)`, `$math$`) /// and styles inline code & file references to match `AstryxMarkdown.tsx` + `conv-markdown.css`. - static func inlineAttributed(_ raw: String) -> AttributedString { + static func inlineAttributed(_ raw: String, appendCursor: Bool = false) -> AttributedString { let normalized = raw.replacingOccurrences(of: #"\$([^$\n]+)\$"#, with: "`$1`", options: .regularExpression) let options = AttributedString.MarkdownParsingOptions( interpretedSyntax: .inlineOnlyPreservingWhitespace ) - guard var attributed = try? AttributedString(markdown: normalized, options: options) else { - return AttributedString(raw) - } + var attributed = (try? AttributedString(markdown: normalized, options: options)) ?? AttributedString(raw) for run in attributed.runs { if run.inlinePresentationIntent?.contains(.code) == true { let textSlice = String(attributed[run.range].characters) @@ -1569,6 +1564,12 @@ private struct MarkdownBlockView: View { attributed[run.range].underlineStyle = .single } } + if appendCursor { + var cursor = AttributedString(" ▍") + cursor.foregroundColor = .accentColor + cursor.font = .system(size: 13, weight: .bold) + attributed.append(cursor) + } return attributed } diff --git a/mobile/ios/App/TaskActivityController.swift b/mobile/ios/App/TaskActivityController.swift index fde959400..529239f5c 100644 --- a/mobile/ios/App/TaskActivityController.swift +++ b/mobile/ios/App/TaskActivityController.swift @@ -3,22 +3,27 @@ import CompanionCore import Foundation import UIKit -/// Mirrors the Agent's task list into a Live Activity: Dynamic Island where the iPhone has one, -/// Lock Screen everywhere else. iOS only lets the app change it while the app is running, so it -/// follows the plan while the app is open and keeps its last state once the app is suspended. +/// Global controller that mirrors the active VibeX Agent session into iOS Live Activities: +/// Dynamic Island on supporting iPhones and Lock Screen / Notification Center banner everywhere else. +/// Converts low-level Agent steps into clean, code-free activity phases ("代码开发中", "思考规划中", +/// "等待你确认", etc.) and drives a smooth circular progress ring (`0.0 ... 1.0`). @MainActor final class TaskActivityController { + static let shared = TaskActivityController() + private var activity: Activity? + private var activeConversationID: String? private var lastState: TaskActivityAttributes.ContentState? private var runStart: Date? + private var peakProgress: Double = 0.12 private var lingerTask: Task? private var lastPush = Date.distantPast private var background = UIBackgroundTaskIdentifier.invalid private var observer: NSObjectProtocol? - /// How long the activity stays fresh without another push; past it the widget says syncing paused. - private static let freshness: TimeInterval = 45 + /// How long the activity stays fresh without another push. + private static let freshness: TimeInterval = 90 init() { observer = NotificationCenter.default.addObserver( @@ -32,12 +37,14 @@ final class TaskActivityController { if let observer { NotificationCenter.default.removeObserver(observer) } } - /// iOS suspends the app shortly after it leaves the foreground; ask for the extra time it grants - /// so the activity keeps following a run that is still going. private func holdBackgroundTime() { guard activity != nil, background == .invalid else { return } let app = UIApplication.shared - background = app.beginBackgroundTask { [weak self] in self?.releaseBackgroundTime() } + background = app.beginBackgroundTask(withName: "VibeXLiveActivityKeepAlive") { [weak self] in + Task { @MainActor in + self?.releaseBackgroundTime() + } + } } private func releaseBackgroundTime() { @@ -46,53 +53,217 @@ final class TaskActivityController { background = .invalid } - /// `tasks` is the Agent's published plan; without an unfinished plan the activity follows the - /// run itself and shows `step` (the latest tool call) with an elapsed timer. - func sync(title: String, tasks: [PlanTask], step: String?, running: Bool) { + /// Synchronizes the Dynamic Island & Lock Screen Live Activity from either `ConversationModel` + /// or the global `CompanionAttentionCenter` background poller. + func sync( + conversationID: String = "default", + projectName: String = "VibeX", + title: String, + tasks: [PlanTask], + latestToolName: String? = nil, + stepCount: Int = 0, + hasThinking: Bool = false, + hasTextOutput: Bool = false, + hasPendingApproval: Bool = false, + approvalSummary: String? = nil, + running: Bool + ) { let completed = tasks.filter { $0.status == .completed }.count let planActive = !tasks.isEmpty && completed < tasks.count - guard running || planActive else { - finish() + let effectivelyActive = running || planActive || hasPendingApproval + + guard effectivelyActive else { + if activeConversationID == nil || activeConversationID == conversationID { + finish() + } return } + lingerTask?.cancel() lingerTask = nil - if runStart == nil { runStart = Date() } - let current = tasks.first { $0.status == .running } ?? tasks.first { $0.status == .pending } + + if activeConversationID != conversationID { + activeConversationID = conversationID + runStart = Date() + peakProgress = 0.12 + } else if runStart == nil { + runStart = Date() + peakProgress = 0.12 + } + + let resolved = Self.resolveHumanStage( + tasks: tasks, + completed: completed, + planActive: planActive, + latestToolName: latestToolName, + stepCount: stepCount, + hasThinking: hasThinking, + hasTextOutput: hasTextOutput, + hasPendingApproval: hasPendingApproval, + approvalSummary: approvalSummary + ) + + if resolved.progress > peakProgress { + peakProgress = resolved.progress + } + let smoothProgress = planActive ? resolved.progress : max(peakProgress, resolved.progress) + let state = TaskActivityAttributes.ContentState( + phase: resolved.phase, + stageTitle: resolved.stageTitle, + stageSubtitle: resolved.stageSubtitle, + progress: min(max(smoothProgress, 0.10), 0.96), completed: planActive ? completed : 0, total: planActive ? tasks.count : 0, - currentTask: planActive ? (current?.label ?? "") : (step ?? "处理中"), - isRunning: running, + stepCount: max(stepCount, completed), + isRunning: running || hasPendingApproval, startedAt: runStart ?? Date() ) + guard state != lastState || Date().timeIntervalSince(lastPush) > Self.freshness / 3 else { return } lastState = state lastPush = Date() let content = ActivityContent(state: state, staleDate: Date().addingTimeInterval(Self.freshness)) + if let activity { Task { await activity.update(content) } } else { - start(title: title, state: state) + // Reattach to an existing system Live Activity if one is already running + if let existing = Activity.activities.first { + activity = existing + Task { await existing.update(content) } + } else { + start(projectName: projectName, title: title, state: state) + } } } - /// The Dynamic Island only shows live activities, so the finished state is pushed while the - /// activity is still live and held for a moment before it is ended. - private func finish() { + private static func resolveHumanStage( + tasks: [PlanTask], + completed: Int, + planActive: Bool, + latestToolName: String?, + stepCount: Int, + hasThinking: Bool, + hasTextOutput: Bool, + hasPendingApproval: Bool, + approvalSummary: String? + ) -> (phase: VibeXActivityPhase, stageTitle: String, stageSubtitle: String, progress: Double) { + let baseProgress: Double + if planActive && !tasks.isEmpty { + let raw = Double(completed) / Double(tasks.count) + baseProgress = min(max(raw, 0.15), 0.94) + } else { + // Smooth asymptotic curve based on stepCount: 0 -> 0.18, 2 -> 0.42, 5 -> 0.66, 10 -> 0.82 + let stepFactor = 1.0 - exp(-Double(max(1, stepCount)) * 0.22) + baseProgress = min(0.16 + stepFactor * 0.74, 0.92) + } + + if hasPendingApproval { + return ( + phase: .waitingInput, + stageTitle: "等待你确认", + stageSubtitle: approvalSummary ?? "需要批准操作权限或确认执行方案", + progress: max(baseProgress, 0.55) + ) + } + + if let tool = latestToolName?.lowercased(), !tool.isEmpty { + if tool.contains("edit") || tool.contains("write") || tool.contains("patch") + || tool.contains("create") || tool.contains("replace") + { + return ( + phase: .developing, + stageTitle: "代码开发中", + stageSubtitle: "正在编写与修改项目模块", + progress: max(baseProgress, 0.58) + ) + } + if tool.contains("bash") || tool.contains("exec") || tool.contains("run") + || tool.contains("shell") || tool.contains("terminal") || tool.contains("test") + || tool.contains("check") || tool.contains("build") + { + return ( + phase: .verifying, + stageTitle: "调试验证中", + stageSubtitle: "正在执行构建或测试验证", + progress: max(baseProgress, 0.74) + ) + } + if tool.contains("read") || tool.contains("search") || tool.contains("grep") + || tool.contains("find") || tool.contains("list") || tool.contains("view") + || tool.contains("tree") || tool.contains("glob") + { + return ( + phase: .exploring, + stageTitle: "查阅项目中", + stageSubtitle: "正在检索项目结构与依赖关系", + progress: max(baseProgress, 0.36) + ) + } + return ( + phase: .developing, + stageTitle: "代码开发中", + stageSubtitle: "正在调用研发工具推进任务", + progress: max(baseProgress, 0.50) + ) + } + + if hasTextOutput { + return ( + phase: .summarizing, + stageTitle: "整理回复中", + stageSubtitle: "正在生成总结与解决方案", + progress: max(baseProgress, 0.88) + ) + } + + if hasThinking { + return ( + phase: .thinking, + stageTitle: "思考规划中", + stageSubtitle: "正在分析需求与梳理实现路径", + progress: max(baseProgress, 0.24) + ) + } + + return ( + phase: .thinking, + stageTitle: "准备执行中", + stageSubtitle: "VibeX 正在同步工作区状态", + progress: 0.16 + ) + } + + /// Pushes the 100% completed state into the Dynamic Island / Lock Screen before dismissing. + func finish(failedMessage: String? = nil) { runStart = nil + peakProgress = 0.12 guard activity != nil, lingerTask == nil, var done = lastState, done.isRunning else { return } done.isRunning = false + if let failedMessage { + done.phase = .failed + done.stageTitle = "执行中断" + done.stageSubtitle = failedMessage + } else { + done.phase = .completed + done.stageTitle = "任务已完成" + done.stageSubtitle = "全部开发步骤已执行完毕,点击查看结果" + done.progress = 1.0 + if done.total > 0 { + done.completed = done.total + } + } lastState = done guard let current = activity else { return } lingerTask = Task { [weak self] in let app = UIApplication.shared - var background = UIBackgroundTaskIdentifier.invalid - background = app.beginBackgroundTask { app.endBackgroundTask(background) } + var bg = UIBackgroundTaskIdentifier.invalid + bg = app.beginBackgroundTask { app.endBackgroundTask(bg) } await current.update(ActivityContent(state: done, staleDate: nil)) - try? await Task.sleep(for: .seconds(20)) - if !Task.isCancelled { self?.end(final: done, after: 30) } - app.endBackgroundTask(background) + try? await Task.sleep(for: .seconds(25)) + if !Task.isCancelled { self?.end(final: done, after: 45) } + app.endBackgroundTask(bg) } } @@ -102,10 +273,13 @@ final class TaskActivityController { end(after: 0) } - private func start(title: String, state: TaskActivityAttributes.ContentState) { + private func start(projectName: String, title: String, state: TaskActivityAttributes.ContentState) { guard ActivityAuthorizationInfo().areActivitiesEnabled else { return } activity = try? Activity.request( - attributes: TaskActivityAttributes(conversationTitle: title), + attributes: TaskActivityAttributes( + projectName: projectName, + conversationTitle: title + ), content: ActivityContent(state: state, staleDate: Date().addingTimeInterval(Self.freshness)) ) } @@ -113,8 +287,10 @@ final class TaskActivityController { private func end(final: TaskActivityAttributes.ContentState? = nil, after seconds: TimeInterval) { guard let current = activity else { return } activity = nil + activeConversationID = nil lastState = nil runStart = nil + peakProgress = 0.12 let content = final.map { ActivityContent(state: $0, staleDate: nil) } Task { await current.end( diff --git a/mobile/ios/App/ThinkingView.swift b/mobile/ios/App/ThinkingView.swift index b5fb230a1..7102d303b 100644 --- a/mobile/ios/App/ThinkingView.swift +++ b/mobile/ios/App/ThinkingView.swift @@ -49,10 +49,12 @@ struct ThinkingView: View { if working { ShimmerText(text: workingLabel) .font(.system(size: 12.5, weight: .medium)) + .fixedSize(horizontal: true, vertical: false) } else { Text(doneLabel) .font(.system(size: 12.5, weight: .medium)) .foregroundStyle(.secondary) + .fixedSize(horizontal: true, vertical: false) } if !expanded, let previewLine { @@ -63,6 +65,7 @@ struct ThinkingView: View { .foregroundStyle(.tertiary) .lineLimit(1) .truncationMode(.tail) + .layoutPriority(-1) } Spacer(minLength: 4) @@ -72,6 +75,7 @@ struct ThinkingView: View { .foregroundStyle(.tertiary) .rotationEffect(.degrees(expanded ? 90 : 0)) } + .frame(maxWidth: .infinity, alignment: .leading) .padding(.horizontal, 10) .padding(.vertical, 6) .background( @@ -95,6 +99,7 @@ struct ThinkingView: View { .font(.system(size: 12.5)) .foregroundStyle(.secondary) .lineSpacing(3) + .fixedSize(horizontal: false, vertical: true) .textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) } diff --git a/mobile/ios/App/ToolChips.swift b/mobile/ios/App/ToolChips.swift index 4662aabb1..e54a7172b 100644 --- a/mobile/ios/App/ToolChips.swift +++ b/mobile/ios/App/ToolChips.swift @@ -79,6 +79,7 @@ struct ToolChipsView: View { .font(.system(size: 12.5, weight: .medium)) .monospacedDigit() .foregroundStyle(.secondary) + .fixedSize(horizontal: true, vertical: false) if !runOpen, let summary = latestToolSummary { Text("·") @@ -88,6 +89,7 @@ struct ToolChipsView: View { .foregroundStyle(.tertiary) .lineLimit(1) .truncationMode(.tail) + .layoutPriority(-1) } Spacer(minLength: 4) @@ -97,6 +99,7 @@ struct ToolChipsView: View { .foregroundStyle(.tertiary) .rotationEffect(.degrees(runOpen ? 90 : 0)) } + .frame(maxWidth: .infinity, alignment: .leading) .padding(.horizontal, 10) .padding(.vertical, 6) .background( diff --git a/mobile/ios/ExportOptions.plist b/mobile/ios/ExportOptions.plist new file mode 100644 index 000000000..c66101d67 --- /dev/null +++ b/mobile/ios/ExportOptions.plist @@ -0,0 +1,22 @@ + + + + + destination + upload + manageAppVersionAndBuildNumber + + method + app-store-connect + signingStyle + automatic + stripSwiftSymbols + + teamID + DD67H4228U + testFlightInternalTestingOnly + + uploadSymbols + + + diff --git a/mobile/ios/Info.plist b/mobile/ios/Info.plist index 5f79bf11e..e7055aefa 100644 --- a/mobile/ios/Info.plist +++ b/mobile/ios/Info.plist @@ -2,18 +2,22 @@ + ITSAppUsesNonExemptEncryption + NSAppTransportSecurity NSAllowsLocalNetworking NSCameraUsageDescription - 扫描电脑上的配对二维码 + 扫描电脑上的配对二维码以连接 VibeX 桌面端 + NSLocalNetworkUsageDescription + 发现在局域网内运行的 VibeX 电脑并建立实时连接 + NSPhotoLibraryUsageDescription + 从相册选择配对二维码图片或向对话附加图片 NSSupportsLiveActivities NSSupportsLiveActivitiesFrequentUpdates - NSLocalNetworkUsageDescription - 连接局域网内的 VibeX 电脑 diff --git a/mobile/ios/Shared/TaskActivityAttributes.swift b/mobile/ios/Shared/TaskActivityAttributes.swift index f06bc3b00..f47dc0ab0 100644 --- a/mobile/ios/Shared/TaskActivityAttributes.swift +++ b/mobile/ios/Shared/TaskActivityAttributes.swift @@ -1,16 +1,36 @@ import ActivityKit import Foundation -/// Live Activity for an Agent run (task list progress, or the current step when there is none): Dynamic Island on supporting iPhones, Lock Screen otherwise. +/// High-level human-readable phase of a VibeX Agent session (never raw code). +enum VibeXActivityPhase: String, Codable, Hashable, Sendable { + case thinking // 思考规划中 + case exploring // 查阅项目中 + case developing // 代码开发中 + case verifying // 调试验证中 + case summarizing // 整理回复中 + case waitingInput // 等待你确认(权限/提问) + case completed // 任务已完成 + case failed // 任务执行异常 +} + +/// Live Activity for an Agent run: Dynamic Island on supporting iPhones, Lock Screen everywhere else. struct TaskActivityAttributes: ActivityAttributes { struct ContentState: Codable, Hashable { + var phase: VibeXActivityPhase + /// Short 4-5 char badge title (e.g. "代码开发中", "等待你确认", "思考规划中") + var stageTitle: String + /// Clean, code-free explanation of what VibeX is doing (e.g. "正在编写与更新项目模块") + var stageSubtitle: String + /// Smooth 0.0 ... 1.0 progress for the circular progress ring + var progress: Double var completed: Int var total: Int - var currentTask: String + var stepCount: Int var isRunning: Bool - /// When the current run began; drives the elapsed timer shown while there is no task list. + /// When the current run began; drives the elapsed timer. var startedAt: Date } + var projectName: String var conversationTitle: String } diff --git a/mobile/ios/Sources/CompanionCore/CollaborationModels.swift b/mobile/ios/Sources/CompanionCore/CollaborationModels.swift index 9bbba8b27..05f85a3b0 100644 --- a/mobile/ios/Sources/CompanionCore/CollaborationModels.swift +++ b/mobile/ios/Sources/CompanionCore/CollaborationModels.swift @@ -452,9 +452,30 @@ public struct CollabRole: Decodable, Identifiable, Equatable, Sendable { public let personaPrompt: String public let agentId: String public let modeId: String? + public let configValues: [String: String] + + public init( + id: String, + name: String, + teamId: String? = nil, + summary: String = "", + personaPrompt: String = "", + agentId: String, + modeId: String? = nil, + configValues: [String: String] = [:] + ) { + self.id = id + self.name = name + self.teamId = teamId + self.summary = summary + self.personaPrompt = personaPrompt + self.agentId = agentId + self.modeId = modeId + self.configValues = configValues + } private enum CodingKeys: String, CodingKey { - case id, name, team_id, summary, persona_prompt, agent_id, mode_id + case id, name, team_id, summary, persona_prompt, agent_id, mode_id, config_values } public init(from decoder: Decoder) throws { @@ -466,6 +487,7 @@ public struct CollabRole: Decodable, Identifiable, Equatable, Sendable { personaPrompt = (try? c.decode(String.self, forKey: .persona_prompt)) ?? "" agentId = (try? c.decode(String.self, forKey: .agent_id)) ?? "" modeId = try? c.decodeIfPresent(String.self, forKey: .mode_id) + configValues = (try? c.decode([String: String].self, forKey: .config_values)) ?? [:] } } diff --git a/mobile/ios/Sources/CompanionCore/HostClient.swift b/mobile/ios/Sources/CompanionCore/HostClient.swift index 2a938c09f..8b13ceaa5 100644 --- a/mobile/ios/Sources/CompanionCore/HostClient.swift +++ b/mobile/ios/Sources/CompanionCore/HostClient.swift @@ -419,6 +419,38 @@ public struct HostClient: Sendable { return try await collaborationCall("role.list", as: Page.self).roles ?? [] } + public func collabSaveRole( + id: String? = nil, + name: String, + agentId: String, + modeId: String? = nil, + personaPrompt: String = "", + teamId: String = "" + ) async throws { + var payload: [String: Any] = [ + "name": name, + "teamId": teamId, + "summary": personaPrompt, + "personaPrompt": personaPrompt, + "agentId": agentId, + "modeId": modeId ?? "", + "configValues": [String: String](), + ] + if let id, !id.isEmpty, !id.hasPrefix("default-agent:") { + payload["id"] = id + try await collaborationCommand("role.update", input: payload) + } else { + try await collaborationCommand("role.create", input: payload) + } + } + + public func collabDeleteRole(roleID: String) async throws { + try await collaborationCommand("role.delete", input: [ + "id": roleID, + "roleId": roleID, + ]) + } + public func collabTeams() async throws -> [CollabTeam] { struct Page: Decodable { let teams: [CollabTeam]? } return try await collaborationCall("team.list", as: Page.self).teams ?? [] @@ -603,6 +635,11 @@ public struct HostClient: Sendable { try await call("get_user_system_info", as: HostUserSystemInfo.self) } + public func managedAgentBar() async throws -> [ManagedAgentBarItem] { + let items = try await call("agent_management_bar", as: [ManagedAgentBarItem].self) + return items.filter { $0.enabled && !$0.retired } + } + public func pluginCatalog() async throws -> [PluginCatalogItem] { do { let res: PluginControlCatalogResponse = try await call( diff --git a/mobile/ios/Sources/CompanionCore/SettingsModels.swift b/mobile/ios/Sources/CompanionCore/SettingsModels.swift index e92110bb5..c5cc6f0e1 100644 --- a/mobile/ios/Sources/CompanionCore/SettingsModels.swift +++ b/mobile/ios/Sources/CompanionCore/SettingsModels.swift @@ -235,6 +235,45 @@ public struct PluginControlCatalogResponse: Codable, Equatable, Sendable { } } +// MARK: - Managed Agent Bar Item (for Subagent Default Roles) + +public struct ManagedAgentBarItem: Codable, Equatable, Identifiable, Sendable { + public let agentId: String + public let displayName: String + public let description: String + public let enabled: Bool + public let retired: Bool + public let runtimeVersion: String? + + public var id: String { agentId } + + public init( + agentId: String, + displayName: String, + description: String = "", + enabled: Bool = true, + retired: Bool = false, + runtimeVersion: String? = nil + ) { + self.agentId = agentId + self.displayName = displayName + self.description = description + self.enabled = enabled + self.retired = retired + self.runtimeVersion = runtimeVersion + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: DynamicCodingKey.self) + self.agentId = c.decodeString(forKeys: ["agent_id", "agentId", "id"]) ?? "" + self.displayName = c.decodeString(forKeys: ["display_name", "displayName", "name"]) ?? self.agentId + self.description = c.decodeString(forKeys: ["description"]) ?? "" + self.enabled = c.decodeBool(forKeys: ["enabled"]) ?? true + self.retired = c.decodeBool(forKeys: ["retired"]) ?? false + self.runtimeVersion = c.decodeString(forKeys: ["runtime_version", "runtimeVersion"]) + } +} + // MARK: - Host Environment & User System Info public struct HostSystemEnvironmentInfo: Codable, Equatable, Sendable { diff --git a/mobile/ios/Sources/CompanionCore/WorkspaceModels.swift b/mobile/ios/Sources/CompanionCore/WorkspaceModels.swift index dfb4858a8..f54d5b0d6 100644 --- a/mobile/ios/Sources/CompanionCore/WorkspaceModels.swift +++ b/mobile/ios/Sources/CompanionCore/WorkspaceModels.swift @@ -50,8 +50,8 @@ public struct FileDiff: Identifiable, Equatable, Sendable { public var id: String { path } public var additions: Int { count(.added) } public var deletions: Int { count(.removed) } - /// Untracked files carry no diff; the phone shows their whole content as additions instead. - public var needsContent: Bool { change == .untracked && !isBinary } + /// Untracked or newly added files with no unified diff payload fetch their whole content as additions instead. + public var needsContent: Bool { hunks.isEmpty && !isBinary && change != .deleted } private func count(_ kind: DiffLine.Kind) -> Int { hunks.reduce(0) { $0 + $1.lines.filter { $0.kind == kind }.count } diff --git a/mobile/ios/TaskWidget/TaskActivityWidget.swift b/mobile/ios/TaskWidget/TaskActivityWidget.swift index e11a65db7..e0c51f8a2 100644 --- a/mobile/ios/TaskWidget/TaskActivityWidget.swift +++ b/mobile/ios/TaskWidget/TaskActivityWidget.swift @@ -10,133 +10,447 @@ struct VibeXTaskWidgetBundle: WidgetBundle { struct TaskActivityWidget: Widget { var body: some WidgetConfiguration { ActivityConfiguration(for: TaskActivityAttributes.self) { context in - LockScreenTaskView(title: context.attributes.conversationTitle, state: context.state, stale: context.isStale) - .padding(16) - .activityBackgroundTint(Color(.systemBackground).opacity(0.85)) + LockScreenTaskView( + projectName: context.attributes.projectName, + conversationTitle: context.attributes.conversationTitle, + state: context.state, + stale: context.isStale + ) + .padding(.horizontal, 16) + .padding(.vertical, 14) + .activityBackgroundTint(Color.black.opacity(0.84)) + .activitySystemActionForegroundColor(.white) } dynamicIsland: { context in DynamicIsland { DynamicIslandExpandedRegion(.leading) { - TaskRing(state: context.state, size: 30).padding(.leading, 6).padding(.top, 2) + HStack(spacing: 9) { + VibeXWidgetLogoView(phase: context.state.phase, size: 32) + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 5) { + Text(context.attributes.projectName) + .font(.system(size: 13, weight: .bold)) + .foregroundStyle(.white) + .lineLimit(1) + PhaseBadgePill(phase: context.state.phase, title: context.state.stageTitle) + } + Text(context.attributes.conversationTitle) + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.white.opacity(0.62)) + .lineLimit(1) + } + } + .padding(.leading, 4) + .padding(.top, 2) } + DynamicIslandExpandedRegion(.trailing) { - ProgressLabel(state: context.state, size: 17).padding(.trailing, 6).padding(.top, 2) + VibeXCircularProgressRing( + progress: context.state.progress, + phase: context.state.phase, + size: 36, + lineWidth: 3.2, + showLabel: true + ) + .padding(.trailing, 4) + .padding(.top, 2) } + DynamicIslandExpandedRegion(.bottom) { - VStack(alignment: .leading, spacing: 6) { - Text(context.attributes.conversationTitle) - .font(.system(size: 12, weight: .medium)) - .foregroundStyle(.secondary) - .lineLimit(1) - Text(context.isStale && context.state.isRunning ? staleNote : context.state.currentTask) - .font(.system(size: 15, weight: .medium)) - .lineLimit(2) - .multilineTextAlignment(.leading) - if context.state.total > 0 { TaskProgressBar(state: context.state).padding(.top, 2) } + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 6) { + Image(systemName: phaseSymbol(context.state.phase)) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(phaseTint(context.state.phase)) + + Text(context.isStale && context.state.isRunning ? staleNote : context.state.stageSubtitle) + .font(.system(size: 13.5, weight: .medium)) + .foregroundStyle(.white.opacity(0.92)) + .lineLimit(1) + + Spacer(minLength: 4) + + if context.state.isRunning { + Text(context.state.startedAt, style: .timer) + .font(.system(size: 11.5, weight: .semibold, design: .monospaced)) + .monospacedDigit() + .foregroundStyle(.white.opacity(0.68)) + .frame(maxWidth: 54, alignment: .trailing) + } else { + Text(context.state.phase == .failed ? "需处理" : "100%") + .font(.system(size: 11.5, weight: .semibold, design: .monospaced)) + .foregroundStyle(phaseTint(context.state.phase)) + } + } + + TaskSmoothProgressBar( + progress: context.state.progress, + tint: phaseTint(context.state.phase) + ) } .frame(maxWidth: .infinity, alignment: .leading) .padding(.horizontal, 6) .padding(.top, 6) + .padding(.bottom, 2) } } compactLeading: { - TaskRing(state: context.state, size: 18) + HStack(spacing: 5) { + VibeXWidgetLogoView(phase: context.state.phase, size: 20) + Text(shortCompactLabel(for: context.state)) + .font(.system(size: 11.5, weight: .semibold)) + .foregroundStyle(.white) + .lineLimit(1) + } } compactTrailing: { - ProgressLabel(state: context.state, size: 13) + VibeXCircularProgressRing( + progress: context.state.progress, + phase: context.state.phase, + size: 21, + lineWidth: 2.4, + showLabel: true + ) } minimal: { - TaskRing(state: context.state, size: 18) + ZStack { + VibeXCircularProgressRing( + progress: context.state.progress, + phase: context.state.phase, + size: 22, + lineWidth: 2.2, + showLabel: false + ) + VibeXWidgetLogoView(phase: context.state.phase, size: 13, showBadge: false) + } } } } } -private let staleNote = "已暂停同步,打开 App 查看最新进度" +private let staleNote = "后台守护中 · 点按进入 VibeX 查看最新进展" + +private func shortCompactLabel(for state: TaskActivityAttributes.ContentState) -> String { + switch state.phase { + case .thinking: return "思考中" + case .exploring: return "查阅中" + case .developing: return "开发中" + case .verifying: return "验证中" + case .summarizing: return "总结中" + case .waitingInput: return "待确认" + case .completed: return "已完成" + case .failed: return "异常" + } +} + +private func phaseTint(_ phase: VibeXActivityPhase) -> Color { + switch phase { + case .thinking: + return Color(red: 0.64, green: 0.52, blue: 1.0) + case .exploring: + return Color(red: 0.35, green: 0.72, blue: 0.98) + case .developing: + return Color(red: 0.28, green: 0.62, blue: 1.0) + case .verifying: + return Color(red: 0.22, green: 0.82, blue: 0.72) + case .summarizing: + return Color(red: 0.45, green: 0.78, blue: 0.98) + case .waitingInput: + return Color(red: 0.98, green: 0.62, blue: 0.16) + case .completed: + return Color(red: 0.30, green: 0.82, blue: 0.44) + case .failed: + return Color(red: 0.96, green: 0.28, blue: 0.28) + } +} + +private func phaseSymbol(_ phase: VibeXActivityPhase) -> String { + switch phase { + case .thinking: return "sparkles" + case .exploring: return "magnifyingglass" + case .developing: return "hammer.fill" + case .verifying: return "checkmark.shield.fill" + case .summarizing: return "text.Justify.left" + case .waitingInput: return "bell.badge.fill" + case .completed: return "checkmark.circle.fill" + case .failed: return "exclamationmark.triangle.fill" + } +} + +// MARK: - Lock Screen Live Activity Banner private struct LockScreenTaskView: View { - let title: String + let projectName: String + let conversationTitle: String let state: TaskActivityAttributes.ContentState let stale: Bool var body: some View { - VStack(alignment: .leading, spacing: 10) { - HStack(spacing: 10) { - TaskRing(state: state, size: 24) - Text(title).font(.system(size: 14, weight: .semibold)).lineLimit(1) - Spacer() - ProgressLabel(state: state, size: 14).foregroundStyle(.secondary) + HStack(alignment: .center, spacing: 13) { + VibeXWidgetLogoView(phase: state.phase, size: 42) + + VStack(alignment: .leading, spacing: 5) { + HStack(spacing: 6) { + Text(projectName) + .font(.system(size: 14, weight: .bold)) + .foregroundStyle(.white) + .lineLimit(1) + + PhaseBadgePill(phase: state.phase, title: state.stageTitle) + + Spacer(minLength: 4) + + if state.isRunning { + Text(state.startedAt, style: .timer) + .font(.system(size: 12, weight: .semibold, design: .monospaced)) + .monospacedDigit() + .foregroundStyle(.white.opacity(0.65)) + } + } + + Text(stale && state.isRunning ? staleNote : state.stageSubtitle) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(.white.opacity(0.88)) + .lineLimit(1) + + HStack(spacing: 8) { + Text(conversationTitle) + .font(.system(size: 11)) + .foregroundStyle(.white.opacity(0.55)) + .lineLimit(1) + + if state.total > 0 { + Text("· 计划 \(state.completed)/\(state.total)") + .font(.system(size: 11, weight: .medium)) + .monospacedDigit() + .foregroundStyle(.white.opacity(0.65)) + } else if state.stepCount > 0 { + Text("· 已推进 \(state.stepCount) 步") + .font(.system(size: 11, weight: .medium)) + .monospacedDigit() + .foregroundStyle(.white.opacity(0.65)) + } + } } - Text(stale && state.isRunning ? staleNote : state.currentTask) - .font(.system(size: 13)) - .foregroundStyle(.secondary) - .lineLimit(2) - if state.total > 0 { TaskProgressBar(state: state) } + + VibeXCircularProgressRing( + progress: state.progress, + phase: state.phase, + size: 44, + lineWidth: 3.8, + showLabel: true + ) } } } -/// `completed/total` for a task list, otherwise the elapsed time of the run. -private struct ProgressLabel: View { - let state: TaskActivityAttributes.ContentState - let size: CGFloat +// MARK: - Phase Badge Pill + +private struct PhaseBadgePill: View { + let phase: VibeXActivityPhase + let title: String var body: some View { - Group { - if state.total > 0 { - Text("\(state.completed)/\(state.total)") - } else if state.isRunning { - Text(state.startedAt, style: .timer).frame(maxWidth: 52, alignment: .trailing) - } else { - Text("完成") - } + let tint = phaseTint(phase) + HStack(spacing: 3.5) { + Circle() + .fill(tint) + .frame(width: 5.5, height: 5.5) + Text(title) + .font(.system(size: 10.5, weight: .semibold)) + .foregroundStyle(tint) + .lineLimit(1) } - .font(.system(size: size, weight: .semibold)) - .monospacedDigit() + .padding(.horizontal, 7) + .padding(.vertical, 2.5) + .background( + Capsule(style: .continuous) + .fill(tint.opacity(0.16)) + ) + .overlay( + Capsule(style: .continuous) + .strokeBorder(tint.opacity(0.32), lineWidth: 0.6) + ) } } -private struct TaskRing: View { - let state: TaskActivityAttributes.ContentState +// MARK: - Circular Progress Ring (`圆形进度条`) + +private struct VibeXCircularProgressRing: View { + let progress: Double + let phase: VibeXActivityPhase let size: CGFloat + let lineWidth: CGFloat + var showLabel: Bool = true - private var fraction: Double { - state.total == 0 ? 0 : Double(state.completed) / Double(state.total) + private var clampedProgress: Double { + if phase == .completed { return 1.0 } + return min(max(progress, 0.08), 0.99) } - var body: some View { - if state.total == 0 && state.isRunning { - ProgressView().frame(width: size, height: size) - } else { - ring - } + private var percentageInt: Int { + if phase == .completed { return 100 } + return Int((clampedProgress * 100).rounded()) } - private var ring: some View { + var body: some View { + let tint = phaseTint(phase) ZStack { - Circle().stroke(Color.primary.opacity(0.18), lineWidth: 2.5) Circle() - .trim(from: 0, to: max(0.04, fraction)) - .stroke(finished ? Color.green : Color.primary, style: StrokeStyle(lineWidth: 2.5, lineCap: .round)) + .stroke(Color.white.opacity(0.14), lineWidth: lineWidth) + + Circle() + .trim(from: 0, to: clampedProgress) + .stroke( + AngularGradient( + colors: [tint.opacity(0.75), tint], + center: .center, + startAngle: .degrees(-90), + endAngle: .degrees(270) + ), + style: StrokeStyle(lineWidth: lineWidth, lineCap: .round) + ) .rotationEffect(.degrees(-90)) - if finished { - Image(systemName: "checkmark").font(.system(size: size * 0.4, weight: .bold)).foregroundStyle(.green) + + if showLabel { + if phase == .completed { + Image(systemName: "checkmark") + .font(.system(size: size * 0.34, weight: .bold)) + .foregroundStyle(tint) + } else if phase == .waitingInput { + Image(systemName: "exclamationmark") + .font(.system(size: size * 0.36, weight: .heavy)) + .foregroundStyle(tint) + } else if phase == .failed { + Image(systemName: "xmark") + .font(.system(size: size * 0.34, weight: .bold)) + .foregroundStyle(tint) + } else { + Text("\(percentageInt)%") + .font(.system(size: max(8.5, size * 0.25), weight: .bold, design: .rounded)) + .monospacedDigit() + .foregroundStyle(.white) + } } } .frame(width: size, height: size) } +} - private var finished: Bool { !state.isRunning && state.completed >= state.total } +// MARK: - Vector VibeX Brand Logo for Widget & Dynamic Island + +private struct VibeXWidgetLogoView: View { + let phase: VibeXActivityPhase + let size: CGFloat + var showBadge: Bool = true + + var body: some View { + ZStack(alignment: .bottomTrailing) { + Canvas { context, canvasSize in + let w = canvasSize.width + let h = canvasSize.height + let corner = w * 0.24 + let rect = CGRect(x: 0, y: 0, width: w, height: h) + let bgPath = Path(roundedRect: rect, cornerRadius: corner, style: .continuous) + context.fill(bgPath, with: .color(Color(red: 0.11, green: 0.11, blue: 0.13))) + context.stroke( + bgPath, + with: .color(Color.white.opacity(0.16)), + lineWidth: max(0.6, w * 0.03) + ) + + let p1 = CGPoint(x: w * 0.27, y: h * 0.27) + let p2 = CGPoint(x: w * 0.73, y: h * 0.73) + let p3 = CGPoint(x: w * 0.73, y: h * 0.27) + let p4 = CGPoint(x: w * 0.27, y: h * 0.73) + let center = CGPoint(x: w * 0.5, y: h * 0.5) + + var diag1 = Path() + diag1.move(to: p1) + diag1.addLine(to: p2) + + var diag2 = Path() + diag2.move(to: p3) + diag2.addLine(to: p4) + + let strokeW = max(1.4, w * 0.085) + context.stroke( + diag1, + with: .color(.white), + style: StrokeStyle(lineWidth: strokeW, lineCap: .round) + ) + context.stroke( + diag2, + with: .color(.white), + style: StrokeStyle(lineWidth: strokeW, lineCap: .round) + ) + + let nodeR = max(1.6, w * 0.085) + for pt in [p1, p2, p3, p4] { + let nodeRect = CGRect( + x: pt.x - nodeR, + y: pt.y - nodeR, + width: nodeR * 2, + height: nodeR * 2 + ) + context.fill(Path(ellipseIn: nodeRect), with: .color(.white)) + } + + let centerOuterR = max(2.2, w * 0.13) + let centerInnerR = max(1.0, w * 0.055) + context.fill( + Path(ellipseIn: CGRect( + x: center.x - centerOuterR, + y: center.y - centerOuterR, + width: centerOuterR * 2, + height: centerOuterR * 2 + )), + with: .color(.white) + ) + context.fill( + Path(ellipseIn: CGRect( + x: center.x - centerInnerR, + y: center.y - centerInnerR, + width: centerInnerR * 2, + height: centerInnerR * 2 + )), + with: .color(Color(red: 0.11, green: 0.11, blue: 0.13)) + ) + } + .frame(width: size, height: size) + + if showBadge { + let badgeSize = max(7, size * 0.28) + Circle() + .fill(phaseTint(phase)) + .frame(width: badgeSize, height: badgeSize) + .overlay( + Circle() + .stroke(Color.black, lineWidth: max(1, size * 0.045)) + ) + .offset(x: 1.5, y: 1.5) + } + } + } } -private struct TaskProgressBar: View { - let state: TaskActivityAttributes.ContentState +private struct TaskSmoothProgressBar: View { + let progress: Double + let tint: Color var body: some View { GeometryReader { proxy in + let clamped = min(max(progress, 0.06), 1.0) ZStack(alignment: .leading) { - Capsule().fill(Color.primary.opacity(0.15)) Capsule() - .fill(Color.primary) - .frame(width: proxy.size.width * (state.total == 0 ? 0 : Double(state.completed) / Double(state.total))) + .fill(Color.white.opacity(0.14)) + Capsule() + .fill( + LinearGradient( + colors: [tint.opacity(0.8), tint], + startPoint: .leading, + endPoint: .trailing + ) + ) + .frame(width: proxy.size.width * clamped) } } - .frame(height: 4) + .frame(height: 4.5) } } diff --git a/mobile/ios/VibeXCompanion.xcodeproj/project.pbxproj b/mobile/ios/VibeXCompanion.xcodeproj/project.pbxproj index 2ddbe67a6..76d41947d 100644 --- a/mobile/ios/VibeXCompanion.xcodeproj/project.pbxproj +++ b/mobile/ios/VibeXCompanion.xcodeproj/project.pbxproj @@ -269,7 +269,7 @@ INFOPLIST_KEY_UILaunchScreen_Generation = YES; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortraitUpsideDown"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; - MARKETING_VERSION = 0.1.0; + MARKETING_VERSION = 0.4.2; PRODUCT_BUNDLE_IDENTIFIER = dev.vibex.companion.ios; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; @@ -293,7 +293,7 @@ INFOPLIST_KEY_UILaunchScreen_Generation = YES; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortraitUpsideDown"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; - MARKETING_VERSION = 0.1.0; + MARKETING_VERSION = 0.4.2; PRODUCT_BUNDLE_IDENTIFIER = dev.vibex.companion.ios; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; @@ -317,7 +317,7 @@ "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MARKETING_VERSION = 0.1.0; + MARKETING_VERSION = 0.4.2; PRODUCT_BUNDLE_IDENTIFIER = dev.vibex.companion.ios.TaskWidget; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; @@ -342,7 +342,7 @@ "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MARKETING_VERSION = 0.1.0; + MARKETING_VERSION = 0.4.2; PRODUCT_BUNDLE_IDENTIFIER = dev.vibex.companion.ios.TaskWidget; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES;