diff --git a/App/AgentIcons.xcassets/AppIcon.appiconset/AppIcon-1024.png b/App/AgentIcons.xcassets/AppIcon.appiconset/AppIcon-1024.png index 12e2cbe..dbb3681 100644 Binary files a/App/AgentIcons.xcassets/AppIcon.appiconset/AppIcon-1024.png and b/App/AgentIcons.xcassets/AppIcon.appiconset/AppIcon-1024.png differ diff --git a/App/AgentIcons.xcassets/dimo_logo.imageset/Contents.json b/App/AgentIcons.xcassets/dimo_logo.imageset/Contents.json new file mode 100644 index 0000000..9e36ef2 --- /dev/null +++ b/App/AgentIcons.xcassets/dimo_logo.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "filename" : "dimo-logo.png", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/App/AgentIcons.xcassets/dimo_logo.imageset/dimo-logo.png b/App/AgentIcons.xcassets/dimo_logo.imageset/dimo-logo.png new file mode 100644 index 0000000..dbb3681 Binary files /dev/null and b/App/AgentIcons.xcassets/dimo_logo.imageset/dimo-logo.png differ diff --git a/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-dark.png b/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-dark.png index 79a395e..2cb242d 100644 Binary files a/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-dark.png and b/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-dark.png differ diff --git a/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-light-default.png b/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-light-default.png index 2656801..2cb242d 100644 Binary files a/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-light-default.png and b/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-light-default.png differ diff --git a/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-dark-lite.png b/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-dark-lite.png index 8438059..2cb242d 100644 Binary files a/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-dark-lite.png and b/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-dark-lite.png differ diff --git a/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-light-lite.png b/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-light-lite.png index deeb244..2cb242d 100644 Binary files a/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-light-lite.png and b/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-light-lite.png differ diff --git a/App/AppAppearanceStore.swift b/App/AppAppearanceStore.swift index 0c762f2..1cdd741 100644 --- a/App/AppAppearanceStore.swift +++ b/App/AppAppearanceStore.swift @@ -5,6 +5,27 @@ import SwiftUI import UIKit import UserNotifications +enum AppLanguageMode: String, CaseIterable, Identifiable { + case zhHans = "zh-Hans" + case en = "en" + + var id: String { rawValue } + + var title: String { + switch self { + case .zhHans: return "简体中文" + case .en: return "English" + } + } + + var locale: Locale { + switch self { + case .zhHans: return Locale(identifier: "zh_Hans") + case .en: return Locale(identifier: "en") + } + } +} + enum AppThemeMode: String, CaseIterable, Identifiable { case system case light @@ -14,12 +35,21 @@ enum AppThemeMode: String, CaseIterable, Identifiable { var title: String { switch self { - case .system: return "跟随系统" + case .system: return "自动" case .light: return "浅色" case .dark: return "深色" } } + func localizedTitle(english: Bool) -> String { + guard english else { return title } + switch self { + case .system: return "Auto" + case .light: return "Light" + case .dark: return "Dark" + } + } + var subtitle: String { switch self { case .system: return "自动跟随系统外观" @@ -72,6 +102,17 @@ enum AppFontSizePreset: String, CaseIterable, Identifiable { } } + func localizedTitle(english: Bool) -> String { + guard english else { return title } + switch self { + case .small: return "Small" + case .standard: return "Standard" + case .mediumLarge: return "Medium" + case .large: return "Large" + case .extraLarge: return "XL" + } + } + var scaleLabel: String { switch self { case .small: return "90%" @@ -129,6 +170,16 @@ enum AppFontStylePreset: String, CaseIterable, Identifiable { } } + func localizedShortTitle(english: Bool) -> String { + guard english else { return shortTitle } + switch self { + case .system: return "System" + case .rounded: return "Rounded" + case .serif: return "Serif" + case .monospaced: return "Mono" + } + } + var subtitle: String { switch self { case .system: return "清晰均衡的 Apple 原生无衬线字体" @@ -182,8 +233,22 @@ final class AppAppearanceStore { var fontStylePreset: AppFontStylePreset { didSet { defaults.set(fontStylePreset.rawValue, forKey: "vibex.appearance.fontStyle") } } + var languageMode: AppLanguageMode { + didSet { + defaults.set(languageMode.rawValue, forKey: "vibex.appearance.language") + defaults.set([languageMode.rawValue], forKey: "AppleLanguages") + } + } + + // 3b. Security & Guardrails + var confirmHighRiskApproval: Bool { + didSet { defaults.set(confirmHighRiskApproval, forKey: "vibex.security.confirmHighRiskApproval") } + } // 4. Notifications + var muteForegroundNotifications: Bool { + didSet { defaults.set(muteForegroundNotifications, forKey: "vibex.notify.muteForeground") } + } var notifyTurnCompleted: Bool { didSet { defaults.set(notifyTurnCompleted, forKey: "vibex.notify.turnCompleted") } } @@ -200,6 +265,7 @@ final class AppAppearanceStore { didSet { defaults.set(hapticFeedback, forKey: "vibex.notify.haptic") } } var systemNotificationStatusText: String = "已启用" + var notificationAuthorizationStatus: UNAuthorizationStatus = .notDetermined private weak var activeOverlayView: UIView? @@ -222,6 +288,12 @@ final class AppAppearanceStore { let rawStyle = defaults.string(forKey: "vibex.appearance.fontStyle") ?? AppFontStylePreset.system.rawValue self.fontStylePreset = AppFontStylePreset(rawValue: rawStyle) ?? .system + let rawLang = defaults.string(forKey: "vibex.appearance.language") ?? AppLanguageMode.zhHans.rawValue + self.languageMode = AppLanguageMode(rawValue: rawLang) ?? .zhHans + + self.confirmHighRiskApproval = defaults.object(forKey: "vibex.security.confirmHighRiskApproval") as? Bool ?? true + self.muteForegroundNotifications = defaults.object(forKey: "vibex.notify.muteForeground") as? Bool ?? false + self.notifyTurnCompleted = defaults.object(forKey: "vibex.notify.turnCompleted") as? Bool ?? true self.notifyApprovalRequired = defaults.object(forKey: "vibex.notify.approvalRequired") as? Bool ?? true self.notifyCollabMessages = defaults.object(forKey: "vibex.notify.collabMessages") as? Bool ?? true @@ -234,6 +306,28 @@ final class AppAppearanceStore { } } + var effectiveLocale: Locale { + languageMode.locale + } + + var systemNotificationStatusTextLocalized: String { + let isEn = languageMode == .en + switch notificationAuthorizationStatus { + case .authorized, .provisional, .ephemeral: + return isEn ? "Enabled" : "系统通知已开启" + case .denied: + return isEn ? "Disabled" : "系统通知已关闭" + case .notDetermined: + return isEn ? "Not Set" : "待授权" + @unknown default: + return isEn ? "Unknown" : "未知" + } + } + + func l(_ zh: String, _ en: String) -> String { + languageMode == .en ? en : zh + } + var avatarConfig: CollabBotAvatarConfig { get { CollabBotAvatarConfig.resolve( @@ -368,6 +462,7 @@ final class AppAppearanceStore { func refreshNotificationAuthorizationStatus() async { let settings = await UNUserNotificationCenter.current().notificationSettings() + notificationAuthorizationStatus = settings.authorizationStatus switch settings.authorizationStatus { case .authorized, .provisional, .ephemeral: systemNotificationStatusText = "系统通知已开启" diff --git a/App/AppSidebar.swift b/App/AppSidebar.swift new file mode 100644 index 0000000..cbbfa90 --- /dev/null +++ b/App/AppSidebar.swift @@ -0,0 +1,261 @@ +import Observation +import SwiftUI +import UIKit + +/// Coordinates Level-1 tab selection, Level-2+ stack depth visibility for the bottom floating capsule, +/// global project filter synchronization, and the centered `+` New Thread trigger. +@MainActor +@Observable +final class WorkspaceNavigationStore { + static let bottomDockClearance: CGFloat = 78 + + var selection: AppTab = .conversations + var selectedProjectID: String? + var conversationsDepth: Int = 0 + var boardDepth: Int = 0 + var spaceDepth: Int = 0 + var settingsDepth: Int = 0 + var collabUnreadCount: Int = 0 + var newThreadTrigger: Int = 0 + + var isCurrentTabAtRoot: Bool { + switch selection { + case .conversations: + return conversationsDepth == 0 + case .board: + return boardDepth == 0 + case .space: + return spaceDepth == 0 + case .settings: + return settingsDepth == 0 + } + } + + func triggerNewThread() { + selection = .conversations + newThreadTrigger &+= 1 + } +} + +// MARK: - Bottom Floating Symmetrical Capsule Dock (Level-1 Only) + +/// Level-1 floating capsule navigation dock: +/// - On `.conversations`: `[ 会话 ] [ 看板 ] [ (+) ] [ 协作 ] [ 设置 ]` +/// - On `.board / .space / .settings`: `[ (+ ) ]` animates to zero width & zero gap so the 4 tabs +/// smoothly expand to 4 equal widths without leaving any blank space in the middle. +struct FloatingWorkspaceCapsuleDock: View { + @Environment(AppAppearanceStore.self) private var appearance + @Bindable var navStore: WorkspaceNavigationStore + var attentionCount: Int = 0 + @Namespace private var tabHighlightNamespace + + private var showComposeButton: Bool { + navStore.selection == .conversations + } + + var body: some View { + HStack(spacing: 0) { + capsuleTabButton(.conversations, badgeCount: attentionCount) + capsuleTabButton(.board) + + ZStack { + if showComposeButton { + Button { + UIImpactFeedbackGenerator(style: .medium).impactOccurred() + navStore.triggerNewThread() + } label: { + Image(systemName: "plus") + .font(.system(size: 18, weight: .bold)) + .foregroundStyle(Color(.systemBackground)) + .frame(width: 42, height: 42) + .background( + Circle() + .fill(Color.primary) + .shadow(color: .black.opacity(0.18), radius: 6, x: 0, y: 2) + ) + } + .buttonStyle(DockScaleButtonStyle()) + .accessibilityLabel("新建会话") + .transition(.scale(scale: 0.35).combined(with: .opacity)) + } + } + .frame(width: showComposeButton ? 54 : 0, height: 48) + .clipped() + + capsuleTabButton(.space, badgeCount: navStore.collabUnreadCount) + capsuleTabButton(.settings) + } + .padding(.horizontal, 6) + .padding(.vertical, 5) + .background { + Capsule(style: .continuous) + .fill(.ultraThinMaterial) + .overlay( + Capsule(style: .continuous) + .strokeBorder(Color.primary.opacity(0.09), lineWidth: 0.75) + ) + .shadow(color: .black.opacity(0.14), radius: 18, x: 0, y: 8) + } + .padding(.horizontal, 18) + .padding(.bottom, 6) + .animation(.spring(response: 0.30, dampingFraction: 0.85), value: showComposeButton) + .animation(.spring(response: 0.26, dampingFraction: 0.86), value: navStore.selection) + } + + private func capsuleTabButton(_ tab: AppTab, badgeCount: Int = 0) -> some View { + let isSelected = navStore.selection == tab + return Button { + if !isSelected { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + } + withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { + navStore.selection = tab + } + } label: { + VStack(spacing: 2.5) { + ZStack(alignment: .topTrailing) { + Image(systemName: isSelected ? tab.selectedIcon : tab.icon) + .font(.system(size: 16.5, weight: isSelected ? .semibold : .medium)) + .frame(width: 24, height: 20) + + if badgeCount > 0 { + Text(badgeCount > 99 ? "99+" : "\(badgeCount)") + .font(.system(size: 9.5, weight: .bold)) + .monospacedDigit() + .foregroundStyle(.white) + .padding(.horizontal, 4.5) + .frame(minWidth: 15, minHeight: 15) + .background(Capsule().fill(Color.accentColor)) + .offset(x: 9, y: -5) + } + } + + Text(tab.localizedTitle(english: appearance.languageMode == .en)) + .font(.system(size: 10.5, weight: isSelected ? .semibold : .medium)) + .lineLimit(1) + } + .foregroundStyle(isSelected ? Color.primary : Color.secondary) + .frame(maxWidth: .infinity) + .frame(height: 48) + .background { + if isSelected { + Capsule(style: .continuous) + .fill(Color.primary.opacity(0.10)) + .matchedGeometryEffect(id: "activeCapsuleTab", in: tabHighlightNamespace) + } + } + .contentShape(Capsule(style: .continuous)) + } + .buttonStyle(.plain) + .accessibilityAddTraits(isSelected ? .isSelected : []) + } +} + +// MARK: - Shared Level-2 Floating Header Chrome + +/// Circular `<` back button used by Level-2 workspace screens (`新建会话` and `会话详情`). +struct FloatingCircleBackButton: View { + let action: () -> Void + + var body: some View { + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + dismissKeyboard() + action() + } label: { + Image(systemName: "chevron.left") + .font(.system(size: 16, weight: .semibold)) + .foregroundStyle(.primary) + .frame(width: 40, height: 40) + .background( + Circle() + .fill(Color(.secondarySystemGroupedBackground)) + .shadow(color: .black.opacity(0.06), radius: 8, x: 0, y: 2) + ) + .overlay( + Circle() + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.65) + ) + } + .buttonStyle(DockScaleButtonStyle()) + .accessibilityLabel("返回") + } +} + +/// Top-right unified dual-icon capsule `[ ⑂ 代码变更 | 📁 项目文件 ]` used on Level-2 workspace screens. +struct WorkspaceDualToolsCapsule: View { + var changeCount: Int = 0 + var isDisabled: Bool = false + let onOpenChanges: () -> Void + let onOpenFiles: () -> Void + + var body: some View { + HStack(spacing: 0) { + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + dismissKeyboard() + onOpenChanges() + } label: { + ZStack(alignment: .topTrailing) { + Image(systemName: "point.topleft.down.curvedto.point.bottomright.up") + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.primary) + .frame(width: 42, height: 40) + .contentShape(Rectangle()) + + if changeCount > 0 { + Text(changeCount > 99 ? "99" : "\(changeCount)") + .font(.system(size: 9, weight: .bold)) + .monospacedDigit() + .foregroundStyle(.white) + .padding(.horizontal, 4) + .frame(minWidth: 14, minHeight: 14) + .background(Capsule().fill(Color.orange)) + .offset(x: -4, y: 5) + } + } + } + .buttonStyle(.plain) + .disabled(isDisabled) + .accessibilityLabel(changeCount > 0 ? "代码差异(\(changeCount) 处改动)" : "代码差异") + + Rectangle() + .fill(Color.primary.opacity(0.09)) + .frame(width: 0.65, height: 18) + + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + dismissKeyboard() + onOpenFiles() + } label: { + Image(systemName: "folder") + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.primary) + .frame(width: 42, height: 40) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(isDisabled) + .accessibilityLabel("浏览项目文件") + } + .padding(.horizontal, 2) + .background( + Capsule(style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + .shadow(color: .black.opacity(0.06), radius: 8, x: 0, y: 2) + ) + .overlay( + Capsule(style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.65) + ) + .opacity(isDisabled ? 0.45 : 1) + } +} + +private struct DockScaleButtonStyle: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .scaleEffect(configuration.isPressed ? 0.92 : 1) + .animation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.15), value: configuration.isPressed) + } +} diff --git a/App/AppUpdateStore.swift b/App/AppUpdateStore.swift new file mode 100644 index 0000000..7da6899 --- /dev/null +++ b/App/AppUpdateStore.swift @@ -0,0 +1,311 @@ +import Foundation +import Observation +import SwiftUI +#if canImport(UIKit) +import UIKit +#endif +#if canImport(UserNotifications) +import UserNotifications +#endif + +struct MobileReleaseNotice: Codable, Equatable, Sendable { + var id: String + var platform: String + var version: String + var buildNumber: Int + var changelog: String + var forceUpdate: Bool + var publishedAt: String + var testFlightUrl: String? + + var releaseKey: String { + "\(version)_\(buildNumber)" + } +} + +private struct MobileReleaseCheckResponse: Codable, Sendable { + var release: MobileReleaseNotice? + var hasUpdate: Bool +} + +@Observable +@MainActor +final class AppUpdateStore { + var checking = false + var hasUpdate = false + var latestRelease: MobileReleaseNotice? + var isSheetPresented = false + var manualStatusMessage: String? + + private let defaults: UserDefaults + private var lastAutoCheckAt: Date? + + private static let dismissedReleaseKey = "vibex.ios.update.dismissed_key" + private static let notifiedReleaseKey = "vibex.ios.update.notified_key" + private static let autoCheckInterval: TimeInterval = 10 * 60 + private static let appStoreTestFlightFallback = "https://apps.apple.com/app/testflight/id899247664" + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + } + + var currentVersion: String { + (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String)? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "0.4.7" + } + + var currentBuild: Int { + let raw = (Bundle.main.infoDictionary?["CFBundleVersion"] as? String)? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "6" + return Int(raw) ?? 6 + } + + func checkIfDue() { + if let last = lastAutoCheckAt, Date().timeIntervalSince(last) < Self.autoCheckInterval { + return + } + lastAutoCheckAt = Date() + Task { + await checkForUpdate(manual: false) + } + } + + func checkForUpdate(manual: Bool) async { + guard !checking else { return } + checking = true + if manual { + manualStatusMessage = nil + } + defer { checking = false } + + guard var components = URLComponents(string: "\(VibeXAccountStore.siteBaseURL)/api/mobile/releases/latest") else { + return + } + components.queryItems = [ + URLQueryItem(name: "platform", value: "ios"), + URLQueryItem(name: "version", value: currentVersion), + URLQueryItem(name: "build", value: String(currentBuild)), + ] + guard let url = components.url else { return } + + var request = URLRequest(url: url) + request.cachePolicy = .reloadIgnoringLocalCacheData + request.timeoutInterval = 12 + request.setValue("application/json", forHTTPHeaderField: "Accept") + + do { + let (data, response) = try await URLSession.shared.data(for: request) + guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else { + if manual { + manualStatusMessage = "检查更新失败,请稍后重试" + } + return + } + let decoded = try JSONDecoder().decode(MobileReleaseCheckResponse.self, from: data) + if let release = decoded.release, decoded.hasUpdate, isLocalOutdated(against: release) { + latestRelease = release + hasUpdate = true + let dismissed = defaults.string(forKey: Self.dismissedReleaseKey) ?? "" + if manual || release.forceUpdate || dismissed != release.releaseKey { + isSheetPresented = true + } + await postSystemNotificationIfNeeded(for: release) + } else { + latestRelease = decoded.release + hasUpdate = false + isSheetPresented = false + if manual { + manualStatusMessage = "当前已是最新版本 v\(currentVersion)" + } + } + } catch { + if manual { + manualStatusMessage = "网络连接异常,暂时无法检查更新" + } + } + } + + func dismissSheet() { + guard let release = latestRelease else { + isSheetPresented = false + return + } + guard !release.forceUpdate else { return } + defaults.set(release.releaseKey, forKey: Self.dismissedReleaseKey) + isSheetPresented = false + } + + func openTestFlight() { + #if canImport(UIKit) + let configured = latestRelease?.testFlightUrl?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !configured.isEmpty, configured.lowercased().hasPrefix("https://"), let url = URL(string: configured) { + UIApplication.shared.open(url) + return + } + if let betaURL = URL(string: "itms-beta://") { + UIApplication.shared.open(betaURL, options: [:]) { success in + if !success, let fallback = URL(string: Self.appStoreTestFlightFallback) { + UIApplication.shared.open(fallback) + } + } + } + #endif + } + + private func isLocalOutdated(against release: MobileReleaseNotice) -> Bool { + if release.buildNumber != currentBuild { + return release.buildNumber > currentBuild + } + return Self.compareSemver(release.version, currentVersion) > 0 + } + + private static func compareSemver(_ a: String, _ b: String) -> Int { + let cleanA = a.trimmingCharacters(in: .whitespacesAndNewlines) + .replacingOccurrences(of: "^v", with: "", options: .regularExpression) + .split(separator: "-").first.map(String.init) ?? "" + let cleanB = b.trimmingCharacters(in: .whitespacesAndNewlines) + .replacingOccurrences(of: "^v", with: "", options: .regularExpression) + .split(separator: "-").first.map(String.init) ?? "" + let pa = cleanA.split(separator: ".").map { Int($0) ?? 0 } + let pb = cleanB.split(separator: ".").map { Int($0) ?? 0 } + let count = max(pa.count, pb.count, 3) + for idx in 0.. db ? 1 : -1 } + } + return 0 + } + + private func postSystemNotificationIfNeeded(for release: MobileReleaseNotice) async { + #if canImport(UserNotifications) + let already = defaults.string(forKey: Self.notifiedReleaseKey) ?? "" + guard already != release.releaseKey else { return } + + let center = UNUserNotificationCenter.current() + let settings = await center.notificationSettings() + if settings.authorizationStatus == .notDetermined { + _ = try? await center.requestAuthorization(options: [.alert, .sound, .badge]) + } + let refreshed = await center.notificationSettings() + guard refreshed.authorizationStatus == .authorized || refreshed.authorizationStatus == .provisional else { + return + } + + defaults.set(release.releaseKey, forKey: Self.notifiedReleaseKey) + + let content = UNMutableNotificationContent() + content.title = "发现 VibeX 新版本 v\(release.version)" + let lines = release.changelog + .split(whereSeparator: \.isNewline) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + content.body = lines.prefix(2).joined(separator: ";").isEmpty + ? "前往 TestFlight 即可更新体验最新功能" + : lines.prefix(2).joined(separator: "\n") + content.sound = .default + + let req = UNNotificationRequest( + identifier: "vibex.ios.release.\(release.releaseKey)", + content: content, + trigger: nil + ) + try? await center.add(req) + #endif + } +} + +struct AppUpdateSheet: View { + @Environment(AppUpdateStore.self) private var updates + let release: MobileReleaseNotice + + var body: some View { + NavigationStack { + VStack(alignment: .leading, spacing: 18) { + HStack(spacing: 14) { + ZStack { + Circle() + .fill(Color.accentColor.opacity(0.14)) + .frame(width: 48, height: 48) + Image(systemName: "arrow.down.app.fill") + .font(.system(size: 22, weight: .semibold)) + .foregroundStyle(Color.accentColor) + } + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 8) { + Text("发现新版本") + .font(.headline.weight(.bold)) + Text("v\(release.version)") + .font(.caption.monospacedDigit().weight(.semibold)) + .padding(.horizontal, 8) + .padding(.vertical, 2.5) + .background(Capsule().fill(Color.accentColor.opacity(0.14))) + .foregroundStyle(Color.accentColor) + } + Text("当前版本 v\(updates.currentVersion) (#\(updates.currentBuild)) → Build #\(release.buildNumber)") + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + Spacer() + } + + VStack(alignment: .leading, spacing: 8) { + Text("更新日志") + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + ScrollView { + Text(release.changelog.isEmpty ? "• 性能优化与细节体验改进" : release.changelog) + .font(.subheadline) + .foregroundStyle(.primary) + .frame(maxWidth: .infinity, alignment: .leading) + .lineSpacing(4) + } + .frame(minHeight: 100, maxHeight: 240) + .padding(14) + .background( + RoundedRectangle(cornerRadius: 14, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + } + + VStack(spacing: 10) { + Button { + updates.openTestFlight() + } label: { + HStack(spacing: 6) { + Image(systemName: "paperplane.fill") + Text("前往 TestFlight 更新") + .fontWeight(.semibold) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 13) + .background( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(Color.accentColor) + ) + .foregroundStyle(.white) + } + .buttonStyle(.plain) + + if !release.forceUpdate { + Button { + updates.dismissSheet() + } label: { + Text("稍后提醒") + .font(.subheadline.weight(.medium)) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity) + .padding(.vertical, 10) + } + .buttonStyle(.plain) + } + } + } + .padding(20) + .background(Color(.systemGroupedBackground)) + .presentationDetents([.medium, .large]) + .presentationDragIndicator(release.forceUpdate ? .hidden : .visible) + .interactiveDismissDisabled(release.forceUpdate) + } + } +} diff --git a/App/BoardView.swift b/App/BoardView.swift index edae49c..6c1ef45 100644 --- a/App/BoardView.swift +++ b/App/BoardView.swift @@ -1,585 +1,134 @@ import CompanionCore import SwiftUI -#if canImport(UIKit) -import UIKit -#endif - -private struct CardChip: ViewModifier { - let tint: Color - - func body(content: Content) -> some View { - content - .font(.caption2.weight(.semibold)) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(tint.opacity(0.14), in: Capsule()) - .foregroundStyle(tint) - } -} +/// Root of the "看板" tab: +/// Directly presents the distilled Usage & Subscription Quota Dashboard at Level 1 +/// (no duplicate 4-column session board, keeping the bottom floating capsule dock visible). struct BoardView: View { let client: HostClient - var onChromeHiddenChange: ((Bool) -> Void)? = nil - @State private var viewMode: KanbanViewMode = .columns + @Environment(WorkspaceNavigationStore.self) private var navStore + @Environment(AppAppearanceStore.self) private var appearance @State private var projects: [ProjectSummary] = [] - @State private var selectedProjectID: String? // nil = 全部项目 - @State private var sessions: [KanbanSessionSummary] = [] - @State private var workspaces: [KanbanWorkspaceRecord] = [] - @State private var isLoading = true - @State private var errorMessage: String? - @State private var noticeMessage: String? + @State private var selectedTarget: String = "global" + @State private var didApplyInitialScope = false @State private var usageRefreshTrigger = 0 - // Two-stage vertical pull gesture state (Half-pull = Refresh, Full-pull = Usage Dashboard) - @State private var pullOffset: CGFloat = 0 - @State private var didTriggerFullPullHaptic = false - @State private var isPullRefreshing = false + private var selectedProject: ProjectSummary? { + guard selectedTarget.hasPrefix("project:") else { return nil } + let id = String(selectedTarget.dropFirst("project:".count)) + return projects.first { $0.id.lowercased() == id.lowercased() } + } - // Sheets & Alerts - @State private var path = NavigationPath() - @State private var createSheetInitialStatus: KanbanSessionStatus? - @State private var showCreateSheet = false - @State private var renamingSession: KanbanSessionSummary? - @State private var renameDraft = "" - @State private var deletingSession: KanbanSessionSummary? + private var scopeLabel: String { + if selectedTarget == "global" { + return appearance.l("全局", "Global") + } + return selectedProject?.displayName ?? appearance.l("当前项目", "Project") + } - private let refreshThreshold: CGFloat = 45 - private let usageThreshold: CGFloat = 100 + private var scopeIcon: String { + if selectedTarget == "global" { + return "globe" + } + return selectedProject?.isGit == true ? "arrow.triangle.branch" : "folder.fill" + } var body: some View { - NavigationStack(path: $path) { - VStack(spacing: 0) { - if let noticeMessage { - noticeBanner(noticeMessage) - } - - switch viewMode { - case .columns: - columnsBoardContent - case .usage: - KanbanUsageDashboardView( - client: client, - projects: projects, - initialProjectID: selectedProjectID, - refreshTrigger: usageRefreshTrigger - ) - } - } + NavigationStack { + KanbanUsageDashboardView( + client: client, + projects: projects, + selectedTarget: $selectedTarget, + refreshTrigger: usageRefreshTrigger + ) .background(Color(.systemGroupedBackground)) - .navigationTitle(viewMode == .columns ? "看板" : "计量统计") + .navigationTitle(appearance.l("看板", "Board")) .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .topBarLeading) { - if viewMode == .columns { - projectSelectorMenu - } else { - Button { - withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { - viewMode = .columns - } - } label: { - HStack(spacing: 4) { - Image(systemName: "chevron.left") - .font(.subheadline.weight(.semibold)) - Text("看板") - .font(.subheadline.weight(.medium)) - } - } - } + scopeSelectorMenu } ToolbarItem(placement: .principal) { - Text(viewMode == .columns ? "看板" : "计量统计") + Text(appearance.l("看板", "Board")) .font(.headline.weight(.semibold)) } ToolbarItem(placement: .topBarTrailing) { - if viewMode == .columns { - HStack(spacing: 12) { - Button { - withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { - viewMode = .usage - } - } label: { - Image(systemName: "chart.bar.xaxis") - .font(.subheadline.weight(.semibold)) - } - .accessibilityLabel("计量统计") - - Button { - createSheetInitialStatus = .todo - showCreateSheet = true - } label: { - Image(systemName: "plus.circle.fill") - .font(.title3) - } - .accessibilityLabel("新建会话") - } - } else { - Button { - usageRefreshTrigger &+= 1 - } label: { - Image(systemName: "arrow.clockwise") - .font(.subheadline.weight(.semibold)) - } - .accessibilityLabel("刷新统计") - } - } - } - .navigationDestination(for: ConversationListItem.self) { item in - ConversationDetailView(client: client, conversation: item) - } - .sheet(isPresented: $showCreateSheet) { - KanbanCreateSessionSheet( - client: client, - projects: projects, - initialProjectID: selectedProjectID ?? projects.first(where: { !$0.isHome })?.id ?? projects.first?.id, - initialStatus: createSheetInitialStatus ?? .todo - ) { createdItem, initialStatus in - Task { - if initialStatus != .todo { - try? await client.updateSessionStatus(sessionID: createdItem.id, status: initialStatus) - } - await reload() - path.append(createdItem) - } - } - } - .alert( - "重命名会话", - isPresented: Binding( - get: { renamingSession != nil }, - set: { if !$0 { renamingSession = nil } } - ) - ) { - TextField("会话名称", text: $renameDraft) - Button("取消", role: .cancel) { renamingSession = nil } - Button("保存") { - if let target = renamingSession { - performRename(target, newName: renameDraft) + Button { + usageRefreshTrigger &+= 1 + } label: { + Image(systemName: "arrow.clockwise") + .font(.subheadline.weight(.semibold)) } - renamingSession = nil - } - } - .alert( - "删除会话", - isPresented: Binding( - get: { deletingSession != nil }, - set: { if !$0 { deletingSession = nil } } - ), - presenting: deletingSession - ) { target in - Button("取消", role: .cancel) { deletingSession = nil } - Button("删除", role: .destructive) { - performDelete(target) - deletingSession = nil + .accessibilityLabel("刷新统计") } - } message: { target in - Text("确定删除会话“\(target.resolvedTitle)”吗?正在执行中的会话不会被删除。") } } .onAppear { - onChromeHiddenChange?(!path.isEmpty) - } - .onChange(of: path.count) { _, count in - onChromeHiddenChange?(count > 0) + navStore.boardDepth = 0 + if !didApplyInitialScope { + didApplyInitialScope = true + if let pid = navStore.selectedProjectID, !pid.isEmpty { + selectedTarget = "project:\(pid)" + } + } } .task { while !Task.isCancelled { - await reload() - try? await Task.sleep(for: .seconds(errorMessage == nil ? 15 : 4)) + if let loaded = try? await client.projects() { + projects = loaded + } + try? await Task.sleep(for: .seconds(20)) } } } - // MARK: - Top Bars - - private var projectSelectorMenu: some View { + private var scopeSelectorMenu: some View { Menu { Button { - selectedProjectID = nil - Task { await reload() } + selectedTarget = "global" } label: { HStack { - Label("全部项目", systemImage: "square.stack.3d.up") - if selectedProjectID == nil { + Label("全局统计", systemImage: "globe") + if selectedTarget == "global" { Image(systemName: "checkmark") } } } - Divider() - - ForEach(projects) { project in - Button { - selectedProjectID = project.id - Task { await reload() } - } label: { - HStack { - Label( - project.displayName, - systemImage: project.isGit ? "arrow.triangle.branch" : "folder" - ) - if selectedProjectID?.lowercased() == project.id.lowercased() { - Image(systemName: "checkmark") + let visibleProjects = projects.filter { !$0.isHome } + if !visibleProjects.isEmpty { + Divider() + ForEach(visibleProjects) { project in + let target = "project:\(project.id)" + Button { + selectedTarget = target + navStore.selectedProjectID = project.id + } label: { + HStack { + Label( + project.displayName, + systemImage: project.isGit ? "arrow.triangle.branch" : "folder" + ) + if selectedTarget.lowercased() == target.lowercased() { + Image(systemName: "checkmark") + } } } } } } label: { - HStack(spacing: 4) { - Image(systemName: selectedProject?.isGit == true ? "arrow.triangle.branch" : "folder.fill") - .font(.caption) - Text(selectedProject?.displayName ?? "全部项目") + HStack(spacing: 5) { + Image(systemName: scopeIcon) + .font(.caption.weight(.semibold)) + Text(scopeLabel) .font(.subheadline.weight(.semibold)) .lineLimit(1) Image(systemName: "chevron.down") - .font(.caption2) - .foregroundStyle(.secondary) - } - .padding(.horizontal, 10) - .padding(.vertical, 5) - .background(Color(.secondarySystemGroupedBackground), in: Capsule()) - } - } - - private func noticeBanner(_ text: String) -> some View { - HStack(spacing: 8) { - Image(systemName: "info.circle.fill") - .foregroundStyle(Color.accentColor) - .font(.footnote) - Text(text) - .font(.caption) - .lineLimit(2) - Spacer() - Button { - withAnimation { noticeMessage = nil } - } label: { - Image(systemName: "xmark") - .font(.caption2) + .font(.caption2.weight(.semibold)) .foregroundStyle(.secondary) } - .buttonStyle(.plain) - } - .padding(.horizontal, 14) - .padding(.vertical, 8) - .background(Color(.secondarySystemGroupedBackground)) - } - - // MARK: - Four-Column Kanban Board (`builtin:columns`) - - @ViewBuilder - private var columnsBoardContent: some View { - if isLoading && sessions.isEmpty { - KanbanBoardSkeletonView() - } else if let errorMessage, sessions.isEmpty { - Spacer() - LoadFailureView(message: errorMessage) { - Task { await reload() } - } - Spacer() - } else { - ZStack(alignment: .top) { - GeometryReader { proxy in - ScrollView(.horizontal, showsIndicators: false) { - HStack(alignment: .top, spacing: 10) { - ForEach(KanbanSessionStatus.activeColumns) { columnStatus in - kanbanColumnView( - status: columnStatus, - width: min(proxy.size.width - 52, 344) - ) - } - } - .scrollTargetLayout() - .padding(.top, 10 + min(pullOffset * 0.35, 42)) - .padding(.bottom, 86) - } - .contentMargins(.horizontal, 16, for: .scrollContent) - .scrollTargetBehavior(.viewAligned) - } - .simultaneousGesture(twoStagePullGesture) - - if pullOffset > 8 || isPullRefreshing { - pullFeedbackCapsule - .padding(.top, 8) - .transition(.move(edge: .top).combined(with: .opacity)) - } - } - } - } - - private var pullFeedbackCapsule: some View { - let isDeepPull = pullOffset >= usageThreshold - let isHalfPull = pullOffset >= refreshThreshold && !isDeepPull - let label: String = { - if isPullRefreshing { return "正在刷新看板…" } - if isDeepPull { return "松手打开计量统计" } - if isHalfPull { return "松手刷新看板 · 继续下拉打开计量统计" } - return "下拉刷新 · 拉到底打开计量统计" - }() - let iconName: String = { - if isDeepPull { return "chart.bar.xaxis" } - return "arrow.clockwise" - }() - - return HStack(spacing: 6) { - if isPullRefreshing { - ProgressView() - .controlSize(.mini) - } else { - Image(systemName: iconName) - .font(.caption.weight(.semibold)) - .foregroundStyle(isDeepPull ? .white : Color.accentColor) - } - Text(label) - .font(.caption.weight(.semibold)) - .foregroundStyle(isDeepPull ? .white : .primary) - } - .padding(.horizontal, 14) - .padding(.vertical, 7) - .background( - isDeepPull - ? AnyShapeStyle(Color.accentColor) - : AnyShapeStyle(.ultraThinMaterial), - in: Capsule() - ) - .overlay( - Capsule() - .strokeBorder(Color.white.opacity(isDeepPull ? 0.25 : 0.14), lineWidth: 0.5) - ) - .shadow(color: .black.opacity(0.18), radius: 8, y: 3) - } - - private var twoStagePullGesture: some Gesture { - DragGesture(minimumDistance: 16, coordinateSpace: .local) - .onChanged { value in - let dx = value.translation.width - let dy = value.translation.height - guard dy > 0, abs(dy) > abs(dx) * 1.2 else { return } - let damped = min(dy * 0.65, 135) - pullOffset = damped - if damped >= usageThreshold && !didTriggerFullPullHaptic { - didTriggerFullPullHaptic = true - #if canImport(UIKit) - UIImpactFeedbackGenerator(style: .medium).impactOccurred() - #endif - } else if damped < usageThreshold { - didTriggerFullPullHaptic = false - } - } - .onEnded { _ in - let finalOffset = pullOffset - didTriggerFullPullHaptic = false - if finalOffset >= usageThreshold { - withAnimation(.spring(response: 0.28, dampingFraction: 0.85)) { - pullOffset = 0 - viewMode = .usage - } - } else if finalOffset >= refreshThreshold { - withAnimation(.spring(response: 0.25, dampingFraction: 0.85)) { - pullOffset = 0 - isPullRefreshing = true - } - Task { - await reload() - await MainActor.run { - withAnimation(.easeOut(duration: 0.2)) { - isPullRefreshing = false - } - } - } - } else { - withAnimation(.spring(response: 0.24, dampingFraction: 0.85)) { - pullOffset = 0 - } - } - } - } - - private func kanbanColumnView(status: KanbanSessionStatus, width: CGFloat) -> some View { - let items = sessionsForStatus(status) - return VStack(alignment: .leading, spacing: 0) { - // Column Header - HStack(spacing: 7) { - Circle() - .fill(statusColor(status)) - .frame(width: 8, height: 8) - Text(status.title) - .font(.subheadline.weight(.semibold)) - Text("\(items.count)") - .font(.footnote.monospacedDigit().weight(.medium)) - .foregroundStyle(.secondary) - Spacer() - Button { - createSheetInitialStatus = status - showCreateSheet = true - } label: { - Image(systemName: "plus") - .font(.system(size: 12, weight: .bold)) - .foregroundStyle(.secondary) - .frame(width: 26, height: 26) - .background(Color(.tertiarySystemFill), in: Circle()) - } - .buttonStyle(.plain) - .accessibilityLabel("在\(status.title)新建会话") - } - .padding(.horizontal, 12) - .padding(.vertical, 9) - .background(statusColor(status).opacity(0.06)) - - if items.isEmpty { - VStack(spacing: 8) { - Spacer(minLength: 40) - Text("暂无\(status.title)会话") - .font(.caption) - .foregroundStyle(.secondary) - Button { - createSheetInitialStatus = status - showCreateSheet = true - } label: { - Label("新建会话", systemImage: "plus") - .font(.caption.weight(.medium)) - .foregroundStyle(Color.accentColor) - } - .buttonStyle(.plain) - Spacer(minLength: 40) - } - .frame(maxWidth: .infinity) - .padding(12) - } else { - ScrollView(.vertical, showsIndicators: false) { - LazyVStack(spacing: 8) { - ForEach(items) { session in - sessionCard(session, showStatusPill: false) - } - } - .padding(8) - } - } - } - .frame(width: width) - .frame(maxHeight: .infinity, alignment: .top) - .background(Color(.secondarySystemGroupedBackground)) - .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous)) - .overlay( - RoundedRectangle(cornerRadius: 16, style: .continuous) - .strokeBorder(Color.primary.opacity(0.06), lineWidth: 0.5) - ) - } - - // MARK: - Reusable Session Card (`SessionHubListItem` in `kanban-board` mode) - - private func sessionCard(_ session: KanbanSessionSummary, showStatusPill: Bool) -> some View { - let member = session.collaboration?.memberName.flatMap { $0.isEmpty ? nil : $0 } - let showsStatus = !session.isRunning && (showStatusPill || session.status == .inreview) - let accent = session.isRunning ? Color.orange : statusColor(session.status) - - return VStack(alignment: .leading, spacing: 7) { - HStack(alignment: .top, spacing: 6) { - if session.isPinned { - Image(systemName: "pin.fill") - .font(.system(size: 10, weight: .semibold)) - .foregroundStyle(.orange) - .padding(.top, 3) - } - - Text(session.resolvedTitle) - .font(.subheadline.weight(.semibold)) - .foregroundStyle(.primary) - .lineLimit(2) - .multilineTextAlignment(.leading) - - Spacer(minLength: 4) - - Menu { - sessionContextMenuItems(session) - } label: { - Image(systemName: "ellipsis") - .font(.system(size: 13, weight: .semibold)) - .foregroundStyle(.secondary) - .frame(width: 26, height: 20) - .contentShape(Rectangle()) - } - } - - if let prompt = session.firstPrompt?.trimmingCharacters(in: .whitespacesAndNewlines), - !prompt.isEmpty, - prompt != session.resolvedTitle - { - Text(prompt) - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(2) - } - - if session.isRunning || showsStatus || member != nil { - HStack(spacing: 5) { - if session.isRunning { - HStack(spacing: 4) { - ProgressView().controlSize(.mini).tint(.orange) - Text("进行中") - } - .modifier(CardChip(tint: .orange)) - } else if showsStatus { - Text(session.status.title) - .modifier(CardChip(tint: statusColor(session.status))) - } - if let member { - HStack(spacing: 3) { - Image(systemName: "person.2.fill").font(.system(size: 8)) - Text(member).lineLimit(1) - } - .modifier(CardChip(tint: .indigo)) - } - } - } - - HStack(spacing: 5) { - AgentIconView(agent: session.effectiveAgentKey, size: 13) - Text(session.model?.isEmpty == false ? session.model! : session.agentDisplayName) - .lineLimit(1) - .layoutPriority(1) - if !session.workspaceDisplayLabel.isEmpty { - Text("·").foregroundStyle(.quaternary) - Text(session.workspaceDisplayLabel) - .lineLimit(1) - .truncationMode(.middle) - } - Spacer(minLength: 4) - if let date = session.updatedDate { - Text(Self.shortRelative(date)) - .foregroundStyle(.tertiary) - .layoutPriority(2) - } - } - .font(.caption2) - .foregroundStyle(.secondary) - } - .padding(.horizontal, 12) - .padding(.vertical, 10) - .background(Color(.systemBackground), in: RoundedRectangle(cornerRadius: 12, style: .continuous)) - .overlay(alignment: .leading) { - if session.isRunning || session.status == .inreview { - Capsule() - .fill(accent) - .frame(width: 3) - .padding(.vertical, 10) - .padding(.leading, 1.5) - } - } - .overlay( - RoundedRectangle(cornerRadius: 12, style: .continuous) - .strokeBorder( - session.isRunning ? Color.orange.opacity(0.35) : Color.primary.opacity(0.06), - lineWidth: session.isRunning ? 1 : 0.5 - ) - ) - .shadow(color: .black.opacity(0.035), radius: 3, y: 1) - .contentShape(RoundedRectangle(cornerRadius: 12)) - .onTapGesture { - openSession(session) - } - .contextMenu { - sessionContextMenuItems(session) + .foregroundStyle(.primary) } } @@ -595,421 +144,4 @@ struct BoardView: View { if abs(date.timeIntervalSinceNow) < 60 { return "刚刚" } return relativeFormatter.localizedString(for: date, relativeTo: .now) } - - @ViewBuilder - private func sessionContextMenuItems(_ session: KanbanSessionSummary) -> some View { - Button { - openSession(session) - } label: { - Label("打开会话", systemImage: "bubble.left.and.bubble.right") - } - - Menu("移动状态", systemImage: "arrow.left.arrow.right") { - ForEach(KanbanSessionStatus.activeColumns) { status in - Button { - performStatusChange(session, to: status) - } label: { - HStack { - Text(status.title) - if session.status == status { - Image(systemName: "checkmark") - } - } - } - } - } - - Button { - performTogglePin(session) - } label: { - Label( - session.isPinned ? "取消置顶" : "置顶", - systemImage: session.isPinned ? "pin.slash" : "pin" - ) - } - - Button { - renameDraft = session.resolvedTitle - renamingSession = session - } label: { - Label("重命名会话", systemImage: "pencil") - } - - if session.isForkSupported { - Button { - performFork(session) - } label: { - Label("从本会话 Fork", systemImage: "arrow.branch") - } - } - - Menu("复制") { - Button { - copyToClipboard(session.resolvedTitle) - noticeMessage = "已复制会话名称" - } label: { - Label("会话名称", systemImage: "doc.on.doc") - } - Button { - copyToClipboard(session.sessionInfoText) - noticeMessage = "已复制会话信息" - } label: { - Label("会话信息", systemImage: "info.circle") - } - } - - Divider() - - if session.isArchived { - Button { - performStatusChange(session, to: .todo) - } label: { - Label("移至待办", systemImage: "tray.and.arrow.up") - } - } else { - Button { - performStatusChange(session, to: .archived) - } label: { - Label("归档", systemImage: "archivebox") - } - } - - Button(role: .destructive) { - deletingSession = session - } label: { - Label("删除会话", systemImage: "trash") - } - } - - // MARK: - Computed Properties & Sorting - - private var selectedProject: ProjectSummary? { - guard let selectedProjectID else { return nil } - return projects.first { $0.id.lowercased() == selectedProjectID.lowercased() } - } - - private var activeSessions: [KanbanSessionSummary] { - sessions.filter { !$0.isArchived } - } - - private func sessionsForStatus(_ status: KanbanSessionStatus) -> [KanbanSessionSummary] { - sortSessionsList(activeSessions.filter { $0.status == status }, by: .defaultOrder) - } - - private func sortSessionsList( - _ list: [KanbanSessionSummary], - by field: KanbanSortField - ) -> [KanbanSessionSummary] { - list.sorted { left, right in - if left.isPinned != right.isPinned { - return left.isPinned && !right.isPinned - } - switch field { - case .defaultOrder, .time: - return (left.updatedDate ?? .distantPast) > (right.updatedDate ?? .distantPast) - case .name: - let cmp = left.resolvedTitle.localizedStandardCompare(right.resolvedTitle) - if cmp != .orderedSame { return cmp == .orderedAscending } - return (left.updatedDate ?? .distantPast) > (right.updatedDate ?? .distantPast) - case .status: - if left.status.sortOrder != right.status.sortOrder { - return left.status.sortOrder < right.status.sortOrder - } - return (left.updatedDate ?? .distantPast) > (right.updatedDate ?? .distantPast) - case .agent: - let cmp = left.agentDisplayName.localizedStandardCompare(right.agentDisplayName) - if cmp != .orderedSame { return cmp == .orderedAscending } - return (left.updatedDate ?? .distantPast) > (right.updatedDate ?? .distantPast) - } - } - } - - private func statusColor(_ status: KanbanSessionStatus) -> Color { - switch status { - case .todo: return .blue - case .inprogress: return .orange - case .inreview: return .purple - case .done: return .green - case .archived: return .gray - } - } - - // MARK: - Actions & Data Loading - - private func reload() async { - do { - let loadedProjects = try await client.projects() - projects = loadedProjects - let wsIDs: [String] - if let selectedProjectID, - let match = loadedProjects.first(where: { $0.id.lowercased() == selectedProjectID.lowercased() }) - { - wsIDs = match.workspaceIds - if let wsList = try? await client.kanbanWorkspaces(projectID: match.id) { - workspaces = wsList - } - } else { - wsIDs = loadedProjects.flatMap(\.workspaceIds) - } - let loadedSessions = try await client.kanbanAllSessions(workspaceIDs: wsIDs) - sessions = loadedSessions - errorMessage = nil - isLoading = false - } catch { - errorMessage = describeHostFailure(error) - isLoading = false - } - } - - private func openSession(_ session: KanbanSessionSummary) { - if session.completesWhenViewed { - if let idx = sessions.firstIndex(where: { $0.id == session.id }) { - sessions[idx].status = .done - } - Task { - try? await client.markSessionViewed(sessionID: session.id) - await reload() - } - } - path.append(session.asConversationListItem) - } - - private func performStatusChange(_ session: KanbanSessionSummary, to newStatus: KanbanSessionStatus) { - let oldStatus = session.status - if let idx = sessions.firstIndex(where: { $0.id == session.id }) { - sessions[idx].status = newStatus - } - Task { - do { - try await client.updateSessionStatus(sessionID: session.id, status: newStatus) - await reload() - } catch { - if let idx = sessions.firstIndex(where: { $0.id == session.id }) { - sessions[idx].status = oldStatus - } - noticeMessage = describeHostFailure(error) - } - } - } - - private func performTogglePin(_ session: KanbanSessionSummary) { - let nextPinned = !session.isPinned - if let idx = sessions.firstIndex(where: { $0.id == session.id }) { - sessions[idx].pinnedAt = nextPinned ? ISO8601DateFormatter().string(from: Date()) : nil - } - Task { - do { - try await client.setSessionPinned(sessionID: session.id, pinned: nextPinned) - await reload() - } catch { - noticeMessage = describeHostFailure(error) - await reload() - } - } - } - - private func performRename(_ session: KanbanSessionSummary, newName: String) { - let trimmed = newName.trimmingCharacters(in: .whitespacesAndNewlines) - if let idx = sessions.firstIndex(where: { $0.id == session.id }) { - sessions[idx].name = trimmed.isEmpty ? nil : trimmed - } - Task { - do { - try await client.renameSession(sessionID: session.id, name: trimmed.isEmpty ? nil : trimmed) - await reload() - } catch { - noticeMessage = describeHostFailure(error) - await reload() - } - } - } - - private func performDelete(_ session: KanbanSessionSummary) { - let removed = session - withAnimation { - sessions.removeAll { $0.id == session.id } - } - Task { - do { - try await client.deleteKanbanSession(sessionID: removed.id) - await reload() - } catch { - noticeMessage = describeHostFailure(error) - await reload() - } - } - } - - private func performFork(_ session: KanbanSessionSummary) { - Task { - do { - if let newID = try await client.forkConversation(conversationID: session.id) { - noticeMessage = "已分叉会话" - await reload() - if let forked = sessions.first(where: { $0.id == newID }) { - openSession(forked) - } - } - } catch { - noticeMessage = "分叉失败:\(describeHostFailure(error))" - } - } - } - - private func copyToClipboard(_ text: String) { - #if canImport(UIKit) - UIPasteboard.general.string = text - #endif - } -} - -// MARK: - Create Kanban Session Sheet - -private struct KanbanCreateSessionSheet: View { - let client: HostClient - let projects: [ProjectSummary] - let initialProjectID: String? - let initialStatus: KanbanSessionStatus - let onCreated: (ConversationListItem, KanbanSessionStatus) -> Void - - @Environment(\.dismiss) private var dismiss - @State private var selectedProjectID: String = "" - @State private var agents: [CatalogAgent] = [] - @State private var selectedAgentID: String = "claude_code" - @State private var selectedStatus: KanbanSessionStatus = .todo - @State private var sessionName: String = "" - @State private var initialPrompt: String = "" - @State private var isSubmitting = false - @State private var errorMessage: String? - - var body: some View { - NavigationStack { - Form { - Section("归属项目与状态") { - Picker("项目", selection: $selectedProjectID) { - ForEach(projects) { project in - Text(project.displayName).tag(project.id) - } - } - - Picker("看板列", selection: $selectedStatus) { - ForEach(KanbanSessionStatus.activeColumns) { status in - Text(status.title).tag(status) - } - } - } - - Section("编程代理") { - if agents.isEmpty { - HStack { - Text("默认代理") - Spacer() - AgentModelLabel( - agent: selectedAgentID, - model: KanbanSessionSummary.formatAgentDisplayName(selectedAgentID) - ) - .foregroundStyle(.secondary) - } - } else { - Picker("Agent", selection: $selectedAgentID) { - ForEach(agents) { agent in - AgentMenuLabel(agentID: agent.id, hostName: agent.displayName).tag(agent.id) - } - } - } - } - - Section("会话信息(可选)") { - TextField("会话名称(留空则自动生成)", text: $sessionName) - TextField("初始消息 / 任务描述(可选)", text: $initialPrompt, axis: .vertical) - .lineLimit(3...6) - } - - if let errorMessage { - Section { - Text(errorMessage) - .font(.footnote) - .foregroundStyle(.red) - } - } - } - .navigationTitle("新建会话") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("取消") { dismiss() } - } - ToolbarItem(placement: .confirmationAction) { - Button { - Task { await create() } - } label: { - if isSubmitting { - ProgressView() - } else { - Text("创建会话") - } - } - .disabled(isSubmitting || selectedWorkspaceID == nil) - } - } - .onAppear { - selectedStatus = initialStatus - if selectedProjectID.isEmpty { - selectedProjectID = initialProjectID ?? projects.first?.id ?? "" - } - } - .task { - if let loaded = try? await client.agentCatalog(), !loaded.isEmpty { - agents = loaded - if let usable = loaded.first(where: \.usable) ?? loaded.first { - selectedAgentID = usable.id - } - } - } - } - } - - private var selectedWorkspaceID: String? { - projects.first { $0.id == selectedProjectID }?.workspaceIds.first - ?? projects.first?.workspaceIds.first - } - - private func create() async { - guard let workspaceID = selectedWorkspaceID else { return } - isSubmitting = true - defer { isSubmitting = false } - do { - var created = try await client.createConversation( - workspaceID: workspaceID, - agentID: selectedAgentID - ) - let trimmedName = sessionName.trimmingCharacters(in: .whitespacesAndNewlines) - if !trimmedName.isEmpty { - try? await client.renameSession(sessionID: created.id, name: trimmedName) - created = ConversationListItem( - id: created.id, - workspace_id: created.workspace_id, - title: trimmedName, - status: selectedStatus.rawValue, - agent_id: created.agent_id, - model: created.model, - message_count: created.message_count, - updated_at: created.updated_at - ) - } - let trimmedPrompt = initialPrompt.trimmingCharacters(in: .whitespacesAndNewlines) - if !trimmedPrompt.isEmpty { - try? await client.sendMessage( - conversationID: created.id, - workspaceID: workspaceID, - agentID: selectedAgentID, - text: trimmedPrompt - ) - } - dismiss() - onCreated(created, selectedStatus) - } catch { - errorMessage = describeHostFailure(error) - } - } } diff --git a/App/CollaborationChatView.swift b/App/CollaborationChatView.swift index 4a08804..112a608 100644 --- a/App/CollaborationChatView.swift +++ b/App/CollaborationChatView.swift @@ -347,9 +347,7 @@ struct CollaborationChatView: View { // MARK: - Composer Bar private var composerBar: some View { - VStack(spacing: 6) { - Divider() - + VStack(spacing: 8) { if let reply = replyingTo { HStack(spacing: 8) { Image(systemName: "arrowshape.turn.up.left.fill") @@ -367,8 +365,8 @@ struct CollaborationChatView: View { .foregroundStyle(.secondary) } } - .padding(.horizontal, 14) - .padding(.top, 4) + .padding(.horizontal, 18) + .padding(.top, 2) } if item.isGroup && !agentMembers.isEmpty { @@ -383,7 +381,7 @@ struct CollaborationChatView: View { ) } } - .padding(.horizontal, 14) + .padding(.horizontal, 16) } .fixedSize(horizontal: false, vertical: true) } @@ -392,10 +390,10 @@ struct CollaborationChatView: View { Text(errorMessage) .font(.system(size: 11)) .foregroundStyle(.red) - .padding(.horizontal, 14) + .padding(.horizontal, 16) } - HStack(alignment: .bottom, spacing: 8) { + HStack(alignment: .bottom, spacing: 6) { if item.isGroup { Menu { ForEach(Self.delayOptions, id: \.seconds) { option in @@ -415,7 +413,7 @@ struct CollaborationChatView: View { Image(systemName: delaySeconds > 0 ? "clock.badge.checkmark.fill" : "clock") .font(.system(size: 17)) .foregroundStyle(delaySeconds > 0 ? Color.orange : Color.secondary) - .frame(width: 32, height: 34) + .frame(width: 34, height: 36) } .accessibilityLabel("定时发送") } @@ -426,28 +424,43 @@ struct CollaborationChatView: View { axis: .vertical ) .lineLimit(1...5) - .font(.system(size: 14)) - .padding(.horizontal, 12) - .padding(.vertical, 8) - .background( - RoundedRectangle(cornerRadius: 18, style: .continuous) - .fill(Color(.secondarySystemGroupedBackground)) - ) + .font(.system(size: 15.5)) + .padding(.leading, item.isGroup ? 4 : 10) + .padding(.vertical, 7) + .frame(minHeight: 36) Button { sendMessage() } label: { - Image(systemName: "arrow.up.circle.fill") - .font(.system(size: 30)) - .foregroundStyle(canSend ? Color.blue : Color.secondary.opacity(0.4)) + Image(systemName: "arrow.up") + .font(.system(size: 15, weight: .bold)) + .foregroundStyle(canSend ? Color(.systemBackground) : Color.primary.opacity(0.36)) + .frame(width: 36, height: 36) + .background( + Circle() + .fill(canSend ? Color.primary : Color.primary.opacity(0.08)) + ) + .animation(.easeOut(duration: 0.18), value: canSend) } + .buttonStyle(.plain) .disabled(!canSend) .accessibilityLabel("发送") } - .padding(.horizontal, 12) + .padding(.leading, 8) + .padding(.trailing, 8) + .padding(.vertical, 8) + .background( + RoundedRectangle(cornerRadius: 26, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + .shadow(color: .black.opacity(0.08), radius: 14, x: 0, y: 4) + ) + .overlay( + RoundedRectangle(cornerRadius: 26, style: .continuous) + .strokeBorder(Color.primary.opacity(0.09), lineWidth: 0.75) + ) + .padding(.horizontal, 14) .padding(.bottom, 8) } - .background(Color(.systemBackground)) } private func mentionChip(name: String, label: String, avatar: CollabBotAvatarConfig?) -> some View { diff --git a/App/CollaborationSpaceView.swift b/App/CollaborationSpaceView.swift index 07cb9ae..7cdcce9 100644 --- a/App/CollaborationSpaceView.swift +++ b/App/CollaborationSpaceView.swift @@ -8,8 +8,8 @@ enum CollabNavRoute: Hashable { struct CollaborationSpaceView: View { let client: HostClient - var onChromeHiddenChange: ((Bool) -> Void)? = nil + @Environment(WorkspaceNavigationStore.self) private var navStore @State private var projects: [ProjectSummary] = [] @State private var selectedProjectID: String = "" @State private var sidebarItems: [CollabSidebarItem] = [] @@ -53,24 +53,7 @@ struct CollaborationSpaceView: View { var body: some View { NavigationStack(path: $path) { - VStack(spacing: 0) { - HStack { - Spacer() - Picker("切换视图", selection: $filterKind) { - ForEach(FilterKind.allCases) { kind in - Text(kind.rawValue).tag(kind) - } - } - .pickerStyle(.segmented) - .frame(width: 196) - Spacer() - } - .padding(.horizontal, 16) - .padding(.vertical, 8) - .background(Color(.systemGroupedBackground)) - - content - } + content .navigationTitle("协作空间") .navigationBarTitleDisplayMode(.inline) .toolbar { @@ -80,6 +63,7 @@ struct CollaborationSpaceView: View { ForEach(orderedProjects) { project in Button { selectedProjectID = project.id + navStore.selectedProjectID = project.id Task { await reload() } } label: { HStack { @@ -91,19 +75,17 @@ struct CollaborationSpaceView: View { } } } label: { - HStack(spacing: 4) { + HStack(spacing: 5) { Image(systemName: activeProject?.isGit == true ? "arrow.triangle.branch" : "folder.fill") - .font(.caption) + .font(.caption.weight(.semibold)) Text(activeProject?.name ?? "选择项目") .font(.subheadline.weight(.semibold)) .lineLimit(1) Image(systemName: "chevron.down") - .font(.caption2) + .font(.caption2.weight(.semibold)) .foregroundStyle(.secondary) } - .padding(.horizontal, 10) - .padding(.vertical, 5) - .background(Color(.secondarySystemGroupedBackground), in: Capsule()) + .foregroundStyle(.primary) } } } @@ -209,10 +191,13 @@ struct CollaborationSpaceView: View { } } .onAppear { - onChromeHiddenChange?(!path.isEmpty) + if let globalProjectID = navStore.selectedProjectID, !globalProjectID.isEmpty { + selectedProjectID = globalProjectID + } + navStore.spaceDepth = path.count } .onChange(of: path.count) { _, count in - onChromeHiddenChange?(count > 0) + navStore.spaceDepth = count } .task { while !Task.isCancelled { @@ -224,18 +209,35 @@ struct CollaborationSpaceView: View { // MARK: - Filtering & Grouping + private var trimmedSearchQuery: String { + searchQuery.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var isSearching: Bool { + !trimmedSearchQuery.isEmpty + } + private var filteredItems: [CollabSidebarItem] { - switch filterKind { - case .all: - return sidebarItems - case .primary: + let basePool: [CollabSidebarItem] + if isSearching || filterKind == .all { + basePool = sidebarItems + } else { let primaryPool = sidebarItems.filter { item in item.isGroup || item.member?.isSupervisor == true || item.unreadCount > 0 || item.lastMessage != nil } - return primaryPool.isEmpty ? sidebarItems : primaryPool + basePool = primaryPool.isEmpty ? sidebarItems : primaryPool + } + + guard isSearching else { return basePool } + let q = trimmedSearchQuery.lowercased() + return basePool.filter { item in + let matchesName = item.displayName.lowercased().contains(q) + let matchesPreview = item.lastMessage?.preview?.lowercased().contains(q) ?? false + let matchesAgent = AgentBrand.displayName(item.member?.agent).lowercased().contains(q) + return matchesName || matchesPreview || matchesAgent } } @@ -252,23 +254,29 @@ struct CollaborationSpaceView: View { return filteredItems.filter { $0.id != sup.id } } - private var searchResults: [SearchResultItem] { - let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - guard !q.isEmpty else { return [] } - return sidebarItems.compactMap { item in - let matchesName = item.displayName.lowercased().contains(q) - let matchesPreview = item.lastMessage?.preview?.lowercased().contains(q) ?? false - guard matchesName || matchesPreview else { return nil } - return SearchResultItem( - id: item.id, - title: item.displayName, - subtitle: item.lastMessage?.preview ?? (item.isGroup ? "群组" : "私聊"), - icon: item.isGroup ? "person.3.fill" : "person.crop.circle.fill", - action: { - cachedSidebarByThreadID[item.threadId] = item - path.append(.chat(threadID: item.threadId)) - } + private var searchAndFilterHeader: some View { + VStack(spacing: 10) { + UnifiedSearchBar( + query: $searchQuery, + placeholder: "搜索群组或助手…" ) + + HStack { + Picker("切换视图", selection: $filterKind) { + ForEach(FilterKind.allCases) { kind in + Text(kind.rawValue).tag(kind) + } + } + .pickerStyle(.segmented) + .frame(maxWidth: 210) + + Spacer(minLength: 10) + + Text("\(filteredItems.count) 个协作") + .font(.system(size: 12, weight: .medium)) + .monospacedDigit() + .foregroundStyle(.secondary) + } } } @@ -281,13 +289,9 @@ struct CollaborationSpaceView: View { } else { List { Section { - SearchListCard( - query: $searchQuery, - placeholder: "搜索群组或助手…", - results: searchResults - ) + searchAndFilterHeader } - .listRowInsets(EdgeInsets(top: 4, leading: 0, bottom: 8, trailing: 0)) + .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 4, trailing: 0)) .listRowBackground(Color.clear) .listRowSeparator(.hidden) @@ -302,64 +306,76 @@ struct CollaborationSpaceView: View { if nonSupervisorItems.isEmpty && supervisorItem == nil { Section { - ContentUnavailableView { - Label("还没有群组或助手", systemImage: "person.2") - } description: { - Text("点击右上角 + 创建助手或群组,开启多智能体协作") + if isSearching { + ContentUnavailableView { + Label("没有匹配的群组或助手", systemImage: "magnifyingglass") + } description: { + Text("换个关键词试试") + } + .frame(maxWidth: .infinity) + .padding(.vertical, 24) + } else { + ContentUnavailableView { + Label("还没有群组或助手", systemImage: "person.2") + } description: { + Text("点击右上角 + 创建助手或群组,开启多智能体协作") + } + .frame(maxWidth: .infinity) + .padding(.vertical, 24) } - .frame(maxWidth: .infinity) - .padding(.vertical, 24) } .listRowBackground(Color.clear) } else if !contactGroups.isEmpty { ForEach(contactGroups) { group in let groupEntries = nonSupervisorItems.filter { $0.groupId == group.groupId } - let isCollapsed = collapsedGroupIDs.contains(group.groupId) - Section { - if !isCollapsed { - ForEach(groupEntries) { item in - NavigationLink(value: CollabNavRoute.chat(threadID: item.threadId)) { - CollabContactRow(item: item, isSupervisorSlot: false) - } - .modifier(rowActions(for: item)) - } - } - } header: { - HStack { - Button { - withAnimation { - if isCollapsed { - collapsedGroupIDs.remove(group.groupId) - } else { - collapsedGroupIDs.insert(group.groupId) + if !isSearching || !groupEntries.isEmpty { + let isCollapsed = collapsedGroupIDs.contains(group.groupId) && !isSearching + Section { + if !isCollapsed { + ForEach(groupEntries) { item in + NavigationLink(value: CollabNavRoute.chat(threadID: item.threadId)) { + CollabContactRow(item: item, isSupervisorSlot: false) } + .modifier(rowActions(for: item)) } - } label: { - HStack(spacing: 6) { - Image(systemName: isCollapsed ? "chevron.right" : "chevron.down") - .font(.system(size: 11, weight: .semibold)) - Text("\(group.name) (\(groupEntries.count))") - } - .foregroundStyle(.secondary) } - .buttonStyle(.plain) - Spacer() - Menu { + } header: { + HStack { Button { - renameGroupDraft = group.name - renamingGroup = group + withAnimation { + if collapsedGroupIDs.contains(group.groupId) { + collapsedGroupIDs.remove(group.groupId) + } else { + collapsedGroupIDs.insert(group.groupId) + } + } } label: { - Label("重命名分组", systemImage: "pencil") + HStack(spacing: 6) { + Image(systemName: isCollapsed ? "chevron.right" : "chevron.down") + .font(.system(size: 11, weight: .semibold)) + Text("\(group.name) (\(groupEntries.count))") + } + .foregroundStyle(.secondary) } - Button(role: .destructive) { - deleteContactGroup(group) + .buttonStyle(.plain) + Spacer() + Menu { + Button { + renameGroupDraft = group.name + renamingGroup = group + } label: { + Label("重命名分组", systemImage: "pencil") + } + Button(role: .destructive) { + deleteContactGroup(group) + } label: { + Label("删除分组", systemImage: "trash") + } } label: { - Label("删除分组", systemImage: "trash") + Image(systemName: "ellipsis") + .font(.system(size: 12)) + .foregroundStyle(.secondary) } - } label: { - Image(systemName: "ellipsis") - .font(.system(size: 12)) - .foregroundStyle(.secondary) } } } @@ -407,8 +423,10 @@ struct CollaborationSpaceView: View { } } } + .contentMargins(.top, 8, for: .scrollContent) .listSectionSpacing(10) - .scrollDismissesKeyboard(.immediately) + .safeAreaPadding(.bottom, WorkspaceNavigationStore.bottomDockClearance) + .scrollDismissesKeyboard(.interactively) .refreshable { await reload() } } } @@ -443,6 +461,7 @@ struct CollaborationSpaceView: View { async let spacesTask = client.collabSpaces(workspaceID: workspaceID) let fetchedSidebar = try await sidebarTask sidebarItems = fetchedSidebar + navStore.collabUnreadCount = fetchedSidebar.reduce(0) { $0 + max(0, $1.unreadCount) } for item in fetchedSidebar { cachedSidebarByThreadID[item.threadId] = item } diff --git a/App/CompanionAttentionCenter.swift b/App/CompanionAttentionCenter.swift index cc9d11c..c7b91e0 100644 --- a/App/CompanionAttentionCenter.swift +++ b/App/CompanionAttentionCenter.swift @@ -688,8 +688,11 @@ final class CompanionAttentionCenter: NSObject, UNUserNotificationCenterDelegate willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void ) { - // Always present native iOS system notification banner & sound even when app is in foreground - completionHandler([.banner, .list, .sound]) + if UserDefaults.standard.bool(forKey: "vibex.notify.muteForeground") { + completionHandler([]) + } else { + completionHandler([.banner, .list, .sound]) + } } nonisolated func userNotificationCenter( @@ -800,6 +803,8 @@ struct CompanionToastOverlay: View { @State private var replyText = "" @State private var remainingFraction: CGFloat = 1.0 @FocusState private var replyFocused: Bool + @AppStorage("vibex.security.confirmHighRiskApproval") private var confirmHighRiskApproval = true + @State private var pendingHighRiskConfirm: (toast: CompanionAttentionToast, prompt: PermissionPrompt, option: PermissionOption)? var body: some View { if let toast = center.activeToast { @@ -1051,6 +1056,35 @@ struct CompanionToastOverlay: View { .strokeBorder(toast.kind.accentColor.opacity(0.28), lineWidth: 1) ) .shadow(color: .black.opacity(0.14), radius: 18, x: 0, y: 8) + .confirmationDialog( + "确认允许执行此操作?", + isPresented: Binding( + get: { pendingHighRiskConfirm != nil }, + set: { if !$0 { pendingHighRiskConfirm = nil } } + ), + titleVisibility: .visible + ) { + if let pending = pendingHighRiskConfirm { + Button("确认\(pending.option.label)", role: .destructive) { + pendingHighRiskConfirm = nil + Task { + await center.respondPermission( + client: client, + conversationID: pending.toast.conversation.id, + prompt: pending.prompt, + option: pending.option + ) + } + } + } + Button("取消", role: .cancel) { + pendingHighRiskConfirm = nil + } + } message: { + if let pending = pendingHighRiskConfirm { + Text(pending.prompt.command ?? pending.prompt.displayHeading) + } + } } @ViewBuilder @@ -1060,13 +1094,17 @@ struct CompanionToastOverlay: View { ForEach(prompt.options) { option in let allow = option.kind.hasPrefix("allow") Button { - Task { - await center.respondPermission( - client: client, - conversationID: toast.conversation.id, - prompt: prompt, - option: option - ) + if allow && confirmHighRiskApproval { + pendingHighRiskConfirm = (toast, prompt, option) + } else { + Task { + await center.respondPermission( + client: client, + conversationID: toast.conversation.id, + prompt: prompt, + option: option + ) + } } } label: { HStack(spacing: 4) { diff --git a/App/ConversationDetailView.swift b/App/ConversationDetailView.swift index c2509d8..c02a28c 100644 --- a/App/ConversationDetailView.swift +++ b/App/ConversationDetailView.swift @@ -29,25 +29,35 @@ struct ConversationDetailView: View { !userDetachedFromBottom && !isUserDraggingScroll && distanceFromBottom <= bottomSafeZoneThreshold } - var onToggleSidebar: (() -> Void)? - var onReturnToLanding: (() -> Void)? + @Environment(\.dismiss) private var dismiss + var onBack: (() -> Void)? + var onMessageSent: ((String) -> Void)? + var onTurnFinishedWhileViewing: (() -> Void)? init( client: HostClient, conversation: ConversationListItem, - onToggleSidebar: (() -> Void)? = nil, - onReturnToLanding: (() -> Void)? = nil + initialPrompt: PendingInitialPrompt? = nil, + onBack: (() -> Void)? = nil, + onMessageSent: ((String) -> Void)? = nil, + onTurnFinishedWhileViewing: (() -> Void)? = nil ) { - _model = State(initialValue: ConversationModel(client: client, conversation: conversation)) - self.onToggleSidebar = onToggleSidebar - self.onReturnToLanding = onReturnToLanding + _model = State( + initialValue: ConversationModel( + client: client, + conversation: conversation, + initialPrompt: initialPrompt + ) + ) + self.onBack = onBack + self.onMessageSent = onMessageSent + self.onTurnFinishedWhileViewing = onTurnFinishedWhileViewing } var body: some View { VStack(spacing: 0) { - if onToggleSidebar != nil { - embeddedHeaderBar - } + levelTwoHeaderBar + messages .overlay { if menu != nil { @@ -55,7 +65,7 @@ struct ConversationDetailView: View { } } if !model.items.currentPlan.isEmpty { - TaskDock(tasks: model.items.currentPlan, running: model.session.isTurnRunning) + TaskDock(tasks: model.items.currentPlan, running: model.isThinkingOrRunning) .padding(.horizontal, 12) .padding(.bottom, 8) } @@ -80,37 +90,10 @@ struct ConversationDetailView: View { .padding(.horizontal, 16) .padding(.top, 6) } - if totalChangeCount > 0 { - changesSummaryBar(count: totalChangeCount) - .padding(.horizontal, 12) - .padding(.top, 6) - } - promptBar.padding(.top, totalChangeCount > 0 ? 4 : 8) - } - .navigationTitle(model.conversation.title ?? "未命名对话") - .navigationBarTitleDisplayMode(.inline) - .toolbar(onToggleSidebar != nil ? .hidden : .visible, for: .navigationBar) - .toolbar(onToggleSidebar != nil ? .visible : .hidden, for: .tabBar) - .toolbar { - ToolbarItem(placement: .primaryAction) { - Menu { - Menu("新对话", systemImage: "square.and.pencil") { - ForEach(model.newConversationAgents) { agent in - Button { - Task { created = await model.createConversation(agentID: agent.id) } - } label: { - AgentMenuLabel(agentID: agent.id, hostName: agent.displayName) - } - } - } - Button("浏览文件", systemImage: "folder") { panel = .files } - Button("代码差异", systemImage: "plus.forwardslash.minus") { panel = .changes } - } label: { - Image(systemName: "ellipsis") - } - .accessibilityLabel("更多") - } + promptBar.padding(.top, 6) } + .toolbar(.hidden, for: .navigationBar) + .toolbar(.hidden, for: .tabBar) .sheet(item: $panel) { panel in switch panel { case .files: @@ -138,6 +121,11 @@ struct ConversationDetailView: View { } .navigationDestination(item: $created) { ConversationDetailView(client: model.client, conversation: $0) } .background { Color(.systemGroupedBackground).ignoresSafeArea() } + .task { + if let failedDraft = await model.dispatchInitialPromptIfNeeded() { + draft = failedDraft + } + } .task { while !Task.isCancelled { await model.reload() @@ -156,158 +144,68 @@ struct ConversationDetailView: View { workspaceDiffCount = diffs.count } } - .onChange(of: model.session.isTurnRunning) { _, running in + .onChange(of: model.isThinkingOrRunning) { wasRunning, running in if !running { + let shouldMarkViewed = wasRunning + && model.session.pendingPermissions.isEmpty + && model.session.pendingQuestions.isEmpty Task { + if shouldMarkViewed { + try? await model.client.markSessionViewed(sessionID: model.conversation.id) + onTurnFinishedWhileViewing?() + } if let diffs = try? await model.client.workspaceDiff(workspaceID: model.conversation.workspace_id) { workspaceDiffCount = diffs.count } } } } - .onChange(of: menu) { _, kind in - if kind == .model || kind == .plusModel { Task { await model.refreshCatalog() } } - } } - private func changesSummaryBar(count: Int) -> some View { - HStack(spacing: 10) { - Button { - UIImpactFeedbackGenerator(style: .light).impactOccurred() - panel = .changes - } label: { - HStack(spacing: 6) { - Image(systemName: "gearshape") - .font(.system(size: 11.5, weight: .medium)) - .foregroundStyle(.secondary) - Text("\(count) CHANGES") - .font(.system(size: 11.5, weight: .semibold, design: .monospaced)) - .tracking(0.3) - .foregroundStyle(.primary.opacity(0.88)) + private var levelTwoHeaderBar: some View { + HStack(spacing: 12) { + FloatingCircleBackButton { + if let onBack { + onBack() + } else { + dismiss() } - .padding(.horizontal, 10) - .padding(.vertical, 5) - .background( - Capsule(style: .continuous) - .fill(Color(.secondarySystemGroupedBackground)) - ) - .overlay( - Capsule(style: .continuous) - .strokeBorder(Color.primary.opacity(0.10), lineWidth: 0.75) - ) - } - .buttonStyle(.plain) - - Spacer() - - Button { - UIImpactFeedbackGenerator(style: .light).impactOccurred() - panel = .files - } label: { - Image(systemName: "folder") - .font(.system(size: 12.5, weight: .medium)) - .foregroundStyle(.secondary) - .frame(width: 26, height: 26) - .background( - RoundedRectangle(cornerRadius: 6, style: .continuous) - .fill(Color(.secondarySystemGroupedBackground)) - ) - } - .buttonStyle(.plain) - .accessibilityLabel("浏览文件") - } - } - - private var embeddedHeaderBar: some View { - HStack(spacing: 10) { - Button { - dismissKeyboard() - onToggleSidebar?() - } label: { - Image(systemName: "sidebar.left") - .font(.system(size: 16.5, weight: .medium)) - .foregroundStyle(.primary) - .frame(width: 36, height: 36) - .background( - Circle() - .fill(Color(.secondarySystemGroupedBackground)) - ) } - .buttonStyle(.plain) - .accessibilityLabel("打开侧边栏") - VStack(spacing: 1.5) { - HStack(spacing: 5) { - if model.session.isTurnRunning { + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 6) { + if model.isThinkingOrRunning { Circle() .fill(Color.orange) - .frame(width: 6.5, height: 6.5) + .frame(width: 7, height: 7) } - Text(model.conversation.title ?? "未命名对话") - .font(.system(size: 15.5, weight: .semibold)) + Text(model.conversation.title ?? "未命名会话") + .font(.system(size: 16.5, weight: .bold)) .foregroundStyle(.primary) .lineLimit(1) } - HStack(spacing: 4) { - AgentIconView(agent: model.conversation.agent_id, size: 11) + HStack(spacing: 4.5) { + AgentIconView(agent: model.conversation.agent_id, size: 11.5) Text(model.currentModelLabel ?? AgentBrand.displayName(model.conversation.agent_id)) - .font(.system(size: 11, weight: .medium)) + .font(.system(size: 11.5, weight: .medium)) .foregroundStyle(.secondary) .lineLimit(1) } } - .frame(maxWidth: .infinity) - HStack(spacing: 6) { - if let onReturnToLanding { - Button { - dismissKeyboard() - onReturnToLanding() - } label: { - Image(systemName: "square.and.pencil") - .font(.system(size: 15.5, weight: .medium)) - .foregroundStyle(.primary) - .frame(width: 36, height: 36) - .background( - Circle() - .fill(Color(.secondarySystemGroupedBackground)) - ) - } - .buttonStyle(.plain) - .accessibilityLabel("新建对话") - } + Spacer(minLength: 6) - Menu { - Button("浏览项目文件", systemImage: "folder") { panel = .files } - Button("查看代码变更 (Diff)", systemImage: "plus.forwardslash.minus") { panel = .changes } - if let onReturnToLanding { - Divider() - Button("回到新对话工作台", systemImage: "sparkles") { - onReturnToLanding() - } - } - } label: { - Image(systemName: "ellipsis") - .font(.system(size: 15.5, weight: .medium)) - .foregroundStyle(.primary) - .frame(width: 36, height: 36) - .background( - Circle() - .fill(Color(.secondarySystemGroupedBackground)) - ) - } - .accessibilityLabel("更多操作") - } + WorkspaceDualToolsCapsule( + changeCount: totalChangeCount, + onOpenChanges: { panel = .changes }, + onOpenFiles: { panel = .files } + ) } - .padding(.horizontal, 12) - .padding(.vertical, 7) - .background( - Color(.systemGroupedBackground) - .overlay(alignment: .bottom) { - Divider().opacity(0.45) - } - ) + .padding(.horizontal, 14) + .padding(.top, 6) + .padding(.bottom, 8) + .background(Color(.systemGroupedBackground)) } // MARK: Prompt bar @@ -316,16 +214,15 @@ struct ConversationDetailView: View { PromptBar( draft: $draft, menu: $menu, - isRunning: model.session.isTurnRunning, + isRunning: model.isThinkingOrRunning, busy: model.busy, hasAlert: !model.session.pendingPermissions.isEmpty, modelName: model.currentModelLabel, agentID: model.conversation.agent_id, + agentName: AgentBrand.displayName(model.conversation.agent_id, hostName: model.currentAgent?.displayName), modelChoices: modelChoices, - otherModelGroups: otherModelGroups, - otherAgentNote: otherModelGroups.isEmpty - ? nil - : "此对话使用 \(model.currentAgent?.displayName ?? "当前 Agent"),换 Agent 请新建对话", + otherModelGroups: [], + otherAgentNote: nil, accessChoices: model.accessModes.map { PromptChoice( id: $0.id, @@ -340,11 +237,20 @@ struct ConversationDetailView: View { }, effort: effort, openFiles: { panel = .files }, - send: { - let text = draft + onRefreshCatalog: { Task { await model.refreshCatalog() } }, + send: {}, + sendText: { sentText in userDetachedFromBottom = false + isUserDraggingScroll = false + distanceFromBottom = 0 unreadMessageUpdates = 0 - Task { if await model.send(text) { draft = "" } } + onMessageSent?(sentText) + Task { + let ok = await model.send(sentText) + if !ok { + draft = sentText + } + } }, stop: { Task { await model.cancelTurn() } }, pickModel: { id in @@ -428,18 +334,6 @@ struct ConversationDetailView: View { return choices } - private var otherModelGroups: [PromptGroup] { - model.otherAgentsWithModels.map { agent in - PromptGroup( - title: AgentBrand.displayName(agent.id, hostName: agent.displayName), - agentID: agent.id, - choices: agent.modelOptions.flatMap(\.choices).map { - PromptChoice(id: agent.id + "|" + $0.id, title: $0.label, agentID: agent.id, enabled: false) - } - ) - } - } - private func findModelChoice(_ id: String) -> (ConfigOption, ConfigChoice)? { for option in model.modelOptions { if let choice = option.choices.first(where: { option.key + "|" + $0.id == id }) { @@ -492,13 +386,13 @@ struct ConversationDetailView: View { agentID: model.conversation.agent_id, modelName: model.currentModelLabel, isLast: item.id == model.items.last?.id, - running: model.session.isTurnRunning, + running: model.isThinkingOrRunning, openDiff: { diffChange = $0 } ) .frame(width: contentWidth, alignment: .leading) .id(item.id) } - if model.session.isTurnRunning && model.items.last?.role != .assistant { + if model.isThinkingOrRunning && model.items.last?.role != .assistant { LoadingState(label: "正在思考").id("loading") } Color.clear @@ -926,6 +820,8 @@ private struct PermissionBanner: View { let respond: (PermissionOption?, Bool) -> Void @State private var expandedDiffIDs: Set = [] + @AppStorage("vibex.security.confirmHighRiskApproval") private var confirmHighRiskApproval = true + @State private var pendingHighRiskConfirm: (option: PermissionOption, persist: Bool)? var body: some View { let primaryAllow = prompt.resolveAllowOption(for: .once) @@ -1039,7 +935,11 @@ private struct PermissionBanner: View { HStack(spacing: 0) { Button { UIImpactFeedbackGenerator(style: .medium).impactOccurred() - respond(primaryAllow, false) + if confirmHighRiskApproval { + pendingHighRiskConfirm = (primaryAllow, false) + } else { + respond(primaryAllow, false) + } } label: { HStack(spacing: 5) { if busy { @@ -1065,7 +965,11 @@ private struct PermissionBanner: View { if let opt = prompt.resolveAllowOption(for: scope) { Button { UIImpactFeedbackGenerator(style: .medium).impactOccurred() - respond(opt, scope != .once) + if confirmHighRiskApproval { + pendingHighRiskConfirm = (opt, scope != .once) + } else { + respond(opt, scope != .once) + } } label: { Text(scope.label) } @@ -1120,6 +1024,26 @@ private struct PermissionBanner: View { .shadow(color: .black.opacity(0.05), radius: 8, y: 2) .padding(.horizontal, 12) .padding(.bottom, 8) + .confirmationDialog( + "确认允许执行此操作?", + isPresented: Binding( + get: { pendingHighRiskConfirm != nil }, + set: { if !$0 { pendingHighRiskConfirm = nil } } + ), + titleVisibility: .visible + ) { + if let pending = pendingHighRiskConfirm { + Button("确认\(pending.option.label)", role: .destructive) { + pendingHighRiskConfirm = nil + respond(pending.option, pending.persist) + } + } + Button("取消", role: .cancel) { + pendingHighRiskConfirm = nil + } + } message: { + Text(prompt.command ?? prompt.displayHeading) + } } private func diffPreviewRow(_ diff: PermissionDiffPreview) -> some View { diff --git a/App/ConversationModel.swift b/App/ConversationModel.swift index f5012e1..0ea9ef7 100644 --- a/App/ConversationModel.swift +++ b/App/ConversationModel.swift @@ -2,13 +2,29 @@ import CompanionCore import Foundation import Observation +struct PendingInitialPrompt: Equatable { + let text: String + let workspaceID: String + let agentID: String + let modeID: String? + let modelKey: String? + let modelValue: String? + let effortKey: String? + let effortValue: JSONValue? +} + @MainActor @Observable final class ConversationModel { let client: HostClient let conversation: ConversationListItem - private(set) var items: [TimelineItem] = [] + private var transcriptItems: [TimelineItem] = [] + private var optimisticUserItem: TimelineItem? + private var optimisticBaselineCount = 0 + private var optimisticThinkingUntil: Date = .distantPast + private var pendingInitialPrompt: PendingInitialPrompt? + private var initialPromptDispatched = false private var transcript: TranscriptState private let activity = TaskActivityController.shared private var events: [RemoteEvent] = [] @@ -26,14 +42,42 @@ final class ConversationModel { private(set) var boostPollingUntil: Date = .distantPast var actionError: String? + var items: [TimelineItem] { + guard let opt = optimisticUserItem else { return transcriptItems } + let caughtUp = transcriptItems.count > optimisticBaselineCount + || transcriptItems.suffix(2).contains(where: { $0.role == .user && $0.text == opt.text }) + return caughtUp ? transcriptItems : (transcriptItems + [opt]) + } + + var isThinkingOrRunning: Bool { + session.isTurnRunning || Date() < optimisticThinkingUntil + } + var isActivelyStreaming: Bool { - session.isTurnRunning || Date() < boostPollingUntil + isThinkingOrRunning || Date() < boostPollingUntil } - init(client: HostClient, conversation: ConversationListItem) { + init( + client: HostClient, + conversation: ConversationListItem, + initialPrompt: PendingInitialPrompt? = nil + ) { self.client = client self.conversation = conversation self.transcript = TranscriptState(conversationID: conversation.id) + if let initialPrompt { + self.pendingInitialPrompt = initialPrompt + self.hasLoaded = true + self.optimisticBaselineCount = 0 + self.optimisticUserItem = TimelineItem( + id: "optimistic-\(UUID().uuidString)", + role: .user, + text: initialPrompt.text + ) + self.optimisticThinkingUntil = Date().addingTimeInterval(25) + self.boostPollingUntil = Date().addingTimeInterval(30) + self.session.isTurnRunning = true + } } func reload() async { @@ -63,13 +107,22 @@ final class ConversationModel { switch transcriptResult { case .success(let state): transcript = state - items = state.items + transcriptItems = state.items + if let opt = optimisticUserItem { + let caughtUp = state.items.count > optimisticBaselineCount + || state.items.suffix(2).contains(where: { $0.role == .user && $0.text == opt.text }) + if caughtUp { + optimisticUserItem = nil + } + } hasLoaded = true loadError = nil case .failure(let error) where error is CancellationError: return case .failure(let error): - loadError = describeHostFailure(error) + if optimisticUserItem == nil { + loadError = describeHostFailure(error) + } return } @@ -78,11 +131,20 @@ final class ConversationModel { let fresh = cache.events ?? [] events += fresh lastSequence = max(lastSequence, cache.confirmed_through) - session = SessionStateBuilder.build(from: events) + let built = SessionStateBuilder.build(from: events) + if built.isTurnRunning { + optimisticThinkingUntil = .distantPast + } else if optimisticUserItem == nil, transcriptItems.last?.role == .assistant { + optimisticThinkingUntil = .distantPast + } + session = built + } + applyLiveControls() + if agents.isEmpty { + Task { await refreshCatalog() } } - await applyLiveControls() - if agents.isEmpty { await refreshCatalog() } - let lastAssistant = items.last { $0.role == .assistant } + let currentItems = items + let lastAssistant = currentItems.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 @@ -97,29 +159,29 @@ final class ConversationModel { conversationID: conversation.id, projectName: "VibeX", title: conversation.title ?? "未命名对话", - tasks: items.currentPlan, + tasks: currentItems.currentPlan, latestToolName: latestToolName, stepCount: totalSteps, hasThinking: !(lastAssistant?.thinking.isEmpty ?? true), hasTextOutput: !(lastAssistant?.text.isEmpty ?? true), hasPendingApproval: hasPendingApproval, approvalSummary: approvalSummary, - running: session.isTurnRunning + running: isThinkingOrRunning ) } 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 { + if !isThinkingOrRunning && 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 { + /// Brings the Agent session up (once per visit, non-blocking) so its modes and options exist even before the first message. + private func applyLiveControls() { if !controlsRequested { controlsRequested = true - await ensureLiveControls() + Task { await ensureLiveControls() } } guard let live = liveControls else { return } if session.modes.isEmpty { @@ -203,9 +265,52 @@ final class ConversationModel { return option.currentLabel ?? conversation.model } - /// Other usable Agents with models: shown for reference, a conversation keeps its Agent. - var otherAgentsWithModels: [CatalogAgent] { - agents.filter { $0.usable && $0.id != conversation.agent_id && !$0.modelOptions.isEmpty } + func dispatchInitialPromptIfNeeded() async -> String? { + guard let prompt = pendingInitialPrompt, !initialPromptDispatched else { return nil } + initialPromptDispatched = true + controlsRequested = true + + let hasCustomModel = (prompt.modelValue?.isEmpty == false) && prompt.modelValue != "default" + let hasCustomMode = prompt.modeID?.isEmpty == false + let hasCustomEffort = prompt.effortKey?.isEmpty == false && prompt.effortValue != nil + + do { + if hasCustomMode || hasCustomModel || hasCustomEffort { + liveControls = try? await client.ensureSessionControls(conversationID: conversation.id) + if let modeID = prompt.modeID, !modeID.isEmpty { + try? await client.setSessionMode(conversationID: conversation.id, modeID: modeID) + } + if hasCustomModel, let modelKey = prompt.modelKey, let modelValue = prompt.modelValue { + try? await client.setSessionConfigOption( + conversationID: conversation.id, + key: modelKey, + value: .string(modelValue) + ) + } + if let effortKey = prompt.effortKey, let effortValue = prompt.effortValue { + try? await client.setSessionConfigOption( + conversationID: conversation.id, + key: effortKey, + value: effortValue + ) + } + } + try await client.sendMessage( + conversationID: conversation.id, + workspaceID: prompt.workspaceID, + agentID: prompt.agentID, + text: prompt.text + ) + actionError = nil + Task { await reload() } + return nil + } catch { + optimisticUserItem = nil + optimisticThinkingUntil = .distantPast + session.isTurnRunning = false + actionError = describeHostFailure(error) + return prompt.text + } } func send(_ text: String) async -> Bool { @@ -215,15 +320,33 @@ final class ConversationModel { actionError = "此对话没有绑定 Agent,无法发送" return false } + actionError = nil + hasLoaded = true + optimisticBaselineCount = transcriptItems.count + optimisticUserItem = TimelineItem( + id: "optimistic-\(UUID().uuidString)", + role: .user, + text: trimmed + ) + optimisticThinkingUntil = Date().addingTimeInterval(20) boostPollingUntil = Date().addingTimeInterval(25) session.isTurnRunning = true - return await perform { + + do { try await client.sendMessage( conversationID: conversation.id, workspaceID: conversation.workspace_id, agentID: agentID, text: trimmed ) + Task { await reload() } + return true + } catch { + optimisticUserItem = nil + optimisticThinkingUntil = .distantPast + session.isTurnRunning = false + actionError = describeHostFailure(error) + return false } } @@ -250,6 +373,8 @@ final class ConversationModel { } func cancelTurn() async { + optimisticThinkingUntil = .distantPast + session.isTurnRunning = false _ = await perform { try await client.cancelTurn(conversationID: conversation.id) } } diff --git a/App/ConversationsView.swift b/App/ConversationsView.swift index b9ced65..d01b516 100644 --- a/App/ConversationsView.swift +++ b/App/ConversationsView.swift @@ -1,54 +1,58 @@ import CompanionCore import SwiftUI +import UIKit -private enum SidebarSectionTab: String, CaseIterable, Identifiable { - case conversations = "最近对话" - case files = "项目文件" - var id: String { rawValue } +enum ConversationsRoute: Hashable { + case newThread + case conversation(ConversationListItem) } -private struct StarterSuggestion: Identifiable { - let id: String - let label: String - let prompt: String +private enum SessionListOrganization: String, CaseIterable, Identifiable { + case statusGrouped = "状态分组" + case workspaceGrouped = "工作区视图" + var id: String { rawValue } } -/// Root of the "对话" tab: -/// - Main canvas is calm and focused: either the minimal AI Chat Landing view (`activeConversation == nil`) -/// or the active conversation (`ConversationDetailView`). -/// - Slide-out Sidebar Drawer houses Recent Conversations and Project Files in one dedicated place. +/// Root of the "会话" tab: +/// - Level 1: Session List with global project switcher, `状态分组 / 工作区视图` toggle, +/// expanded active groups (`进行中 / 待检查 / 待开始`), and a collapsible `已完成` shelf (collapsed by default). +/// - Level 2 (`ConversationsRoute.newThread`): Focused `新建会话` screen triggered by the centered `+` button +/// in the Level-1 floating capsule dock, with top-right `[ ⑂ | 📁 ]` capsule, lightweight project/host/branch +/// breadcrumbs above the unified floating capsule composer, and zero bottom tab bar interference. +/// - Level 2 (`ConversationsRoute.conversation`): `ConversationDetailView` with the bottom capsule dock hidden. struct ConversationsView: View { let client: HostClient - var onChromeHiddenChange: ((Bool) -> Void)? = nil - var onLaunchRevealedChange: ((Bool) -> Void)? = nil - var onSelectTab: ((AppTab) -> Void)? = nil + @Binding var selection: AppTab + + @Environment(ServerStore.self) private var servers + @Environment(WorkspaceNavigationStore.self) private var navStore @Environment(CompanionAttentionCenter.self) private var attentionCenter: CompanionAttentionCenter? + @Environment(DesktopConnectFlow.self) private var connectFlow - @State private var list = RemoteList() - @State private var projects: [ProjectSummary]? + @State private var path: [ConversationsRoute] = [] + @State private var projects: [ProjectSummary] = [] + @State private var sessions: [KanbanSessionSummary] = [] + @State private var recentConversations: [ConversationListItem] = [] @State private var agents: [CatalogAgent] = [] - - // Launch logo -> Landing logo morph & radial bloom state - @State private var launchLogoEntered = false - @State private var isLaunchRevealed = false - - // Active conversation shown in the main canvas (`nil` = New Chat Landing view) - @State private var activeConversation: ConversationListItem? - @State private var didSyncInitialDesktopConversation = false - @State private var userRequestedNewChatLanding = false - - // Sidebar state - @State private var isSidebarOpen = false - @State private var sidebarTab: SidebarSectionTab = .conversations - @State private var sidebarSearchQuery = "" - @State private var expandedFileProjectIDs: Set = [] - @State private var projectEntriesByWorkspace: [String: [WorkspaceEntry]] = [:] - @State private var loadingWorkspaceIDs: Set = [] - @State private var removedConversationIDs: Set = [] + @State private var workspacesByProject: [String: [KanbanWorkspaceRecord]] = [:] + @State private var isLoading = true + @State private var loadErrorMessage: String? @State private var actionErrorMessage: String? - // Landing page configuration state - @State private var selectedProjectID: String? + // Level-1 Session List state + @State private var organization: SessionListOrganization = .statusGrouped + @State private var searchQuery = "" + @State private var isCompletedShelfExpanded = false + @State private var removedSessionIDs: Set = [] + @AppStorage("vibex.manuallyCompletedSessionIDs") private var manuallyCompletedRaw = "" + @State private var renamingSession: KanbanSessionSummary? + @State private var renameDraft = "" + @State private var deletingSession: KanbanSessionSummary? + + // Level-2 New Thread configuration state + @State private var newThreadProjectID: String? + @State private var newThreadWorkspaceID: String? + @State private var newThreadDiffCount: Int = 0 @State private var selectedAgentID: String? @State private var selectedModelChoiceID: String? @State private var customModelName: String? @@ -58,184 +62,272 @@ struct ConversationsView: View { @State private var draft = "" @State private var composerMenu: ComposerMenu? @State private var isCreatingAndSending = false - @State private var showProjectPickerSheet = false + @State private var pendingInitialPrompts: [String: PendingInitialPrompt] = [:] + + // Shared Workspace Sheets (`项目文件` & `代码差异` & `项目选择`) + @State private var showNewThreadProjectSheet = false @State private var activeFileBrowserWorkspace: WorkspaceSheetTarget? @State private var activeDiffWorkspace: WorkspaceSheetTarget? - @State private var previewFileTarget: FilePreviewSheetTarget? - - private let suggestions: [StarterSuggestion] = [ - StarterSuggestion( - id: "arch", - label: "梳理项目架构", - prompt: "梳理当前项目的整体架构、目录结构与核心模块职责" - ), - StarterSuggestion( - id: "bug", - label: "排查近期改动", - prompt: "检查当前工作区最近的代码改动,排查潜在问题并给出修复方案" - ), - StarterSuggestion( - id: "test", - label: "补充单元测试", - prompt: "为当前工作区最近修改的核心逻辑补充单元测试并运行验证" - ), - ] - - private var isConnected: Bool { - list.errorMessage == nil && list.items != nil + + private var selectedFilterProject: ProjectSummary? { + guard let pid = navStore.selectedProjectID else { return nil } + return projects.first { $0.id.lowercased() == pid.lowercased() } } - private var shouldHideBottomChrome: Bool { - isSidebarOpen || activeConversation != nil || composerMenu != nil + // Merge KanbanSessionSummary with any recent conversations so no session is ever missed + private var mergedSessions: [KanbanSessionSummary] { + var byID: [String: KanbanSessionSummary] = [:] + for s in sessions where !s.isArchived && !removedSessionIDs.contains(s.id) { + byID[s.id] = s + } + for c in recentConversations where !removedSessionIDs.contains(c.id) { + if byID[c.id] == nil { + let converted = KanbanSessionSummary(fromConversation: c) + if !converted.isArchived { + byID[c.id] = converted + } + } + } + let allowedWorkspaces: Set? = { + guard let proj = selectedFilterProject else { return nil } + return Set(proj.workspaceIds) + }() + let filtered = byID.values.filter { item in + if let allowedWorkspaces, !allowedWorkspaces.contains(item.workspaceId) { + return false + } + let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !q.isEmpty else { return true } + let titleMatch = item.resolvedTitle.lowercased().contains(q) + let branchMatch = item.workspaceDisplayLabel.lowercased().contains(q) + let agentMatch = item.agentDisplayName.lowercased().contains(q) + let modelMatch = (item.model ?? "").lowercased().contains(q) + let projMatch = (projectName(forWorkspace: item.workspaceId) ?? "").lowercased().contains(q) + return titleMatch || branchMatch || agentMatch || modelMatch || projMatch + } + return filtered.sorted { lhs, rhs in + if lhs.isPinned != rhs.isPinned { + return lhs.isPinned && !rhs.isPinned + } + return (lhs.updatedDate ?? .distantPast) > (rhs.updatedDate ?? .distantPast) + } } - private var visibleConversations: [ConversationListItem] { - (list.items ?? []).filter { !removedConversationIDs.contains($0.id) } + private func projectName(forWorkspace workspaceID: String) -> String? { + projects.first { $0.workspaceIds.contains(workspaceID) }?.displayName } - private var groups: [ProjectGroup] { - ProjectGroup.make(conversations: visibleConversations, projects: projects ?? []) + private var manuallyCompletedIDs: Set { + Set( + manuallyCompletedRaw + .split(separator: "|") + .map { String($0).trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + ) + } + + private func setManuallyCompleted(_ id: String, completed: Bool) { + var next = manuallyCompletedIDs + if completed { + next.insert(id) + } else { + next.remove(id) + } + // Cap stored set to avoid unbounded growth + let trimmed = Array(next.sorted().suffix(200)) + manuallyCompletedRaw = trimmed.joined(separator: "|") } - private var currentGroup: ProjectGroup? { - if let id = selectedProjectID, let match = groups.first(where: { $0.id == id }) { + /// In VibeX's backend state machine (`workbench_status.rs`), `status == .done` means + /// "latest finished turn has been viewed", NOT "conversation archived/finished forever". + /// Keep conversations active within the last 24h visible in `近期对话` unless the user + /// explicitly marked them `已完成`. + private func isRecentlyActiveReadSession(_ session: KanbanSessionSummary) -> Bool { + guard session.status == .done, !session.isRunning else { return false } + guard !manuallyCompletedIDs.contains(session.id) else { return false } + guard let date = session.updatedDate else { return false } + return Date().timeIntervalSince(date) <= 24 * 3600 + } + + // MARK: - New Thread Resolved Project / Workspace / Agent + + private var effectiveNewThreadProject: ProjectSummary? { + if let pid = newThreadProjectID ?? navStore.selectedProjectID, + let match = projects.first(where: { $0.id.lowercased() == pid.lowercased() }) + { return match } - if let gitGroup = groups.first(where: { !$0.isHome && $0.id != "other" && $0.isGit }) { - return gitGroup + if let gitProj = projects.first(where: { !$0.isHome && $0.isGit }) { + return gitProj } - if let nonHome = groups.first(where: { !$0.isHome && $0.id != "other" }) { + if let nonHome = projects.first(where: { !$0.isHome }) { return nonHome } - return groups.first + return projects.first } - private var currentWorkspaceID: String? { - guard let group = currentGroup else { - return visibleConversations.first?.workspace_id + private var newThreadWorkspaces: [KanbanWorkspaceRecord] { + guard let proj = effectiveNewThreadProject else { return [] } + return (workspacesByProject[proj.id] ?? []).filter { !$0.archived } + } + + private var effectiveNewThreadWorkspaceRecord: KanbanWorkspaceRecord? { + let list = newThreadWorkspaces + if let wid = newThreadWorkspaceID, let match = list.first(where: { $0.id == wid }) { + return match } - return workspaceID(for: group) + return list.first } - private func workspaceID(for group: ProjectGroup) -> String? { - group.conversations.first?.workspace_id - ?? group.workspaceIds.first - ?? projects?.first(where: { $0.id == group.id })?.workspaceIds.first + private var effectiveNewThreadWorkspaceID: String? { + if let rec = effectiveNewThreadWorkspaceRecord { + return rec.id + } + if let wid = newThreadWorkspaceID, + let proj = effectiveNewThreadProject, + proj.workspaceIds.contains(wid) + { + return wid + } + return effectiveNewThreadProject?.workspaceIds.first + ?? recentConversations.first?.workspace_id + } + + private var effectiveNewThreadBranchLabel: String { + if let rec = effectiveNewThreadWorkspaceRecord { + return rec.displayLabel + } + if effectiveNewThreadProject?.isGit == true { + return "main" + } + return "默认目录" } private var usableAgents: [CatalogAgent] { - let usable = agents.filter(\.usable) - return usable.isEmpty ? agents : usable + agents.filter(\.usable) } private var currentAgent: CatalogAgent? { if let id = selectedAgentID, let match = usableAgents.first(where: { $0.id == id }) { return match } - if let recentAgentID = currentGroup?.conversations.first?.agent_id ?? visibleConversations.first?.agent_id, - let match = usableAgents.first(where: { $0.id == recentAgentID }) { + if let recentAgentID = mergedSessions.first?.effectiveAgentKey ?? recentConversations.first?.agent_id, + let match = usableAgents.first(where: { $0.id == recentAgentID }) + { return match } return usableAgents.first } + // MARK: - Body + var body: some View { - ZStack(alignment: .leading) { - Group { - if let activeConversation { - NavigationStack { + NavigationStack(path: $path) { + sessionListRootView + .navigationTitle("会话") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarLeading) { + projectSelectorMenu + } + ToolbarItem(placement: .principal) { + Text("会话") + .font(.headline.weight(.semibold)) + } + } + .navigationDestination(for: ConversationsRoute.self) { route in + switch route { + case .newThread: + newThreadScreen + case .conversation(let item): ConversationDetailView( client: client, - conversation: activeConversation, - onToggleSidebar: { - withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { - isSidebarOpen.toggle() + conversation: item, + initialPrompt: pendingInitialPrompts[item.id], + onBack: { + pendingInitialPrompts.removeValue(forKey: item.id) + if !path.isEmpty { + path.removeLast() } }, - onReturnToLanding: { - withAnimation(.smooth(duration: 0.2)) { - self.userRequestedNewChatLanding = true - self.activeConversation = nil - } + onMessageSent: { sentText in + markLocalSessionRunning(conversation: item, promptText: sentText) + }, + onTurnFinishedWhileViewing: { + markLocalSessionViewedNow(sessionID: item.id) } ) - .id(activeConversation.id) + .id(item.id) } - } else { - landingWorkspaceView } + } + .onChange(of: path.count, initial: true) { oldCount, count in + navStore.conversationsDepth = count + if count == 0 && oldCount > 0 { + Task { await reload() } } - .disabled(isSidebarOpen) - - if isSidebarOpen { - Color.black.opacity(0.36) - .ignoresSafeArea() - .onTapGesture { - withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { - isSidebarOpen = false - dismissKeyboard() - } - } - .transition(.opacity) - .zIndex(1) - - sidebarDrawer - .transition(.move(edge: .leading)) - .zIndex(2) + } + .onChange(of: navStore.newThreadTrigger) { _, _ in + newThreadProjectID = navStore.selectedProjectID ?? effectiveNewThreadProject?.id + newThreadWorkspaceID = nil + actionErrorMessage = nil + if path.last != .newThread { + path = [.newThread] + } + if let proj = effectiveNewThreadProject { + Task { await loadWorkspacesAndDiffForNewThread(projectID: proj.id) } } } - .gesture( - DragGesture(minimumDistance: 24, coordinateSpace: .local) - .onEnded { value in - if !isSidebarOpen && value.startLocation.x < 32 && value.translation.width > 64 { - dismissKeyboard() - withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { - isSidebarOpen = true - } - } else if isSidebarOpen && value.translation.width < -60 { - withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { - isSidebarOpen = false - } - } - } - ) .sheet(item: $activeFileBrowserWorkspace) { target in FileBrowserView(client: client, workspaceID: target.workspaceID) } .sheet(item: $activeDiffWorkspace) { target in DiffListView(client: client, workspaceID: target.workspaceID) } - .sheet(item: $previewFileTarget) { target in - NavigationStack { - FileContentView(client: client, workspaceID: target.workspaceID, path: target.path) - .toolbar { - ToolbarItem(placement: .confirmationAction) { - Button("完成") { previewFileTarget = nil } - } - } - } - } - .sheet(isPresented: $showProjectPickerSheet) { - projectPickerSheet - .presentationDetents([.medium]) + .sheet(isPresented: $showNewThreadProjectSheet) { + newThreadProjectPickerSheet + .presentationDetents([.medium, .large]) .presentationDragIndicator(.visible) } - .onAppear { - consumePendingNavigationIfNeeded() - onChromeHiddenChange?(shouldHideBottomChrome) - if !launchLogoEntered { - withAnimation(.easeOut(duration: 0.36)) { - launchLogoEntered = true + .alert( + "重命名会话", + isPresented: Binding( + get: { renamingSession != nil }, + set: { if !$0 { renamingSession = nil } } + ) + ) { + TextField("会话名称", text: $renameDraft) + Button("取消", role: .cancel) { renamingSession = nil } + Button("保存") { + if let target = renamingSession { + performRename(target, newName: renameDraft) } + renamingSession = nil } } - .onChange(of: shouldHideBottomChrome) { _, hidden in - onChromeHiddenChange?(hidden) + .alert( + "删除会话", + isPresented: Binding( + get: { deletingSession != nil }, + set: { if !$0 { deletingSession = nil } } + ), + presenting: deletingSession + ) { target in + Button("取消", role: .cancel) { deletingSession = nil } + Button("删除", role: .destructive) { + performDelete(target) + deletingSession = nil + } + } message: { target in + Text("确定删除会话“\(target.resolvedTitle)”吗?") + } + .onAppear { + consumePendingNavigationIfNeeded() } .onChange(of: actionErrorMessage) { _, msg in guard msg != nil else { return } Task { @MainActor in - try? await Task.sleep(for: .milliseconds(3200)) + try? await Task.sleep(for: .milliseconds(3400)) if !Task.isCancelled { withAnimation(.easeOut(duration: 0.2)) { actionErrorMessage = nil @@ -246,635 +338,813 @@ struct ConversationsView: View { .onChange(of: attentionCenter?.pendingNavigationConversation) { _, _ in consumePendingNavigationIfNeeded() } - .onChange(of: attentionCenter?.latestConversations) { _, updated in - guard let updated, !updated.isEmpty else { return } - syncWithFetchedConversations(updated) - } .onChange(of: attentionCenter?.latestNewlyCreatedConversation) { _, newConv in - guard let newConv else { return } + guard newConv != nil else { return } Task { await reload() } - if activeConversation == nil && draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - userRequestedNewChatLanding = false - withAnimation(.smooth(duration: 0.22)) { - activeConversation = newConv - } - } - } - .task { - guard !isLaunchRevealed else { return } - try? await Task.sleep(for: .milliseconds(620)) - guard !Task.isCancelled else { return } - withAnimation(.spring(response: 1.08, dampingFraction: 0.86, blendDuration: 0.2)) { - isLaunchRevealed = true - } - onLaunchRevealedChange?(true) } .task { while !Task.isCancelled { await reload() - try? await Task.sleep(for: .seconds(list.errorMessage == nil ? 25 : 4)) + let hasRunning = sessions.contains { $0.isRunning || $0.status == .inprogress } + let delaySeconds: Int = if loadErrorMessage != nil { + 4 + } else if hasRunning && path.isEmpty { + 3 + } else { + 12 + } + try? await Task.sleep(for: .seconds(delaySeconds)) } } } - // MARK: - Minimal, Focused AI Chat Landing View + // MARK: - Level-1 Top Bar Controls - private var landingWorkspaceView: some View { - VStack(spacing: 0) { - landingTopBar - .opacity(isLaunchRevealed ? 1 : 0) - .scaleEffect(isLaunchRevealed ? 1 : 0.82) - .offset(y: isLaunchRevealed ? 0 : 145) - .blur(radius: isLaunchRevealed ? 0 : 5) - - Spacer(minLength: 24) - - // Single focal point: Persistent Logo (morphs from center launch logo -> landing logo) - // + Greeting + Quiet Project Pill radiating outward from the logo - VStack(spacing: 16) { - Image("vibex_logo") - .resizable() - .interpolation(.high) - .scaledToFit() - .frame(width: 54, height: 54) - .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous)) - .shadow( - color: .black.opacity(isLaunchRevealed ? 0.08 : 0.14), - radius: isLaunchRevealed ? 10 : 18, - x: 0, - y: isLaunchRevealed ? 4 : 8 - ) - .scaleEffect(isLaunchRevealed ? 1.0 : (launchLogoEntered ? 1.52 : 1.28)) - .offset(y: isLaunchRevealed ? 0 : 42) - .zIndex(2) - - VStack(spacing: 14) { - Text("有什么可以帮你?") - .font(.system(size: 22, weight: .bold)) - .foregroundStyle(.primary) - - if let group = currentGroup { - projectContextPill(group: group) - } else if let errorMessage = list.errorMessage { - LoadFailureView(message: errorMessage) { - Task { await reload() } - } - .padding(.horizontal, 24) - } - - if let actionErrorMessage { - Text(actionErrorMessage) - .font(.footnote) - .foregroundStyle(.red) - .multilineTextAlignment(.center) - .padding(.horizontal, 24) + private var projectSelectorMenu: some View { + Menu { + Button { + navStore.selectedProjectID = nil + Task { await reload() } + } label: { + HStack { + Label("全部项目", systemImage: "square.stack.3d.up") + if navStore.selectedProjectID == nil { + Image(systemName: "checkmark") } } - .opacity(isLaunchRevealed ? 1 : 0) - .scaleEffect(isLaunchRevealed ? 1 : 0.78) - .offset(y: isLaunchRevealed ? 0 : -36) - .blur(radius: isLaunchRevealed ? 0 : 5) } - .frame(maxWidth: .infinity) - .contentShape(Rectangle()) - .onTapGesture { - if composerMenu != nil { - composerMenu = nil + + if !projects.isEmpty { + Divider() + ForEach(projects) { project in + Button { + navStore.selectedProjectID = project.id + Task { await reload() } + } label: { + HStack { + Label( + project.displayName, + systemImage: project.isHome ? "house" : (project.isGit ? "arrow.triangle.branch" : "folder") + ) + if navStore.selectedProjectID?.lowercased() == project.id.lowercased() { + Image(systemName: "checkmark") + } + } + } } - dismissKeyboard() } - - Spacer(minLength: 24) - - // Quiet starter chips: only shown when input is empty and menu is closed - if draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && composerMenu == nil { - starterChipsStrip - .padding(.bottom, 10) - .opacity(isLaunchRevealed ? 1 : 0) - .scaleEffect(isLaunchRevealed ? 1 : 0.82) - .offset(y: isLaunchRevealed ? 0 : -150) - .blur(radius: isLaunchRevealed ? 0 : 5) - .transition(.opacity.combined(with: .move(edge: .bottom))) + } label: { + HStack(spacing: 5) { + Image( + systemName: selectedFilterProject == nil + ? "square.stack.3d.up.fill" + : (selectedFilterProject?.isGit == true ? "arrow.triangle.branch" : "folder.fill") + ) + .font(.caption.weight(.semibold)) + Text(selectedFilterProject?.displayName ?? "全部项目") + .font(.subheadline.weight(.semibold)) + .lineLimit(1) + Image(systemName: "chevron.down") + .font(.caption2.weight(.semibold)) + .foregroundStyle(.secondary) } - - landingPromptBar - .opacity(isLaunchRevealed ? 1 : 0) - .scaleEffect(isLaunchRevealed ? 1 : 0.85) - .offset(y: isLaunchRevealed ? 0 : -195) - .blur(radius: isLaunchRevealed ? 0 : 6) + .foregroundStyle(.primary) } - .allowsHitTesting(isLaunchRevealed) - .background(Color(.systemGroupedBackground).ignoresSafeArea()) - .animation(.smooth(duration: 0.18), value: draft.isEmpty) } - private var landingTopBar: some View { - HStack { - Button { - dismissKeyboard() - withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { - isSidebarOpen.toggle() + // MARK: - Level-1 Session List Root View + + private var sessionListRootView: some View { + VStack(spacing: 0) { + if let actionErrorMessage, path.isEmpty { + HStack(spacing: 8) { + Image(systemName: "exclamationmark.circle.fill") + .foregroundStyle(.red) + .font(.footnote) + Text(actionErrorMessage) + .font(.caption) + .foregroundStyle(.red) + .lineLimit(2) + Spacer() } - } label: { - Image(systemName: "sidebar.left") - .font(.system(size: 16.5, weight: .medium)) - .foregroundStyle(.primary) - .frame(width: 36, height: 36) - .background( + .padding(.horizontal, 16) + .padding(.vertical, 8) + .background(Color(.secondarySystemGroupedBackground)) + } else if loadErrorMessage != nil, (!sessions.isEmpty || !recentConversations.isEmpty) { + Button { + connectFlow.presentPicker(servers: servers) + } label: { + HStack(spacing: 7) { Circle() - .fill(Color(.secondarySystemGroupedBackground)) - ) + .fill(Color.orange) + .frame(width: 6.5, height: 6.5) + Text("连接已断开,点击重连或切换电脑") + .font(.caption.weight(.medium)) + .foregroundStyle(.secondary) + Spacer() + Image(systemName: "chevron.right") + .font(.caption2.weight(.semibold)) + .foregroundStyle(.tertiary) + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + .background(Color(.secondarySystemGroupedBackground)) + } + .buttonStyle(.plain) } - .buttonStyle(.plain) - .accessibilityLabel("打开侧边栏") - Spacer() - - HStack(spacing: 5) { - Circle() - .fill(isConnected ? Color.green : Color.orange) - .frame(width: 6, height: 6) - Text(isConnected ? "已连接" : "连接中") - .font(.system(size: 12, weight: .medium)) + if isLoading && sessions.isEmpty && recentConversations.isEmpty { + Spacer() + ProgressView("正在同步会话…") + .font(.subheadline) .foregroundStyle(.secondary) + Spacer() + } else if let loadErrorMessage, sessions.isEmpty && recentConversations.isEmpty { + Spacer() + LoadFailureView(message: loadErrorMessage) { + Task { await reload() } + } + Spacer() + } else { + ScrollView { + VStack(alignment: .leading, spacing: 14) { + searchAndModeHeader + + switch organization { + case .statusGrouped: + statusGroupedContent + case .workspaceGrouped: + workspaceGroupedContent + } + } + .padding(.horizontal, 16) + .padding(.top, 8) + .padding(.bottom, WorkspaceNavigationStore.bottomDockClearance + 14) + } + .scrollDismissesKeyboard(.interactively) + .refreshable { + await reload() + } } - - Spacer() - - // Symmetric spacer to keep the status centered without adding extra buttons - Color.clear - .frame(width: 36, height: 36) } - .padding(.horizontal, 14) - .padding(.top, 6) - .padding(.bottom, 4) + .background(Color(.systemGroupedBackground).ignoresSafeArea()) } - private func projectContextPill(group: ProjectGroup) -> some View { - Button { - showProjectPickerSheet = true - } label: { - HStack(spacing: 7) { - Image(systemName: group.isHome ? "house" : "folder") - .font(.system(size: 12.5, weight: .medium)) - .foregroundStyle(.secondary) - - Text(group.name) - .font(.system(size: 13.5, weight: .medium)) - .foregroundStyle(.primary) - .lineLimit(1) + private var searchAndModeHeader: some View { + VStack(spacing: 10) { + UnifiedSearchBar( + query: $searchQuery, + placeholder: "搜索会话、分支或模型…" + ) - if group.isGit { - Text("·") - .foregroundStyle(.tertiary) - HStack(spacing: 2.5) { - Image(systemName: "arrow.triangle.branch") - .font(.system(size: 10, weight: .medium)) - Text("main") - .font(.system(size: 12.5)) + HStack { + Picker("视图模式", selection: $organization) { + ForEach(SessionListOrganization.allCases) { mode in + Text(mode.rawValue).tag(mode) } - .foregroundStyle(.secondary) } + .pickerStyle(.segmented) - Image(systemName: "chevron.up.chevron.down") - .font(.system(size: 10, weight: .semibold)) - .foregroundStyle(.tertiary) - .padding(.leading, 2) + Spacer(minLength: 10) + + Text("\(mergedSessions.count) 个会话") + .font(.system(size: 12, weight: .medium)) + .monospacedDigit() + .foregroundStyle(.secondary) } - .padding(.horizontal, 14) - .padding(.vertical, 8) - .background( - Capsule(style: .continuous) - .fill(Color(.secondarySystemGroupedBackground)) - ) - .overlay( - Capsule(style: .continuous) - .strokeBorder(Color.primary.opacity(0.07), lineWidth: 0.6) - ) } - .buttonStyle(.plain) } - private var starterChipsStrip: some View { - ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 8) { - ForEach(suggestions) { item in - Button { - withAnimation(.smooth(duration: 0.16)) { - draft = item.prompt - } - } label: { - Text(item.label) - .font(.system(size: 13, weight: .medium)) - .foregroundStyle(.secondary) - .padding(.horizontal, 13) - .padding(.vertical, 7.5) - .background( - Capsule(style: .continuous) - .fill(Color(.secondarySystemGroupedBackground)) - ) - .overlay( - Capsule(style: .continuous) - .strokeBorder(Color.primary.opacity(0.06), lineWidth: 0.6) - ) - } - .buttonStyle(.plain) + // MARK: - Mode 1: Status Grouped (`状态分组` + Collapsible `已完成` Shelf) + + @ViewBuilder + private var statusGroupedContent: some View { + let all = mergedSessions + let runningList = all.filter { $0.status == .inprogress || ($0.isRunning && $0.status != .inreview) } + let reviewList = all.filter { $0.status == .inreview && !runningList.contains($0) } + let recentReadList = all.filter { isRecentlyActiveReadSession($0) } + let todoList = all.filter { $0.status == .todo && !$0.isRunning } + let doneList = all.filter { $0.status == .done && !$0.isRunning && !isRecentlyActiveReadSession($0) } + let hasActive = !runningList.isEmpty || !reviewList.isEmpty || !recentReadList.isEmpty || !todoList.isEmpty + let isSearching = !searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + + if all.isEmpty { + emptySessionsCard + } else { + if !hasActive && !isSearching { + HStack(spacing: 10) { + Image(systemName: "checkmark.circle.fill") + .font(.system(size: 16)) + .foregroundStyle(.green) + Text("当前没有进行中或近期对话,点底部 + 新建会话") + .font(.system(size: 13)) + .foregroundStyle(.secondary) + Spacer(minLength: 0) } + .padding(.horizontal, 14) + .padding(.vertical, 12) + .background( + RoundedRectangle(cornerRadius: 14, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + } + + if !runningList.isEmpty { + sessionSectionBlock( + title: "进行中", + tint: .orange, + icon: "bolt.horizontal.circle.fill", + items: runningList + ) + } + + if !reviewList.isEmpty { + sessionSectionBlock( + title: "待检查", + tint: .purple, + icon: "eye.circle.fill", + items: reviewList + ) + } + + if !recentReadList.isEmpty { + sessionSectionBlock( + title: "近期对话", + tint: .teal, + icon: "bubble.left.and.bubble.right.fill", + items: recentReadList + ) + } + + if !todoList.isEmpty { + sessionSectionBlock( + title: "待开始", + tint: .blue, + icon: "circle.dotted", + items: todoList + ) + } + + if !doneList.isEmpty { + completedShelfView(items: doneList, forceExpanded: isSearching) } - .padding(.horizontal, 14) } - .fixedSize(horizontal: false, vertical: true) } - // MARK: - Slide-Out Sidebar Drawer (Recent Conversations + Project Files) - - private var sidebarDrawer: some View { - VStack(alignment: .leading, spacing: 0) { - // Sidebar top bar: segmented switcher + New Chat button - HStack(spacing: 8) { - HStack(spacing: 3) { - ForEach(SidebarSectionTab.allCases) { tab in - let selected = sidebarTab == tab - Button { - withAnimation(.smooth(duration: 0.18)) { - sidebarTab = tab - } - } label: { - Text(tab.rawValue) - .font(.system(size: 13, weight: selected ? .semibold : .medium)) - .padding(.horizontal, 12) - .padding(.vertical, 6) - .background( - Capsule(style: .continuous) - .fill(selected ? Color(.systemBackground) : Color.clear) - .shadow(color: .black.opacity(selected ? 0.06 : 0), radius: 2, x: 0, y: 1) - ) - .foregroundStyle(selected ? .primary : .secondary) - } - .buttonStyle(.plain) - } + private func completedShelfView(items: [KanbanSessionSummary], forceExpanded: Bool) -> some View { + let expanded = forceExpanded || isCompletedShelfExpanded + return VStack(alignment: .leading, spacing: 8) { + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { + isCompletedShelfExpanded.toggle() + } + } label: { + HStack(spacing: 8) { + Image(systemName: expanded ? "chevron.down" : "chevron.right") + .font(.system(size: 11.5, weight: .bold)) + .foregroundStyle(.secondary) + .frame(width: 14) + + Image(systemName: "checkmark.seal.fill") + .font(.system(size: 13.5)) + .foregroundStyle(.green.opacity(0.85)) + + Text("已完成历史会话") + .font(.system(size: 13.5, weight: .semibold)) + .foregroundStyle(.secondary) + + Spacer() + + Text("\(items.count)") + .font(.system(size: 12, weight: .semibold)) + .monospacedDigit() + .foregroundStyle(.secondary) + .padding(.horizontal, 8) + .padding(.vertical, 2.5) + .background(Capsule().fill(Color(.tertiarySystemFill))) } - .padding(3) + .padding(.horizontal, 14) + .padding(.vertical, 11) .background( - Capsule(style: .continuous) - .fill(Color(.tertiarySystemFill)) + RoundedRectangle(cornerRadius: 14, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) ) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) - Spacer() - - Button { - withAnimation(.spring(response: 0.26, dampingFraction: 0.86)) { - userRequestedNewChatLanding = true - activeConversation = nil - isSidebarOpen = false - } - } label: { - Image(systemName: "square.and.pencil") - .font(.system(size: 15, weight: .semibold)) - .foregroundStyle(.primary) - .frame(width: 32, height: 32) - .background( - Circle() - .fill(Color(.tertiarySystemFill)) - ) - } - .buttonStyle(.plain) - .accessibilityLabel("新对话") + if expanded { + sessionCardGroup(items: items) + .transition(.opacity.combined(with: .move(edge: .top))) } - .padding(.horizontal, 14) - .padding(.top, 12) - .padding(.bottom, 10) + } + } - // Search box - HStack(spacing: 7) { - Image(systemName: "magnifyingglass") - .font(.system(size: 12.5, weight: .medium)) - .foregroundStyle(.secondary) - TextField( - sidebarTab == .conversations ? "搜索对话…" : "搜索项目…", - text: $sidebarSearchQuery - ) - .font(.system(size: 13.5)) - .textFieldStyle(.plain) - if !sidebarSearchQuery.isEmpty { - Button { - sidebarSearchQuery = "" - } label: { - Image(systemName: "xmark.circle.fill") - .font(.system(size: 13)) - .foregroundStyle(.tertiary) - } - .buttonStyle(.plain) - } + // MARK: - Mode 2: Workspace Grouped (`工作区视图`) + + @ViewBuilder + private var workspaceGroupedContent: some View { + let all = mergedSessions + if all.isEmpty { + emptySessionsCard + } else { + let grouped = Dictionary(grouping: all) { item -> String in + let proj = projectName(forWorkspace: item.workspaceId) ?? "其他项目" + let branch = item.workspaceDisplayLabel + return branch.isEmpty ? proj : "\(proj) · \(branch)" } - .padding(.horizontal, 10) - .padding(.vertical, 7.5) - .background( - RoundedRectangle(cornerRadius: 10, style: .continuous) - .fill(Color(.tertiarySystemFill)) - ) - .padding(.horizontal, 14) - .padding(.bottom, 10) - - Divider().opacity(0.45) - - ScrollView { - switch sidebarTab { - case .conversations: - sidebarConversationsContent - .padding(.vertical, 10) - case .files: - sidebarFilesContent - .padding(.vertical, 10) - } + let sortedKeys = grouped.keys.sorted { lhs, rhs in + let lDate = grouped[lhs]?.first?.updatedDate ?? .distantPast + let rDate = grouped[rhs]?.first?.updatedDate ?? .distantPast + return lDate > rDate } - .refreshable { - await reload() + + ForEach(sortedKeys, id: \.self) { headerKey in + if let items = grouped[headerKey], !items.isEmpty { + sessionSectionBlock( + title: headerKey, + tint: .secondary, + icon: "arrow.triangle.branch", + items: items + ) + } } } - .frame(width: 304) - .frame(maxHeight: .infinity) + } + + private var emptySessionsCard: some View { + VStack(spacing: 12) { + Image(systemName: "bubble.left.and.bubble.right") + .font(.system(size: 32)) + .foregroundStyle(.tertiary) + + Text(searchQuery.isEmpty ? "暂无会话记录" : "没有找到匹配的会话") + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(.primary) + + Text(searchQuery.isEmpty ? "点击底部胶囊栏中间的 + 发起新会话" : "请尝试更换搜索关键词或切换项目筛选") + .font(.system(size: 13)) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 42) + .padding(.horizontal, 20) .background( - Color(.secondarySystemGroupedBackground) - .ignoresSafeArea() + RoundedRectangle(cornerRadius: 16, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) ) - .overlay(alignment: .trailing) { - Rectangle() - .fill(Color.primary.opacity(0.07)) - .frame(width: 0.5) - .ignoresSafeArea() - } - .shadow(color: .black.opacity(0.18), radius: 18, x: 5, y: 0) } - private func sidebarQuickNavButton( + private func sessionSectionBlock( title: String, + tint: Color, icon: String, - action: @escaping () -> Void + items: [KanbanSessionSummary] ) -> some View { - Button(action: action) { - VStack(spacing: 4) { + VStack(alignment: .leading, spacing: 7) { + HStack(spacing: 6) { Image(systemName: icon) - .font(.system(size: 14.5, weight: .medium)) - .frame(height: 18) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(tint) Text(title) - .font(.system(size: 10.5, weight: .medium)) + .font(.system(size: 12.5, weight: .semibold)) + .foregroundStyle(.secondary) .lineLimit(1) + Text("\(items.count)") + .font(.system(size: 11.5, weight: .medium)) + .monospacedDigit() + .foregroundStyle(.tertiary) + Spacer() } - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity) - .padding(.vertical, 6) - .background( - RoundedRectangle(cornerRadius: 8, style: .continuous) - .fill(Color(.tertiarySystemFill).opacity(0.65)) - ) - .contentShape(Rectangle()) + .padding(.horizontal, 4) + + sessionCardGroup(items: items) } - .buttonStyle(.plain) } - // MARK: Sidebar Tab 1: 最近对话 + private func sessionCardGroup(items: [KanbanSessionSummary]) -> some View { + VStack(spacing: 0) { + ForEach(Array(items.enumerated()), id: \.element.id) { idx, session in + sessionRowButton(session) + if idx < items.count - 1 { + Divider() + .padding(.leading, 48) + } + } + } + .background( + RoundedRectangle(cornerRadius: 16, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + } - private var sidebarConversationsContent: some View { - let q = sidebarSearchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - let nonEmptyGroups = groups.filter { !$0.conversations.isEmpty } + private func sessionRowButton(_ session: KanbanSessionSummary) -> some View { + let projLabel = projectName(forWorkspace: session.workspaceId) + let branchLabel = session.workspaceDisplayLabel + return Button { + openSession(session) + } label: { + HStack(alignment: .center, spacing: 11) { + ZStack(alignment: .bottomTrailing) { + AgentIconView(agent: session.effectiveAgentKey, size: 20) + .frame(width: 32, height: 32) + .background( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(Color(.tertiarySystemFill)) + ) - return VStack(alignment: .leading, spacing: 14) { - if nonEmptyGroups.isEmpty { - Text("暂无对话记录") - .font(.system(size: 13)) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity) - .padding(.vertical, 32) - } else { - ForEach(nonEmptyGroups) { group in - let filteredConvs = group.conversations.filter { item in - guard !q.isEmpty else { return true } - let title = (item.title ?? "未命名对话").lowercased() - let model = (item.model ?? "").lowercased() - return title.contains(q) || model.contains(q) || group.name.lowercased().contains(q) + if session.isRunning || session.status == .inprogress { + Circle() + .fill(Color.orange) + .frame(width: 8, height: 8) + .overlay(Circle().stroke(Color(.secondarySystemGroupedBackground), lineWidth: 1.5)) + .offset(x: 2, y: 2) + } else if session.status == .inreview { + Circle() + .fill(Color.purple) + .frame(width: 8, height: 8) + .overlay(Circle().stroke(Color(.secondarySystemGroupedBackground), lineWidth: 1.5)) + .offset(x: 2, y: 2) } + } - if !filteredConvs.isEmpty { - VStack(alignment: .leading, spacing: 4) { - Text(group.name) - .font(.system(size: 11.5, weight: .semibold)) - .foregroundStyle(.secondary) - .padding(.horizontal, 16) + VStack(alignment: .leading, spacing: 3.5) { + HStack(spacing: 5) { + if session.isPinned { + Image(systemName: "pin.fill") + .font(.system(size: 10)) + .foregroundStyle(.orange) + } + Text(session.resolvedTitle) + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.primary) + .lineLimit(1) + } - VStack(spacing: 2) { - ForEach(filteredConvs) { item in - sidebarConversationRow(item) - } + HStack(spacing: 6) { + if let projLabel, navStore.selectedProjectID == nil { + Text(projLabel) + .lineLimit(1) + } + if !branchLabel.isEmpty { + HStack(spacing: 2) { + Image(systemName: "arrow.triangle.branch") + .font(.system(size: 9.5)) + Text(branchLabel) + .lineLimit(1) } - .padding(.horizontal, 8) + } + if let model = session.model, !model.isEmpty { + Text("· \(model)") + .lineLimit(1) } } + .font(.system(size: 12)) + .foregroundStyle(.secondary) } - } - } - } - - private func sidebarConversationRow(_ item: ConversationListItem) -> some View { - let isCurrent = activeConversation?.id == item.id - return Button { - withAnimation(.spring(response: 0.26, dampingFraction: 0.86)) { - userRequestedNewChatLanding = false - activeConversation = item - isSidebarOpen = false - } - } label: { - HStack(alignment: .center, spacing: 9) { - AgentIconView(agent: item.agent_id, size: 14) - .frame(width: 24, height: 24) - Text(item.title ?? "未命名对话") - .font(.system(size: 13.5, weight: isCurrent ? .semibold : .regular)) - .foregroundStyle(isCurrent ? Color.accentColor : Color.primary) - .lineLimit(1) + Spacer(minLength: 6) - Spacer(minLength: 4) + VStack(alignment: .trailing, spacing: 4) { + if let date = session.updatedDate { + Text(relativeChinese(date)) + .font(.system(size: 11)) + .foregroundStyle(.tertiary) + } - if let date = item.updatedAt { - Text(relativeChinese(date)) - .font(.system(size: 10.5)) - .foregroundStyle(.tertiary) - .layoutPriority(1) + if organization == .workspaceGrouped { + statusBadge(for: session) + } } } - .padding(.horizontal, 10) - .padding(.vertical, 8) - .background( - RoundedRectangle(cornerRadius: 9, style: .continuous) - .fill(isCurrent ? Color.accentColor.opacity(0.12) : Color.clear) - ) + .padding(.horizontal, 14) + .padding(.vertical, 11) .contentShape(Rectangle()) } .buttonStyle(.plain) .contextMenu { + Menu { + ForEach(KanbanSessionStatus.activeColumns) { targetStatus in + let isCurrentSelection = session.status == targetStatus + && !(targetStatus == .done && isRecentlyActiveReadSession(session)) + Button { + performStatusChange(session, to: targetStatus) + } label: { + HStack { + Text(targetStatus.title) + if isCurrentSelection { + Image(systemName: "checkmark") + } + } + } + } + } label: { + Label("切换状态", systemImage: "flag") + } + + Button { + performTogglePin(session) + } label: { + Label(session.isPinned ? "取消置顶" : "置顶会话", systemImage: session.isPinned ? "pin.slash" : "pin") + } + Button { - archiveSingleConversation(item) + renameDraft = session.name ?? session.resolvedTitle + renamingSession = session } label: { - Label("归档对话", systemImage: "archivebox") + Label("重命名", systemImage: "pencil") } + + Button { + performArchive(session) + } label: { + Label("归档会话", systemImage: "archivebox") + } + + Divider() + Button(role: .destructive) { - deleteSingleConversation(item) + deletingSession = session } label: { - Label("删除对话", systemImage: "trash") + Label("删除会话", systemImage: "trash") } } } - // MARK: Sidebar Tab 2: 项目文件 + private func statusBadge(for session: KanbanSessionSummary) -> some View { + let (label, color): (String, Color) = { + if session.isRunning || session.status == .inprogress { return ("进行中", .orange) } + switch session.status { + case .inreview: return ("待检查", .purple) + case .todo: return ("待开始", .blue) + case .done: + if isRecentlyActiveReadSession(session) { + return ("近期对话", .teal) + } + return ("已完成", .green) + case .archived: return ("已归档", .gray) + case .inprogress: return ("进行中", .orange) + } + }() + return Text(label) + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(color) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Capsule().fill(color.opacity(0.13))) + } + + // MARK: - Level-2 `新建会话` (`New Thread`) Screen - private var sidebarFilesContent: some View { - let q = sidebarSearchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - let filteredGroups = groups.filter { group in - guard group.id != "other" else { return false } - guard !q.isEmpty else { return true } - return group.name.lowercased().contains(q) || group.rootPath.lowercased().contains(q) - } - - return VStack(alignment: .leading, spacing: 6) { - ForEach(filteredGroups) { group in - let ws = workspaceID(for: group) - let isExpanded = expandedFileProjectIDs.contains(group.id) - VStack(alignment: .leading, spacing: 2) { - HStack(spacing: 8) { - Button { - guard let ws else { return } - withAnimation(.smooth(duration: 0.18)) { - if isExpanded { - expandedFileProjectIDs.remove(group.id) - } else { - expandedFileProjectIDs.insert(group.id) - loadSidebarWorkspaceEntries(workspaceID: ws) - } - } - } label: { - HStack(spacing: 8) { - Image(systemName: isExpanded ? "chevron.down" : "chevron.right") - .font(.system(size: 10.5, weight: .semibold)) - .foregroundStyle(.tertiary) - .frame(width: 12) - - Image(systemName: "folder") - .font(.system(size: 13.5)) - .foregroundStyle(.secondary) - - Text(group.name) - .font(.system(size: 13.5, weight: .medium)) - .foregroundStyle(.primary) - .lineLimit(1) + private var newThreadScreen: some View { + VStack(spacing: 0) { + // Top Floating Bar (`< 新建会话` + `[ ⑂ | 📁 ]`) + HStack(spacing: 12) { + FloatingCircleBackButton { + if !path.isEmpty { + path.removeLast() + } + } - Spacer(minLength: 4) - } - .contentShape(Rectangle()) + Text("新建会话") + .font(.system(size: 20, weight: .bold)) + .foregroundStyle(.primary) + + Spacer() + + WorkspaceDualToolsCapsule( + changeCount: newThreadDiffCount, + isDisabled: effectiveNewThreadWorkspaceID == nil, + onOpenChanges: { + if let ws = effectiveNewThreadWorkspaceID { + activeDiffWorkspace = WorkspaceSheetTarget( + workspaceID: ws, + title: effectiveNewThreadProject?.displayName ?? "代码差异" + ) + } + }, + onOpenFiles: { + if let ws = effectiveNewThreadWorkspaceID { + activeFileBrowserWorkspace = WorkspaceSheetTarget( + workspaceID: ws, + title: effectiveNewThreadProject?.displayName ?? "项目文件" + ) } - .buttonStyle(.plain) + } + ) + } + .padding(.horizontal, 14) + .padding(.top, 6) + .padding(.bottom, 8) + + // Calm middle canvas — tap anywhere to dismiss keyboard + Spacer(minLength: 20) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .contentShape(Rectangle()) + .onTapGesture { + dismissKeyboard() + } + + if let actionErrorMessage { + Text(actionErrorMessage) + .font(.footnote) + .foregroundStyle(.red) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 18) + .padding(.bottom, 8) + } + + // Lightweight bottom-aligned context breadcrumbs right above composer + newThreadContextBreadcrumbs + .padding(.horizontal, 18) + .padding(.bottom, 12) + + // Unified Floating Capsule Composer + newThreadPromptBar + } + .background(Color(.systemGroupedBackground).ignoresSafeArea()) + .toolbar(.hidden, for: .navigationBar) + .toolbar(.hidden, for: .tabBar) + .task(id: effectiveNewThreadProject?.id) { + if let pid = effectiveNewThreadProject?.id { + await loadWorkspacesAndDiffForNewThread(projectID: pid) + } + } + .task(id: effectiveNewThreadWorkspaceID) { + if let wid = effectiveNewThreadWorkspaceID, + let diffs = try? await client.workspaceDiff(workspaceID: wid) + { + newThreadDiffCount = diffs.count + } else { + newThreadDiffCount = 0 + } + } + } + + private var newThreadContextBreadcrumbs: some View { + VStack(alignment: .leading, spacing: 11) { + // Row 1: `📁 ›` + `💻 ›` + HStack(spacing: 14) { + Button { + dismissKeyboard() + showNewThreadProjectSheet = true + } label: { + HStack(spacing: 5.5) { + Image(systemName: effectiveNewThreadProject?.isHome == true ? "house" : "folder") + .font(.system(size: 13.5, weight: .medium)) + Text(effectiveNewThreadProject?.displayName ?? "选择项目") + .font(.system(size: 14, weight: .medium)) + .lineLimit(1) + Image(systemName: "chevron.right") + .font(.system(size: 11, weight: .semibold)) + .opacity(0.65) + } + .foregroundStyle(.secondary) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) - if let ws { + Button { + dismissKeyboard() + connectFlow.presentPicker(servers: servers) + } label: { + HStack(spacing: 5.5) { + Image(systemName: "laptopcomputer") + .font(.system(size: 13.5, weight: .medium)) + Text(servers.activeProfile?.displayHost ?? "VibeX 桌面端") + .font(.system(size: 14, weight: .medium)) + .lineLimit(1) + Image(systemName: "chevron.right") + .font(.system(size: 11, weight: .semibold)) + .opacity(0.65) + } + .foregroundStyle(.secondary) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + Spacer(minLength: 0) + } + + // Row 2: `📁 当前检出` + `⑂ ›` + HStack(spacing: 14) { + HStack(spacing: 5.5) { + Image(systemName: "folder") + .font(.system(size: 13.5, weight: .medium)) + Text(effectiveNewThreadWorkspaceRecord?.useWorktree == true ? "独立工作树" : "当前检出") + .font(.system(size: 14, weight: .medium)) + .lineLimit(1) + } + .foregroundStyle(.secondary) + + if newThreadWorkspaces.count > 1 { + Menu { + ForEach(newThreadWorkspaces) { ws in Button { - isSidebarOpen = false - activeFileBrowserWorkspace = WorkspaceSheetTarget( - workspaceID: ws, - title: group.name - ) + newThreadWorkspaceID = ws.id } label: { - Text("浏览") - .font(.system(size: 11.5, weight: .medium)) - .foregroundStyle(.secondary) - .padding(.horizontal, 8) - .padding(.vertical, 3.5) - .background( - Capsule(style: .continuous) - .fill(Color(.tertiarySystemFill)) + HStack { + Label( + ws.displayLabel, + systemImage: ws.useWorktree ? "square.split.2x1" : "arrow.triangle.branch" ) - } - .buttonStyle(.plain) - } - } - .padding(.horizontal, 10) - .padding(.vertical, 7) - - if isExpanded, let ws { - if loadingWorkspaceIDs.contains(ws) { - HStack(spacing: 8) { - ProgressView().controlSize(.small) - Text("读取中…") - .font(.system(size: 11.5)) - .foregroundStyle(.secondary) - } - .padding(.leading, 30) - .padding(.vertical, 4) - } else if let entries = projectEntriesByWorkspace[ws] { - VStack(alignment: .leading, spacing: 1) { - ForEach(entries.prefix(25), id: \.path) { entry in - Button { - isSidebarOpen = false - if entry.directory { - activeFileBrowserWorkspace = WorkspaceSheetTarget( - workspaceID: ws, - title: group.name - ) - } else { - previewFileTarget = FilePreviewSheetTarget( - workspaceID: ws, - path: entry.path - ) - } - } label: { - HStack(spacing: 7) { - Image( - systemName: entry.directory - ? "folder" - : FileGlyph.symbol(for: entry.name) - ) - .font(.system(size: 11.5)) - .foregroundStyle(.secondary) - .frame(width: 15) - - Text(entry.name) - .font(.system(size: 12.5)) - .foregroundStyle(.primary) - .lineLimit(1) - - Spacer() - } - .padding(.leading, 28) - .padding(.trailing, 10) - .padding(.vertical, 5) - .contentShape(Rectangle()) + if ws.id == effectiveNewThreadWorkspaceID { + Image(systemName: "checkmark") } - .buttonStyle(.plain) } } } + } label: { + HStack(spacing: 5.5) { + Image(systemName: "arrow.triangle.branch") + .font(.system(size: 13, weight: .medium)) + Text(effectiveNewThreadBranchLabel) + .font(.system(size: 14, weight: .medium)) + .lineLimit(1) + Image(systemName: "chevron.right") + .font(.system(size: 11, weight: .semibold)) + .opacity(0.65) + } + .foregroundStyle(.secondary) + .contentShape(Rectangle()) + } + } else { + HStack(spacing: 5.5) { + Image(systemName: "arrow.triangle.branch") + .font(.system(size: 13, weight: .medium)) + Text(effectiveNewThreadBranchLabel) + .font(.system(size: 14, weight: .medium)) + .lineLimit(1) + Image(systemName: "chevron.right") + .font(.system(size: 11, weight: .semibold)) + .opacity(0.45) } + .foregroundStyle(.secondary) } - .padding(.horizontal, 8) + + Spacer(minLength: 0) } } } - private func loadSidebarWorkspaceEntries(workspaceID: String) { - guard projectEntriesByWorkspace[workspaceID] == nil, - !loadingWorkspaceIDs.contains(workspaceID) - else { return } - loadingWorkspaceIDs.insert(workspaceID) - Task { - defer { loadingWorkspaceIDs.remove(workspaceID) } - if let tree = try? await client.workspaceTree(workspaceID: workspaceID, path: "") { - let sorted = tree.entries.sorted { - if $0.directory != $1.directory { return $0.directory && !$1.directory } - return $0.name.localizedStandardCompare($1.name) == .orderedAscending + // MARK: - New Thread Project Picker Sheet + + private var newThreadProjectPickerSheet: some View { + NavigationStack { + List { + ForEach(projects) { project in + let isSelected = effectiveNewThreadProject?.id.lowercased() == project.id.lowercased() + Button { + newThreadProjectID = project.id + newThreadWorkspaceID = nil + showNewThreadProjectSheet = false + Task { await loadWorkspacesAndDiffForNewThread(projectID: project.id) } + } label: { + HStack(spacing: 12) { + Image(systemName: project.isHome ? "house" : (project.isGit ? "arrow.triangle.branch" : "folder")) + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.secondary) + .frame(width: 28) + + VStack(alignment: .leading, spacing: 2) { + Text(project.displayName) + .font(.system(size: 15, weight: isSelected ? .semibold : .regular)) + .foregroundStyle(.primary) + if !project.rootPath.isEmpty { + Text(project.rootPath) + .font(.system(size: 11.5)) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + } + + Spacer() + + if isSelected { + Image(systemName: "checkmark") + .font(.system(size: 14, weight: .semibold)) + .foregroundStyle(Color.accentColor) + } + } + .padding(.vertical, 3) + } + .buttonStyle(.plain) + } + } + .navigationTitle("选择项目") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("关闭") { showNewThreadProjectSheet = false } } - projectEntriesByWorkspace[workspaceID] = sorted } } } - // MARK: - Landing PromptBar Integration + // MARK: - New Thread PromptBar & Creation Logic private var savedCustomModels: [String] { savedCustomModelsRaw @@ -894,13 +1164,16 @@ struct ConversationsView: View { private var landingAgentChoices: [PromptChoice] { let activeID = currentAgent?.id ?? "claude_code" - let list = usableAgents.isEmpty - ? [ + let list: [CatalogAgent] + if !usableAgents.isEmpty { + list = usableAgents + } else if agents.isEmpty { + list = [ CatalogAgent(id: "claude_code", displayName: "Claude Code", usable: true, currentModeID: nil, modes: [], options: []), - CatalogAgent(id: "codex", displayName: "Codex", usable: true, currentModeID: nil, modes: [], options: []), - CatalogAgent(id: "antigravity", displayName: "Antigravity", usable: true, currentModeID: nil, modes: [], options: []), ] - : usableAgents + } else { + list = [] + } return list.map { item in PromptChoice( id: item.id, @@ -952,7 +1225,7 @@ struct ConversationsView: View { PromptChoice( id: customID, title: custom, - tag: "自定义/中转", + tag: "自定义", agentID: agent.id, selected: selectedModelChoiceID == customID || customModelName == custom ) @@ -996,7 +1269,8 @@ struct ConversationsView: View { return customModelName } if let selectedID = selectedModelChoiceID, - let match = landingModelChoices.first(where: { $0.id == selectedID }) { + let match = landingModelChoices.first(where: { $0.id == selectedID }) + { return match.title } if let firstSelected = landingModelChoices.first(where: \.selected) { @@ -1032,41 +1306,11 @@ struct ConversationsView: View { } let activeID = selectedAccessModeID ?? "auto" return [ - PromptChoice( - id: "manual", - title: "手动审批", - detail: "每次修改前询问确认", - icon: "shield", - selected: activeID == "manual" - ), - PromptChoice( - id: "accept_edits", - title: "自动接受编辑", - detail: "自动接受所有文件编辑", - icon: "shield", - selected: activeID == "accept_edits" - ), - PromptChoice( - id: "plan", - title: "仅规划", - detail: "执行前先生成规划方案", - icon: "shield", - selected: activeID == "plan" - ), - PromptChoice( - id: "auto", - title: "自动", - detail: "由 Agent 自动处理权限判断", - icon: "shield", - selected: activeID == "auto" - ), - PromptChoice( - id: "bypass", - title: "跳过权限", - detail: "自动通过所有权限请求", - icon: "shield", - selected: activeID == "bypass" - ), + PromptChoice(id: "manual", title: "手动审批", detail: "每次修改前询问确认", icon: "shield", selected: activeID == "manual"), + PromptChoice(id: "accept_edits", title: "自动接受编辑", detail: "自动接受所有文件编辑", icon: "shield", selected: activeID == "accept_edits"), + PromptChoice(id: "plan", title: "仅规划", detail: "执行前先生成规划方案", icon: "shield", selected: activeID == "plan"), + PromptChoice(id: "auto", title: "自动", detail: "由 Agent 自动处理权限判断", icon: "shield", selected: activeID == "auto"), + PromptChoice(id: "bypass", title: "完全访问", detail: "自动通过所有权限请求", icon: "shield", selected: activeID == "bypass"), ] } @@ -1089,7 +1333,7 @@ struct ConversationsView: View { return PromptEffort(levels: levels, index: idx) } - private var landingPromptBar: some View { + private var newThreadPromptBar: some View { PromptBar( draft: $draft, menu: $composerMenu, @@ -1106,23 +1350,33 @@ struct ConversationsView: View { accessChoices: landingAccessChoices, extraChoices: [], effort: landingEffort, + placeholder: "发消息或提问…", openFiles: { - if let ws = currentWorkspaceID { + if let ws = effectiveNewThreadWorkspaceID { activeFileBrowserWorkspace = WorkspaceSheetTarget( workspaceID: ws, - title: currentGroup?.name ?? "文件" + title: effectiveNewThreadProject?.displayName ?? "项目文件" ) } }, + onRefreshCatalog: { + Task { + if let fetched = try? await client.agentCatalog(), !fetched.isEmpty { + agents = fetched + } + } + }, send: { startNewConversation(with: draft) }, + sendText: { sentText in + startNewConversation(with: sentText) + }, stop: {}, pickAgent: { id in selectedAgentID = id selectedModelChoiceID = nil customModelName = nil - composerMenu = nil }, pickModel: { id in if id.hasPrefix("switch-agent|") { @@ -1144,7 +1398,6 @@ struct ConversationsView: View { customModelName = nil selectedModelChoiceID = id } - composerMenu = nil }, onAddCustomModel: { custom in rememberCustomModel(custom) @@ -1155,7 +1408,6 @@ struct ConversationsView: View { }, pickAccess: { id in selectedAccessModeID = id - composerMenu = nil }, pickExtra: { _ in }, setEffort: { index in @@ -1167,11 +1419,11 @@ struct ConversationsView: View { private func startNewConversation(with text: String) { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty, !isCreatingAndSending else { return } - guard let workspaceID = currentWorkspaceID else { + guard let workspaceID = effectiveNewThreadWorkspaceID else { actionErrorMessage = "当前没有可用项目工作区,请先在桌面端导入项目" return } - let agentID = currentAgent?.id ?? visibleConversations.first?.agent_id ?? "claude_code" + let agentID = currentAgent?.id ?? recentConversations.first?.agent_id ?? "claude_code" let chosenModel = resolvedSelectedModelKeyValue let chosenModeID = selectedAccessModeID let chosenEffort: (key: String, value: JSONValue)? = { @@ -1198,193 +1450,251 @@ struct ConversationsView: View { agentID: agentID ) attentionCenter?.markLocallyCreatedConversation(created.id) - _ = try? await client.ensureSessionControls(conversationID: created.id) - if let chosenModeID, !chosenModeID.isEmpty { - try? await client.setSessionMode(conversationID: created.id, modeID: chosenModeID) - } - if let chosenModel, !chosenModel.value.isEmpty, chosenModel.value != "default" { - try? await client.setSessionConfigOption( - conversationID: created.id, - key: chosenModel.key, - value: .string(chosenModel.value) - ) - } - if let chosenEffort { - try? await client.setSessionConfigOption( - conversationID: created.id, - key: chosenEffort.key, - value: chosenEffort.value - ) - } - try await client.sendMessage( - conversationID: created.id, + setManuallyCompleted(created.id, completed: false) + + pendingInitialPrompts[created.id] = PendingInitialPrompt( + text: trimmed, workspaceID: workspaceID, agentID: agentID, - text: trimmed + modeID: chosenModeID, + modelKey: chosenModel?.key, + modelValue: chosenModel?.value, + effortKey: chosenEffort?.key, + effortValue: chosenEffort?.value + ) + + let nowISO = ISO8061NowString() + let optimistic = KanbanSessionSummary( + id: created.id, + workspaceId: workspaceID, + name: created.title, + displayName: created.title, + status: .inprogress, + executor: agentID, + agentId: agentID, + workspaceName: effectiveNewThreadWorkspaceRecord?.name, + workspaceBranch: effectiveNewThreadBranchLabel, + createdAt: nowISO, + updatedAt: nowISO, + firstPrompt: trimmed, + isRunning: true, + model: chosenModel?.value ?? created.model ) + sessions.removeAll { $0.id == created.id } + sessions.insert(optimistic, at: 0) draft = "" - userRequestedNewChatLanding = false - withAnimation(.smooth(duration: 0.22)) { - activeConversation = created - } - await reload() + path = [.conversation(created)] + Task { await reload() } } catch { + draft = trimmed actionErrorMessage = describeHostFailure(error) } } } - // MARK: - Project Picker Sheet - - private var projectPickerSheet: some View { - NavigationStack { - List { - ForEach(groups.filter { $0.id != "other" }) { group in - let isSelected = currentGroup?.id == group.id - Button { - selectedProjectID = group.id - showProjectPickerSheet = false - } label: { - HStack(spacing: 12) { - Image(systemName: group.isHome ? "house" : "folder") - .font(.system(size: 15, weight: .medium)) - .foregroundStyle(.secondary) - .frame(width: 28) - - VStack(alignment: .leading, spacing: 2) { - Text(group.name) - .font(.system(size: 15, weight: isSelected ? .semibold : .regular)) - .foregroundStyle(.primary) - if !group.rootPath.isEmpty { - Text(group.rootPath) - .font(.system(size: 11.5)) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.middle) - } - } + // MARK: - Session Actions & Data Loading + + private func markLocalSessionRunning(conversation: ConversationListItem, promptText: String) { + setManuallyCompleted(conversation.id, completed: false) + let nowISO = ISO8061NowString() + if let idx = sessions.firstIndex(where: { $0.id == conversation.id }) { + sessions[idx].status = .inprogress + sessions[idx].isRunning = true + sessions[idx].updatedAt = nowISO + } else { + let optimistic = KanbanSessionSummary( + id: conversation.id, + workspaceId: conversation.workspace_id, + name: conversation.title, + displayName: conversation.title, + status: .inprogress, + executor: conversation.agent_id, + agentId: conversation.agent_id, + createdAt: nowISO, + updatedAt: nowISO, + firstPrompt: promptText, + isRunning: true, + model: conversation.model + ) + sessions.insert(optimistic, at: 0) + } + } - Spacer() + private func markLocalSessionViewedNow(sessionID: String) { + let nowISO = ISO8061NowString() + if let idx = sessions.firstIndex(where: { $0.id == sessionID }) { + sessions[idx].isRunning = false + sessions[idx].status = .done + sessions[idx].updatedAt = nowISO + } + } - if isSelected { - Image(systemName: "checkmark") - .font(.system(size: 14, weight: .semibold)) - .foregroundStyle(Color.accentColor) - } - } - .padding(.vertical, 3) - } - .buttonStyle(.plain) - } + private func openSession(_ session: KanbanSessionSummary) { + if session.completesWhenViewed { + if let idx = sessions.firstIndex(where: { $0.id == session.id }) { + sessions[idx].status = .done } - .navigationTitle("选择项目") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("关闭") { showProjectPickerSheet = false } - } + Task { + try? await client.markSessionViewed(sessionID: session.id) } } + path.append(.conversation(session.asConversationListItem)) } - // MARK: - Helpers & Data Loading - private func consumePendingNavigationIfNeeded() { guard let target = attentionCenter?.pendingNavigationConversation else { return } attentionCenter?.pendingNavigationConversation = nil - isSidebarOpen = false - userRequestedNewChatLanding = false - withAnimation(.smooth(duration: 0.2)) { - activeConversation = target + path = [.conversation(target)] + } + + private func performStatusChange(_ session: KanbanSessionSummary, to newStatus: KanbanSessionStatus) { + let oldStatus = session.status + let wasManuallyCompleted = manuallyCompletedIDs.contains(session.id) + setManuallyCompleted(session.id, completed: newStatus == .done) + if let idx = sessions.firstIndex(where: { $0.id == session.id }) { + sessions[idx].status = newStatus + if newStatus != .inprogress { + sessions[idx].isRunning = false + } + } + Task { + do { + try await client.updateSessionStatus(sessionID: session.id, status: newStatus) + await reload() + } catch { + setManuallyCompleted(session.id, completed: wasManuallyCompleted) + if let idx = sessions.firstIndex(where: { $0.id == session.id }) { + sessions[idx].status = oldStatus + } + actionErrorMessage = describeHostFailure(error) + } + } + } + + private func performTogglePin(_ session: KanbanSessionSummary) { + let nextPinned = !session.isPinned + if let idx = sessions.firstIndex(where: { $0.id == session.id }) { + sessions[idx].pinnedAt = nextPinned ? ISO8061NowString() : nil + } + Task { + do { + try await client.setSessionPinned(sessionID: session.id, pinned: nextPinned) + await reload() + } catch { + actionErrorMessage = describeHostFailure(error) + await reload() + } } } - private func syncWithFetchedConversations(_ fetched: [ConversationListItem]) { - if let current = activeConversation, - let updated = fetched.first(where: { $0.id == current.id }) { - activeConversation = updated - } else if !didSyncInitialDesktopConversation && !userRequestedNewChatLanding, - let initial = fetched.first(where: { !removedConversationIDs.contains($0.id) }) { - didSyncInitialDesktopConversation = true - withAnimation(.smooth(duration: 0.22)) { - activeConversation = initial + private func performRename(_ session: KanbanSessionSummary, newName: String) { + let trimmed = newName.trimmingCharacters(in: .whitespacesAndNewlines) + if let idx = sessions.firstIndex(where: { $0.id == session.id }) { + sessions[idx].name = trimmed.isEmpty ? nil : trimmed + } + Task { + do { + try await client.renameSession(sessionID: session.id, name: trimmed.isEmpty ? nil : trimmed) + await reload() + } catch { + actionErrorMessage = describeHostFailure(error) + await reload() } } } - private func archiveSingleConversation(_ item: ConversationListItem) { - let id = item.id + private func performArchive(_ session: KanbanSessionSummary) { + let id = session.id withAnimation { - _ = removedConversationIDs.insert(id) - if activeConversation?.id == id { - activeConversation = nil - } + _ = removedSessionIDs.insert(id) } Task { do { try await client.archiveConversation(conversationID: id) - actionErrorMessage = nil await reload() } catch { - withAnimation { _ = removedConversationIDs.remove(id) } + withAnimation { _ = removedSessionIDs.remove(id) } actionErrorMessage = describeHostFailure(error) } } } - private func deleteSingleConversation(_ item: ConversationListItem) { - let id = item.id + private func performDelete(_ session: KanbanSessionSummary) { + let id = session.id withAnimation { - _ = removedConversationIDs.insert(id) - if activeConversation?.id == id { - activeConversation = nil - } + _ = removedSessionIDs.insert(id) } Task { do { try await client.deleteConversation(conversationID: id) - actionErrorMessage = nil await reload() } catch { - withAnimation { _ = removedConversationIDs.remove(id) } + withAnimation { _ = removedSessionIDs.remove(id) } actionErrorMessage = describeHostFailure(error) } } } + private func loadWorkspacesAndDiffForNewThread(projectID: String) async { + if let wsList = try? await client.kanbanWorkspaces(projectID: projectID) { + workspacesByProject[projectID] = wsList + } + if let wid = effectiveNewThreadWorkspaceID, + let diffs = try? await client.workspaceDiff(workspaceID: wid) + { + newThreadDiffCount = diffs.count + } + } + private func reload() async { - async let projectsTask = try? client.projects() - async let agentsTask = try? client.agentCatalog() - let (fetchedProjects, fetchedAgents) = await (projectsTask, agentsTask) - if let fetchedProjects { projects = fetchedProjects } - if let fetchedAgents, !fetchedAgents.isEmpty { agents = fetchedAgents } - - await list.load { - let fetched = try await client.call( + do { + async let projectsTask = client.projects() + async let agentsTask = try? client.agentCatalog() + async let recentTask = try? client.call( "conversation_list_recent", args: ["sinceDays": 30, "limit": 100], as: [ConversationListItem].self ) - let activeIDs = Set(fetched.map(\.id)) - removedConversationIDs.formIntersection(activeIDs) - syncWithFetchedConversations(fetched) - return fetched + + let (loadedProjects, fetchedAgents, fetchedRecent) = try await (projectsTask, agentsTask, recentTask) + projects = loadedProjects + if let fetchedAgents, !fetchedAgents.isEmpty { + agents = fetchedAgents + } + if let fetchedRecent { + recentConversations = fetchedRecent + } + + let allWorkspaceIDs = loadedProjects.flatMap(\.workspaceIds) + if !allWorkspaceIDs.isEmpty, + let fetchedSessions = try? await client.kanbanAllSessions(workspaceIDs: allWorkspaceIDs) + { + sessions = fetchedSessions + } + + let activeIDs = Set(sessions.map(\.id)).union(recentConversations.map(\.id)) + removedSessionIDs.formIntersection(activeIDs) + loadErrorMessage = nil + isLoading = false + } catch { + loadErrorMessage = describeHostFailure(error) + isLoading = false } } } +private let sharedISO8601Formatter = ISO8601DateFormatter() + +private func ISO8061NowString() -> String { + sharedISO8601Formatter.string(from: Date()) +} + private struct WorkspaceSheetTarget: Identifiable { let workspaceID: String let title: String var id: String { workspaceID } } -private struct FilePreviewSheetTarget: Identifiable { - let workspaceID: String - let path: String - var id: String { "\(workspaceID):\(path)" } -} - extension ConversationListItem: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(id) } } diff --git a/App/DesktopConnectFlow.swift b/App/DesktopConnectFlow.swift index b3aed37..8ef648d 100644 --- a/App/DesktopConnectFlow.swift +++ b/App/DesktopConnectFlow.swift @@ -3,37 +3,54 @@ import Observation import SwiftUI import UIKit -enum DesktopChannel: Equatable { - case cloud - case lan -} - -/// Drives the one-tap connection to a desktop signed into the same VibeX account, and the code-pairing fallback. +/// Drives seamless connection to a desktop signed into the same VibeX account (auto-selecting LAN first, +/// Cloud Relay second), plus 1-tap LAN 4-digit SAS visual comparison and code/QR fallback. @Observable @MainActor final class DesktopConnectFlow { + enum Target: Equatable { + case accountDesktop(AccountDesktop) + case lanHost(DiscoveredLanHost) + + var displayName: String { + switch self { + case .accountDesktop(let desktop): return desktop.displayName + case .lanHost(let host): return host.displayName + } + } + + var hostId: String { + switch self { + case .accountDesktop(let desktop): return desktop.hostId + case .lanHost(let host): return host.hostId.map(AccountDesktop.rawHostId) ?? "" + } + } + } + enum Phase: Equatable { case choosing - case connecting(DesktopChannel) - case awaitingApproval(sasCode: String) + case connecting + case awaitingApproval(sasCode: String, hostName: String) case failed(String) } struct ReplaceConfirmation: Identifiable { let id = UUID() let existingDeviceName: String - let desktop: AccountDesktop - let channel: DesktopChannel + let target: Target } var isPickerPresented = false var isCodePairingPresented = false + var isAutoConnectingInBackground = false + var autoConnectingHostName: String? var selectedHostId: String? var replaceConfirmation: ReplaceConfirmation? private(set) var phase: Phase = .choosing - private var lastAttempt: (desktop: AccountDesktop, channel: DesktopChannel)? + private var lastAttemptTarget: Target? private var openCodePairingAfterPicker = false private var connectTask: Task? + private var didAttemptInitialAutoConnect = false func presentPicker(servers: ServerStore) { phase = .choosing @@ -47,10 +64,12 @@ final class DesktopConnectFlow { isPickerPresented = false } - /// Called when the picker sheet goes away by any route; abandons an in-flight request. + /// Called when the picker sheet goes away by any route; abandons an in-flight sheet request. func pickerDismissed() { - connectTask?.cancel() - connectTask = nil + if !isAutoConnectingInBackground { + connectTask?.cancel() + connectTask = nil + } phase = .choosing if openCodePairingAfterPicker { openCodePairingAfterPicker = false @@ -62,98 +81,201 @@ final class DesktopConnectFlow { desktops.first { $0.hostId == selectedHostId } ?? desktops.first } + /// Automatically connects when the signed-in account has a single computer, avoiding extra modal steps. + /// Falls back to presenting the picker when multiple computers exist or when user attention is required. + func autoConnectOnSignIn(servers: ServerStore, account: VibeXAccountStore) { + if account.desktops.count == 1, let only = account.desktops.first { + connect(.accountDesktop(only), servers: servers, account: account, silentUntilNeeded: true) + } else { + presentPicker(servers: servers) + } + } + + /// Triggered once when account hosts finish syncing while no computer is currently paired. + func autoConnectInitialIfNeeded(servers: ServerStore, account: VibeXAccountStore) { + guard !didAttemptInitialAutoConnect, + servers.autoConnect, + servers.profiles.isEmpty, + account.isSignedIn, + account.desktops.count == 1, + let only = account.desktops.first + else { return } + didAttemptInitialAutoConnect = true + connect(.accountDesktop(only), servers: servers, account: account, silentUntilNeeded: true) + } + func retry(servers: ServerStore, account: VibeXAccountStore) { - guard let lastAttempt else { + guard let lastAttemptTarget else { phase = .choosing return } - connect(lastAttempt.desktop, via: lastAttempt.channel, servers: servers, account: account) + connect(lastAttemptTarget, servers: servers, account: account) } func confirmReplace(servers: ServerStore, account: VibeXAccountStore) { guard let confirmation = replaceConfirmation else { return } replaceConfirmation = nil - connect(confirmation.desktop, via: confirmation.channel, servers: servers, account: account, replaceExistingMobile: true) + connect(confirmation.target, servers: servers, account: account, replaceExistingMobile: true) } func connect( - _ desktop: AccountDesktop, - via channel: DesktopChannel, + _ target: Target, servers: ServerStore, account: VibeXAccountStore, - replaceExistingMobile: Bool = false + replaceExistingMobile: Bool = false, + silentUntilNeeded: Bool = false ) { - let origin: String - switch channel { - case .cloud: - origin = desktop.cloudOrigin(relayBase: account.relayBase) - case .lan: - guard let lanOrigin = servers.lanOrigin(forHostId: desktop.hostId) else { - phase = .choosing - return - } - origin = lanOrigin + lastAttemptTarget = target + if silentUntilNeeded { + isAutoConnectingInBackground = true + autoConnectingHostName = target.displayName + } else { + phase = .connecting } - lastAttempt = (desktop, channel) - phase = .connecting(channel) + connectTask?.cancel() connectTask = Task { @MainActor [weak self] in guard let self else { return } - if !replaceExistingMobile, await servers.connectSavedCredential(hostId: desktop.hostId, origin: origin) { - self.finish() - return + defer { + self.isAutoConnectingInBackground = false + self.autoConnectingHostName = nil } - guard let accountToken = account.token else { - self.isPickerPresented = false - await account.signOut() + + let candidateOrigins = await Self.resolveCandidateOrigins( + for: target, + servers: servers, + account: account + ) + guard !candidateOrigins.isEmpty else { + if silentUntilNeeded { + self.presentPicker(servers: servers) + } + self.phase = .failed("未发现可用连接通道,请确认电脑端在线或与手机处于同一 Wi-Fi") return } - do { - try await servers.connectViaAccountRequest( - origin: origin, - hostId: desktop.hostId, - hostName: desktop.displayName, - deviceName: UIDevice.current.name, - accountToken: accountToken, - replaceExistingMobile: replaceExistingMobile, - onAwaitingApproval: { sasCode in - self.phase = .awaitingApproval(sasCode: sasCode) + + if !replaceExistingMobile, !target.hostId.isEmpty { + for origin in candidateOrigins { + if await servers.connectSavedCredential(hostId: target.hostId, origin: origin) { + self.finish() + return } - ) - self.finish() - } catch is CancellationError { - return - } catch PairingError.mobileDeviceConflict(let existingName) { - self.phase = .choosing - self.replaceConfirmation = ReplaceConfirmation(existingDeviceName: existingName, desktop: desktop, channel: channel) - } catch PairingError.accountTokenInvalid { - self.isPickerPresented = false - await account.signOut() - } catch { + } + } + + var lastError: Error = PairingError.unreachable + for origin in candidateOrigins { guard !Task.isCancelled else { return } - UINotificationFeedbackGenerator().notificationOccurred(.error) - self.phase = .failed(Self.message(for: error)) + do { + try await servers.connectViaAccountRequest( + origin: origin, + hostId: target.hostId, + hostName: target.displayName, + deviceName: UIDevice.current.name, + accountToken: account.token, + replaceExistingMobile: replaceExistingMobile, + onAwaitingApproval: { sasCode in + self.isAutoConnectingInBackground = false + self.phase = .awaitingApproval(sasCode: sasCode, hostName: target.displayName) + if !self.isPickerPresented { + self.isPickerPresented = true + } + } + ) + self.finish() + return + } catch is CancellationError { + return + } catch PairingError.mobileDeviceConflict(let existingName) { + self.phase = .choosing + if !self.isPickerPresented { + self.isPickerPresented = true + } + self.replaceConfirmation = ReplaceConfirmation( + existingDeviceName: existingName, + target: target + ) + return + } catch PairingError.accountTokenInvalid { + self.isPickerPresented = false + await account.signOut() + return + } catch let pairingErr as PairingError { + lastError = pairingErr + switch pairingErr { + case .connectRejected, .connectExpired, .accountMismatch: + break + default: + continue + } + break + } catch { + lastError = error + continue + } + } + + guard !Task.isCancelled else { return } + UINotificationFeedbackGenerator().notificationOccurred(.error) + self.phase = .failed(Self.message(for: lastError)) + if silentUntilNeeded && !self.isPickerPresented { + self.isPickerPresented = true + } + } + } + + /// Resolves LAN direct first (lowest latency), seamlessly falling back to Cloud Relay when available. + private static func resolveCandidateOrigins( + for target: Target, + servers: ServerStore, + account: VibeXAccountStore + ) async -> [String] { + switch target { + case .lanHost(let host): + return [host.origin] + case .accountDesktop(let desktop): + var origins: [String] = [] + if let existingLan = servers.lanOrigin(forHostId: desktop.hostId) { + origins.append(existingLan) + } else { + let freshLan = await PairingClient.discoverLanHosts() + if servers.discoveredHosts.isEmpty && !freshLan.isEmpty { + servers.discoveredHosts = freshLan + } + if let matched = freshLan.first(where: { + !$0.isCloudService && $0.hostId.map(AccountDesktop.rawHostId) == desktop.hostId + }) { + origins.append(matched.origin) + } + } + if account.canUseCloudRelay { + let cloud = desktop.cloudOrigin(relayBase: account.relayBase) + if !cloud.isEmpty, !origins.contains(cloud) { + origins.append(cloud) + } } + return origins } } private func finish() { UINotificationFeedbackGenerator().notificationOccurred(.success) + phase = .choosing isPickerPresented = false } private static func message(for error: Error) -> String { - if let pairingError = error as? PairingError, let description = pairingError.errorDescription { - return description - } + if let pairingError = error as? PairingError, let description = pairingError.errorDescription { + return description + } if error is URLError { - return PairingError.unreachable.errorDescription ?? "" - } + return PairingError.unreachable.errorDescription ?? "无法连接到电脑,请确认电脑端在线" + } return error.localizedDescription } } -/// Popup listing the account's desktops with one-tap cloud / LAN connect. +/// Sheet listing the account's desktops (and any LAN-discovered hosts) with 1-tap automatic channel selection. struct DesktopPickerSheet: View { @Environment(ServerStore.self) private var servers @Environment(VibeXAccountStore.self) private var account @@ -161,21 +283,49 @@ struct DesktopPickerSheet: View { private var desktops: [AccountDesktop] { account.desktops } + private var extraLanHosts: [DiscoveredLanHost] { + let knownIds = Set(desktops.map(\.hostId)) + return servers.discoveredHosts.filter { host in + guard !host.isCloudService else { return false } + guard let rawId = host.hostId.map(AccountDesktop.rawHostId), !rawId.isEmpty else { return true } + return !knownIds.contains(rawId) + } + } + var body: some View { VStack(spacing: 16) { - if account.desktops.isEmpty && (account.isLoading || account.isSyncingHosts) { + if desktops.isEmpty && extraLanHosts.isEmpty && (account.isLoading || account.isSyncingHosts) { LoadingState(label: "正在同步你的电脑") .padding(.vertical, 24) - } else if account.desktops.isEmpty && account.desktopsSyncFailed { - errorRow("同步失败,请重试") - actionButton("重试", prominent: true, enabled: true) { - Task { await account.syncHosts(with: servers) } - } - codePairingLink - } else if let desktop = flow.selectedDesktop(in: desktops) { - Text("发现你的电脑") + } else if case .awaitingApproval(let sasCode, let hostName) = flow.phase { + sasApprovalCard(sasCode: sasCode, hostName: hostName) + } else if case .failed(let message) = flow.phase { + Text("连接电脑") + .font(.system(size: 17, weight: .semibold)) + errorRow(message) + actionButton("重试", prominent: true, enabled: true) { + flow.retry(servers: servers, account: account) + } + codePairingLink + } else if let desktop = flow.selectedDesktop(in: desktops) { + Text("连接你的电脑") .font(.system(size: 17, weight: .semibold)) - content(for: desktop) + desktopList + connectPrimarySection(for: desktop) + if !extraLanHosts.isEmpty { + lanHostsSection + } + } else if !extraLanHosts.isEmpty { + Text("当前 Wi-Fi 发现电脑") + .font(.system(size: 17, weight: .semibold)) + lanHostsSection + codePairingLink + } else if desktops.isEmpty && account.desktopsSyncFailed { + errorRow("同步失败,请重试") + actionButton("重试", prominent: true, enabled: true) { + Task { await account.syncHosts(with: servers) } + } + codePairingLink } else { noDesktopGuide } @@ -203,32 +353,28 @@ struct DesktopPickerSheet: View { } } - @ViewBuilder - private func content(for desktop: AccountDesktop) -> some View { - switch flow.phase { - case .awaitingApproval(let sasCode): + private func sasApprovalCard(sasCode: String, hostName: String) -> some View { + VStack(spacing: 12) { + Text("连接「\(hostName)」") + .font(.system(size: 17, weight: .semibold)) + VStack(spacing: 8) { - Text("请在电脑上点击“连接”确认") - .font(.system(size: 13.5)) + Text("对比电脑顶部显示的连接码一致后,点击「连接」") + .font(.system(size: 13)) .foregroundStyle(.secondary) - Text("核对码 \(sasCode)") - .font(.system(size: 22, weight: .bold, design: .monospaced)) + .multilineTextAlignment(.center) + + Text(sasCode) + .font(.system(size: 30, weight: .bold, design: .monospaced)) + .monospacedDigit() + .kerning(3) .foregroundStyle(Color.accentColor) + .padding(.top, 2) } .frame(maxWidth: .infinity) - .padding(.vertical, 16) + .padding(.horizontal, 16) + .padding(.vertical, 18) .background(cardBackground) - case .failed(let message): - errorRow(message) - HStack(spacing: 10) { - actionButton("重试", prominent: true, enabled: true) { - flow.retry(servers: servers, account: account) - } - } - codePairingLink - case .choosing, .connecting: - desktopList - channelButtons(for: desktop) } } @@ -239,6 +385,7 @@ struct DesktopPickerSheet: View { Divider().padding(.leading, 14) } let isSelected = flow.selectedDesktop(in: desktops)?.id == desktop.id + let lanReady = servers.lanOrigin(forHostId: desktop.hostId) != nil Button { flow.selectedHostId = desktop.hostId } label: { @@ -258,6 +405,14 @@ struct DesktopPickerSheet: View { .background(Capsule().fill(Color.secondary.opacity(0.12))) .foregroundStyle(.secondary) } + if lanReady { + Text("局域网极速") + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Capsule().fill(Color.green.opacity(0.14))) + .foregroundStyle(.green) + } Spacer() if desktops.count > 1 && isSelected { Image(systemName: "checkmark") @@ -276,30 +431,73 @@ struct DesktopPickerSheet: View { .background(cardBackground) } - private func channelButtons(for desktop: AccountDesktop) -> some View { + private func connectPrimarySection(for desktop: AccountDesktop) -> some View { let lanAvailable = servers.lanOrigin(forHostId: desktop.hostId) != nil - let busy = flow.phase != .choosing - var notes: [String] = [] - if !account.canUseCloudRelay { - notes.append("账号未开通云服务") - } - if !lanAvailable { - notes.append(servers.discoveringHosts ? "正在搜索局域网…" : "当前 Wi-Fi 未发现这台电脑") - } + let canConnect = lanAvailable || account.canUseCloudRelay || servers.discoveringHosts + let busy = flow.phase == .connecting + let channelHint: String = { + if lanAvailable { + return "同账号免确认直连 · 已就绪局域网高速通道" + } + if account.canUseCloudRelay { + return "同账号免确认直连 · 自动优选局域网或云服务" + } + return servers.discoveringHosts ? "正在扫描当前 Wi-Fi…" : "当前 Wi-Fi 未发现该电脑且账号未开启云服务" + }() + return VStack(spacing: 8) { - HStack(spacing: 10) { - actionButton("使用云服务", prominent: true, enabled: account.canUseCloudRelay && !busy, inProgress: flow.phase == .connecting(.cloud)) { - flow.connect(desktop, via: .cloud, servers: servers, account: account) - } - actionButton("局域网", prominent: false, enabled: lanAvailable && !busy, inProgress: flow.phase == .connecting(.lan)) { - flow.connect(desktop, via: .lan, servers: servers, account: account) - } + actionButton( + "一键连接", + prominent: true, + enabled: canConnect && !busy, + inProgress: busy + ) { + flow.connect(.accountDesktop(desktop), servers: servers, account: account) } - if !notes.isEmpty { - Text(notes.joined(separator: " · ")) - .font(.caption) + Text(channelHint) + .font(.caption) + .foregroundStyle(.secondary) + } + } + + private var lanHostsSection: some View { + VStack(alignment: .leading, spacing: 6) { + if !desktops.isEmpty { + Text("当前 Wi-Fi 其他电脑") + .font(.caption.weight(.medium)) .foregroundStyle(.secondary) + .padding(.leading, 4) } + VStack(spacing: 0) { + ForEach(Array(extraLanHosts.enumerated()), id: \.element.id) { index, host in + if index > 0 { + Divider().padding(.leading, 14) + } + Button { + flow.connect(.lanHost(host), servers: servers, account: account) + } label: { + HStack(spacing: 10) { + Image(systemName: "wifi") + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.green) + Text(host.displayName) + .font(.system(size: 14.5, weight: .semibold)) + .foregroundStyle(.primary) + .lineLimit(1) + Spacer() + Text("对比连接码接入") + .font(.caption.weight(.semibold)) + .foregroundStyle(Color.accentColor) + } + .padding(.horizontal, 14) + .padding(.vertical, 12) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(flow.phase == .connecting) + } + } + .background(cardBackground) } } @@ -308,7 +506,7 @@ struct DesktopPickerSheet: View { Image(systemName: "desktopcomputer") .font(.system(size: 34, weight: .regular)) .foregroundStyle(Color.secondary) - Text("在电脑上安装 VibeX 并登录同一账号") + Text("在电脑上打开 VibeX 并登录同一账号,即可免确认直连") .font(.system(size: 15, weight: .semibold)) .multilineTextAlignment(.center) Button("下载 VibeX") { @@ -322,7 +520,7 @@ struct DesktopPickerSheet: View { } private var codePairingLink: some View { - Button("使用连接码配对") { + Button("扫码或输入 8 位连接码") { flow.switchToCodePairing() } .font(.system(size: 13)) diff --git a/App/InteractionEnhancer.swift b/App/InteractionEnhancer.swift index 9f97b16..8bd9df9 100644 --- a/App/InteractionEnhancer.swift +++ b/App/InteractionEnhancer.swift @@ -121,6 +121,7 @@ struct GlobalInteractionInstaller: UIViewRepresentable { private func enableInteractivePopInHierarchy(from root: UIViewController?) { guard let root else { return } if let nav = root as? UINavigationController { + nav.interactivePopGestureRecognizer?.delegate = nil nav.interactivePopGestureRecognizer?.isEnabled = nav.viewControllers.count > 1 } for child in root.children { diff --git a/App/KanbanUsageDashboardView.swift b/App/KanbanUsageDashboardView.swift index 450d7d7..2046287 100644 --- a/App/KanbanUsageDashboardView.swift +++ b/App/KanbanUsageDashboardView.swift @@ -4,28 +4,26 @@ import SwiftUI struct KanbanUsageDashboardView: View { let client: HostClient let projects: [ProjectSummary] - let initialProjectID: String? + @Binding var selectedTarget: String var refreshTrigger: Int = 0 - @State private var selectedTarget: String = "global" + private enum PrimaryMode: String, CaseIterable, Identifiable { + case overview = "用量概览" + case plan = "套餐额度" + var id: String { rawValue } + } + + @State private var mode: PrimaryMode = .overview @State private var dateRange: UsageDateRange = .sevenDays - @State private var activeTab: UsageDashboardTab = .overview @State private var statistics: ProjectUsageStatistics? @State private var isLoading = false @State private var errorMessage: String? - @State private var sessionSortBy: SessionUsageSort = .cost // Plan usage state @State private var selectedPlanAgent: PlanAgentDescriptor = PlanAgentDescriptor.all[0] @State private var planUsageByAgent: [String: PlanUsageResponse] = [:] @State private var isLoadingPlan = false - enum SessionUsageSort: String, CaseIterable, Identifiable { - case cost = "按费用" - case time = "按时间" - var id: String { rawValue } - } - struct PlanAgentDescriptor: Identifiable, Equatable { let id: String let title: String @@ -73,9 +71,8 @@ struct KanbanUsageDashboardView: View { var body: some View { VStack(spacing: 0) { filterHeader - Divider() - if activeTab == .plan { + if mode == .plan { planTabContent } else if isLoading && statistics == nil { UsageDashboardSkeletonView() @@ -87,264 +84,149 @@ struct KanbanUsageDashboardView: View { Spacer() } else if let stats = statistics { ScrollView { - VStack(spacing: 16) { - switch activeTab { - case .overview: - overviewContent(stats) - case .folders: - foldersContent(stats) - case .agents: - agentsContent(stats) - case .models: - modelsContent(stats) - case .sessions: - sessionsContent(stats) - case .plan: - EmptyView() - } + VStack(spacing: 14) { + overviewContent(stats) } - .padding(16) - .padding(.bottom, 76) + .padding(.horizontal, 16) + .padding(.top, 8) + .padding(.bottom, WorkspaceNavigationStore.bottomDockClearance + 16) } .refreshable { await reloadStatistics() } } else { Spacer() - ContentUnavailableView("暂无数据", systemImage: "chart.bar.xaxis") + ContentUnavailableView("暂无数据", systemImage: "chart.bar") Spacer() } } .task(id: "\(selectedTarget)-\(dateRange.rawValue)") { await reloadStatistics() } - .task(id: activeTab) { - if activeTab == .plan { + .task(id: mode) { + if mode == .plan { await loadPlanUsage(for: selectedPlanAgent.id) } } .onChange(of: refreshTrigger) { _, _ in Task { - if activeTab == .plan { + if mode == .plan { await loadPlanUsage(for: selectedPlanAgent.id, force: true) } else { await reloadStatistics() } } } - .onAppear { - if let initialProjectID, !initialProjectID.isEmpty, selectedTarget == "global" { - selectedTarget = "project:\(initialProjectID)" - } - } } - // MARK: - Unified Single Filter Row (Row 2) + // MARK: - Single Distilled Control Row (`用量概览 | 套餐额度` + Time Window) private var filterHeader: some View { - HStack(spacing: 6) { - // 1. Unified Dimension Dropdown (概览 / 项目 / Agent / 模型 / 会话 / 套餐) - Menu { - ForEach(UsageDashboardTab.allCases) { tab in - Button { - withAnimation(.easeInOut(duration: 0.18)) { - activeTab = tab - } - } label: { - HStack { - Label(tab.label, systemImage: tab.icon) - if activeTab == tab { - Image(systemName: "checkmark") - } - } - } - } - } label: { - HStack(spacing: 5) { - Image(systemName: activeTab.icon) - .font(.caption) - .foregroundStyle(Color.accentColor) - Text(activeTab.label) - .font(.subheadline.weight(.medium)) - .lineLimit(1) - Image(systemName: "chevron.down") - .font(.caption2) - .foregroundStyle(.secondary) + HStack(spacing: 10) { + Picker("统计视图", selection: $mode) { + ForEach(PrimaryMode.allCases) { item in + Text(item.rawValue).tag(item) } - .padding(.horizontal, 10) - .padding(.vertical, 6) - .background(Color(.secondarySystemGroupedBackground), in: Capsule()) - .overlay( - Capsule().strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.5) - ) } - .buttonStyle(.plain) + .pickerStyle(.segmented) - // 2. Scope Dropdown (全局 / 指定项目) right next to Dimension Dropdown - Menu { - Button { - selectedTarget = "global" - } label: { - HStack { - Text("全局") - if selectedTarget == "global" { Image(systemName: "checkmark") } - } - } - ForEach(projects.filter { !$0.isHome }) { project in - let target = "project:\(project.id)" - Button { - selectedTarget = target - } label: { - HStack { - Text(project.displayName) - if selectedTarget == target { Image(systemName: "checkmark") } + if mode == .overview { + Menu { + ForEach(UsageDateRange.allCases) { range in + Button { + dateRange = range + } label: { + HStack { + Text(range.label) + if dateRange == range { + Image(systemName: "checkmark") + } + } } } - } - } label: { - HStack(spacing: 5) { - Image(systemName: selectedTarget == "global" ? "globe" : "folder") - .font(.caption) - .foregroundStyle(.secondary) - Text(selectedTargetLabel) - .font(.subheadline.weight(.medium)) - .lineLimit(1) - Image(systemName: "chevron.down") - .font(.caption2) - .foregroundStyle(.secondary) - } - .padding(.horizontal, 10) - .padding(.vertical, 6) - .background(Color(.secondarySystemGroupedBackground), in: Capsule()) - .overlay( - Capsule().strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.5) - ) - } - .buttonStyle(.plain) - - Spacer(minLength: 6) - - if activeTab != .plan { - Picker("时间范围", selection: $dateRange) { - ForEach(UsageDateRange.allCases) { range in - Text(range.label).tag(range) + } label: { + HStack(spacing: 4) { + Text(dateRange.label) + .font(.subheadline.weight(.medium)) + .lineLimit(1) + Image(systemName: "chevron.down") + .font(.caption2.weight(.semibold)) + .foregroundStyle(.secondary) } + .foregroundStyle(.primary) + .padding(.horizontal, 11) + .padding(.vertical, 6.5) + .background( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) } - .pickerStyle(.segmented) - .frame(width: 148) + .buttonStyle(.plain) } } - .padding(.horizontal, 14) + .padding(.horizontal, 16) .padding(.vertical, 8) .background(Color(.systemGroupedBackground)) } - private var selectedTargetLabel: String { - if selectedTarget == "global" { return "全局" } - let id = selectedTarget.replacingOccurrences(of: "project:", with: "") - return projects.first { $0.id.lowercased() == id.lowercased() }?.displayName ?? "当前项目" - } - - // MARK: - Overview Tab + // MARK: - Distilled Overview Content @ViewBuilder private func overviewContent(_ stats: ProjectUsageStatistics) -> some View { let preferredTokens = stats.totalTokens.preferred - // Summary Metric Grid LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 10) { metricCard( title: "总费用", value: Self.formatCost(stats.resolvedCost), subtitle: stats.totalSessions > 0 && stats.resolvedCost != nil - ? "平均 \(Self.formatCost((stats.resolvedCost ?? 0) / Double(stats.totalSessions)))/会话" - : "按协议与日志估算", + ? "均 \(Self.formatCost((stats.resolvedCost ?? 0) / Double(stats.totalSessions))) / 会话" + : "按日志估算", icon: "dollarsign.circle.fill", tint: .green ) - metricCard( - title: "总会话", - value: "\(stats.totalSessions)", - subtitle: "\(stats.activeDaysCount) 个活跃日", - icon: "bubble.left.and.bubble.right.fill", - tint: .blue - ) metricCard( title: "总 Token", value: Self.formatTokens(preferredTokens.resolvedTotal), - subtitle: "平均每次 \(Self.formatTokens(stats.avgTokensPerSession)) Token", + subtitle: "均 \(Self.formatTokens(stats.avgTokensPerSession)) / 会话", icon: "cpu.fill", tint: .purple ) + metricCard( + title: "会话数", + value: "\(stats.totalSessions)", + subtitle: "\(stats.activeDaysCount) 个活跃日", + icon: "bubble.left.and.bubble.right.fill", + tint: .blue + ) metricCard( title: "缓存命中率", value: stats.cacheHitRatePercent.map { String(format: "%.1f%%", $0) } ?? "--", - subtitle: "缓存读取 \(Self.formatTokens(preferredTokens.cacheReadTokens ?? 0))", + subtitle: "读取 \(Self.formatTokens(preferredTokens.cacheReadTokens ?? 0))", icon: "bolt.horizontal.circle.fill", tint: .orange ) } - // Token Composition - VStack(alignment: .leading, spacing: 12) { - Text("Token 构成") - .font(.subheadline.weight(.semibold)) - - let total = max(1, Double(preferredTokens.resolvedTotal)) - let items: [(String, Int64, Color)] = [ - ("输入", preferredTokens.inputTokens ?? 0, .blue), - ("输出", preferredTokens.outputTokens ?? 0, .purple), - ("缓存写入", preferredTokens.cacheWriteTokens ?? 0, .orange), - ("缓存读取", preferredTokens.cacheReadTokens ?? 0, .green), - ] - - ForEach(items, id: \.0) { label, count, color in - VStack(spacing: 4) { - HStack { - Circle() - .fill(color) - .frame(width: 8, height: 8) - Text(label) - .font(.caption) - .foregroundStyle(.secondary) - Spacer() - Text(Self.formatTokens(count)) - .font(.caption.monospacedDigit().weight(.medium)) - } - GeometryReader { geo in - ZStack(alignment: .leading) { - Capsule() - .fill(Color(.systemFill)) - Capsule() - .fill(color) - .frame(width: max(4, geo.size.width * CGFloat(Double(count) / total))) - } - } - .frame(height: 6) - } - } - } - .padding(14) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14)) - - // Daily Trend if !stats.dailyUsage.isEmpty { - VStack(alignment: .leading, spacing: 12) { + VStack(alignment: .leading, spacing: 11) { HStack { - Text("用量趋势") + Text("每日趋势") .font(.subheadline.weight(.semibold)) Spacer() - Text("\(stats.dailyUsage.count) 天") + Text("近 \(min(stats.dailyUsage.count, 7)) 天") .font(.caption) + .monospacedDigit() .foregroundStyle(.secondary) } + let recentDays = Array(stats.dailyUsage.suffix(7).reversed()) let maxTokens = max( 1, - stats.dailyUsage.map { $0.tokens.preferred.resolvedTotal }.max() ?? 1 + recentDays.map { $0.tokens.preferred.resolvedTotal }.max() ?? 1 ) - ForEach(stats.dailyUsage.suffix(14).reversed()) { day in + ForEach(recentDays) { day in let dayTokens = day.tokens.preferred.resolvedTotal VStack(spacing: 4) { HStack { @@ -352,11 +234,9 @@ struct KanbanUsageDashboardView: View { .font(.caption.monospacedDigit()) .foregroundStyle(.secondary) Spacer() - Text("\(day.sessions) 会话") - .font(.caption2) - .foregroundStyle(.secondary) - Text("\(Self.formatTokens(dayTokens)) Token") + Text(Self.formatTokens(dayTokens)) .font(.caption.monospacedDigit().weight(.medium)) + .foregroundStyle(.primary) if let cost = day.cost { Text(Self.formatCost(cost)) .font(.caption.monospacedDigit()) @@ -381,237 +261,38 @@ struct KanbanUsageDashboardView: View { } } .padding(14) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14)) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14, style: .continuous)) } - // Top Models & Top Agents quick view if !stats.byModel.isEmpty { VStack(alignment: .leading, spacing: 10) { Text("常用模型") .font(.subheadline.weight(.semibold)) - ForEach(stats.byModel.prefix(5)) { item in - HStack(spacing: 6) { + + ForEach(Array(stats.byModel.prefix(6).enumerated()), id: \.element.id) { idx, item in + HStack(spacing: 8) { AgentModelLabel(agent: AgentBrand.inferAgent(fromModel: item.model), model: item.model) .font(.footnote.weight(.medium)) - Spacer() - Text("\(item.sessionCount) 会话") - .font(.caption) - .foregroundStyle(.secondary) + .lineLimit(1) + Spacer(minLength: 6) Text(Self.formatTokens(item.tokens.preferred.resolvedTotal)) .font(.caption.monospacedDigit()) .foregroundStyle(.secondary) if let cost = item.cost { Text(Self.formatCost(cost)) .font(.caption.monospacedDigit().weight(.semibold)) + .foregroundStyle(.primary) } } .padding(.vertical, 4) - } - } - .padding(14) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14)) - } - } - - // MARK: - Folders Tab - - @ViewBuilder - private func foldersContent(_ stats: ProjectUsageStatistics) -> some View { - if stats.byFolder.isEmpty { - ContentUnavailableView("暂无目录数据", systemImage: "folder") - .padding(.top, 40) - } else { - ForEach(stats.byFolder) { item in - let counts = item.tokens.preferred - VStack(alignment: .leading, spacing: 8) { - HStack { - Image(systemName: "folder.fill") - .foregroundStyle(.blue) - Text(item.displayName) - .font(.subheadline.weight(.semibold)) - .lineLimit(1) - Spacer() - if let cost = item.cost { - Text(Self.formatCost(cost)) - .font(.subheadline.monospacedDigit().weight(.semibold)) - .foregroundStyle(.green) - } - } - if let folder = item.folder, !folder.isEmpty { - Text(folder) - .font(.caption2) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.middle) - } - HStack(spacing: 12) { - Label("\(item.sessionCount) 会话", systemImage: "bubble.left.and.bubble.right") - Label("总 Token: \(Self.formatTokens(counts.resolvedTotal))", systemImage: "cpu") - Spacer() - } - .font(.caption) - .foregroundStyle(.secondary) - } - .padding(14) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14)) - } - } - } - - // MARK: - Agents Tab - - @ViewBuilder - private func agentsContent(_ stats: ProjectUsageStatistics) -> some View { - if stats.byAgent.isEmpty { - ContentUnavailableView("暂无 Agent 数据", systemImage: "bolt") - .padding(.top, 40) - } else { - ForEach(stats.byAgent) { item in - let counts = item.tokens.preferred - VStack(alignment: .leading, spacing: 8) { - HStack { - Image(systemName: "sparkles") - .foregroundStyle(.purple) - Text(item.displayName) - .font(.subheadline.weight(.semibold)) - Spacer() - if let cost = item.cost { - Text(Self.formatCost(cost)) - .font(.subheadline.monospacedDigit().weight(.semibold)) - .foregroundStyle(.green) - } - } - HStack(spacing: 12) { - Text("\(item.sessionCount) 会话") - Text("输入: \(Self.formatTokens(counts.inputTokens ?? 0))") - Text("输出: \(Self.formatTokens(counts.outputTokens ?? 0))") - Text("总计: \(Self.formatTokens(counts.resolvedTotal))") - } - .font(.caption) - .foregroundStyle(.secondary) - } - .padding(14) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14)) - } - } - } - - // MARK: - Models Tab - - @ViewBuilder - private func modelsContent(_ stats: ProjectUsageStatistics) -> some View { - if stats.byModel.isEmpty { - ContentUnavailableView("暂无模型数据", systemImage: "number") - .padding(.top, 40) - } else { - ForEach(stats.byModel) { item in - let counts = item.tokens.preferred - VStack(alignment: .leading, spacing: 8) { - HStack { - if let agent = AgentBrand.inferAgent(fromModel: item.model) { - AgentIconView(agent: agent, size: 18) - } else { - Image(systemName: "cube.transparent.fill") - .foregroundStyle(.indigo) - } - Text(item.model) - .font(.subheadline.weight(.semibold)) - .lineLimit(1) - Spacer() - if let cost = item.cost { - Text(Self.formatCost(cost)) - .font(.subheadline.monospacedDigit().weight(.semibold)) - .foregroundStyle(.green) - } - } - HStack(spacing: 12) { - Text("\(item.sessionCount) 会话") - Text("输入: \(Self.formatTokens(counts.inputTokens ?? 0))") - Text("输出: \(Self.formatTokens(counts.outputTokens ?? 0))") - Text("总 Token: \(Self.formatTokens(counts.resolvedTotal))") - } - .font(.caption) - .foregroundStyle(.secondary) - } - .padding(14) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14)) - } - } - } - - // MARK: - Sessions Tab - - @ViewBuilder - private func sessionsContent(_ stats: ProjectUsageStatistics) -> some View { - let sorted = stats.sessions.sorted { left, right in - switch sessionSortBy { - case .cost: - return (left.cost ?? -1) > (right.cost ?? -1) - case .time: - return left.timestamp > right.timestamp - } - } - - VStack(alignment: .leading, spacing: 12) { - HStack { - Text("会话列表 (\(sorted.count))") - .font(.subheadline.weight(.semibold)) - Spacer() - Picker("排序", selection: $sessionSortBy) { - ForEach(SessionUsageSort.allCases) { mode in - Text(mode.rawValue).tag(mode) - } - } - .pickerStyle(.segmented) - .frame(width: 140) - } - if sorted.isEmpty { - ContentUnavailableView("暂无会话数据", systemImage: "list.bullet") - .padding(.top, 32) - } else { - ForEach(sorted.prefix(50)) { item in - let counts = item.tokens.preferred - VStack(alignment: .leading, spacing: 6) { - HStack { - Text(item.displayTitle) - .font(.subheadline.weight(.medium)) - .lineLimit(1) - Spacer() - if let cost = item.cost { - Text(Self.formatCost(cost)) - .font(.footnote.monospacedDigit().weight(.semibold)) - .foregroundStyle(.green) - } - } - HStack(spacing: 8) { - if let agent = item.agentId, !agent.isEmpty { - HStack(spacing: 3) { - AgentIconView(agent: agent, size: 11) - Text(KanbanSessionSummary.formatAgentDisplayName(agent)) - } - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(Color.accentColor.opacity(0.12), in: Capsule()) - } - if let model = item.model, !model.isEmpty { - Text(model) - .lineLimit(1) - } - if let turns = item.turns, turns > 0 { - Text("\(turns) 轮次") - } - Text("\(Self.formatTokens(counts.resolvedTotal)) Token") - Spacer() - Text(BoardView.shortRelative(item.date)) - } - .font(.caption2) - .foregroundStyle(.secondary) + if idx < min(stats.byModel.count, 6) - 1 { + Divider() } - .padding(12) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 12)) } } + .padding(14) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14, style: .continuous)) } } @@ -619,7 +300,7 @@ struct KanbanUsageDashboardView: View { private var planTabContent: some View { ScrollView { - VStack(alignment: .leading, spacing: 16) { + VStack(alignment: .leading, spacing: 14) { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 8) { ForEach(PlanAgentDescriptor.all) { descriptor in @@ -632,16 +313,16 @@ struct KanbanUsageDashboardView: View { AgentIconView(agent: descriptor.id, size: 14) Text(KanbanSessionSummary.formatAgentDisplayName(descriptor.id)) } - .font(.footnote.weight(isSelected ? .semibold : .medium)) - .padding(.horizontal, 12) - .padding(.vertical, 7) - .foregroundStyle(isSelected ? Color.white : Color.primary) - .background( - isSelected - ? Color.accentColor - : Color(.secondarySystemGroupedBackground), - in: Capsule() - ) + .font(.footnote.weight(isSelected ? .semibold : .medium)) + .padding(.horizontal, 12) + .padding(.vertical, 7) + .foregroundStyle(isSelected ? Color.white : Color.primary) + .background( + isSelected + ? Color.accentColor + : Color(.secondarySystemGroupedBackground), + in: Capsule() + ) } .buttonStyle(.plain) } @@ -703,7 +384,7 @@ struct KanbanUsageDashboardView: View { } .padding(10) .frame(maxWidth: .infinity, alignment: .leading) - .background(Color(.tertiarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 10)) + .background(Color(.tertiarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 10, style: .continuous)) } case .unavailable: HStack(spacing: 8) { @@ -727,9 +408,14 @@ struct KanbanUsageDashboardView: View { } } .padding(16) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14)) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14, style: .continuous)) } - .padding(16) + .padding(.horizontal, 16) + .padding(.top, 8) + .padding(.bottom, WorkspaceNavigationStore.bottomDockClearance + 16) + } + .refreshable { + await loadPlanUsage(for: selectedPlanAgent.id, force: true) } } @@ -776,7 +462,7 @@ struct KanbanUsageDashboardView: View { .frame(height: 8) } .padding(12) - .background(Color(.tertiarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 10)) + .background(Color(.tertiarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 10, style: .continuous)) } // MARK: - Helpers @@ -804,12 +490,13 @@ struct KanbanUsageDashboardView: View { .minimumScaleFactor(0.75) Text(subtitle) .font(.caption2) + .monospacedDigit() .foregroundStyle(.secondary) .lineLimit(1) } .padding(12) .frame(maxWidth: .infinity, alignment: .leading) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14)) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14, style: .continuous)) } private func reloadStatistics() async { diff --git a/App/PairView.swift b/App/PairView.swift index 9e46b19..d59771b 100644 --- a/App/PairView.swift +++ b/App/PairView.swift @@ -1,26 +1,36 @@ import CompanionCore +import PhotosUI import SwiftUI import UIKit +import Vision struct PairView: View { @Environment(ServerStore.self) private var servers @Environment(\.dismiss) private var dismiss - var startWithScanner: Bool = false + var startWithScanner: Bool = true var initialOrigin: String? = nil + @State private var showingScanner: Bool + + init(startWithScanner: Bool = true, initialOrigin: String? = nil) { + self.startWithScanner = startWithScanner + self.initialOrigin = initialOrigin + _showingScanner = State(initialValue: startWithScanner) + } + var body: some View { NavigationStack { PairingCodeForm( - startWithScanner: startWithScanner, + showingScanner: $showingScanner, initialOrigin: initialOrigin, onPaired: { dismiss() } ) - .navigationTitle("使用连接码配对") + .navigationTitle(showingScanner ? "扫码配对" : "使用连接码配对") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { - Button("取消") { dismiss() } + Button("关闭") { dismiss() } } } .onAppear { servers.isPresentingPairSheet = true } @@ -29,60 +39,114 @@ struct PairView: View { } } -/// Pairs with a desktop through its one-time connection code or QR invitation; works without a VibeX account. +/// Unified single-page pairing view: squircle QR scanner at top with inline toggle to hide the +/// viewfinder and enter a connection code on the same page. struct PairingCodeForm: View { @Environment(ServerStore.self) private var servers - var startWithScanner: Bool = false + @Binding var showingScanner: Bool var initialOrigin: String? = nil var onPaired: () -> Void @State private var quickCode = "" - @State private var scanning = false @State private var submittingCode = false + @State private var awaitingLanSas: (hostName: String, sasCode: String)? + @State private var connectingLanHostId: String? + @State private var lanConnectTask: Task? @State private var localError: String? @State private var localMobileConflict: PendingMobileConflict? @State private var didAppear = false + @State private var selectedZoom: CGFloat = 1.5 + @State private var torchOn = false + @State private var selectedPhotoItem: PhotosPickerItem? + @State private var photoErrorMessage: String? + @State private var pendingCloudNodeChoiceInput: String? + + private var lanHosts: [DiscoveredLanHost] { + servers.discoveredHosts.filter { !$0.isCloudService } + } + var body: some View { - ScrollView { - VStack(spacing: 16) { - Spacer(minLength: 24) + VStack(spacing: 0) { + ScrollView { + VStack(spacing: 16) { + if showingScanner { + scannerCard + .transition(.opacity.combined(with: .scale(scale: 0.96))) + } else { + Spacer(minLength: 12) - Image(systemName: "qrcode.viewfinder") - .font(.system(size: 38, weight: .regular)) - .foregroundStyle(Color.secondary) + if let awaiting = awaitingLanSas { + lanSasComparisonCard(hostName: awaiting.hostName, sasCode: awaiting.sasCode) + } else if !lanHosts.isEmpty { + discoveredLanCard + } - inlineCodeAndScanCard + inlineCodeCard + .transition(.opacity.combined(with: .move(edge: .bottom))) + } - if let errorText = localError, !errorText.isEmpty { - HStack(spacing: 8) { - Image(systemName: "exclamationmark.triangle.fill") - .font(.footnote) - .foregroundStyle(.red) - Text(errorText) - .font(.footnote) - .foregroundStyle(.red) - .multilineTextAlignment(.leading) + if let errorText = localError, !errorText.isEmpty { + HStack(spacing: 8) { + Image(systemName: "exclamationmark.triangle.fill") + .font(.footnote) + .foregroundStyle(.red) + Text(errorText) + .font(.footnote) + .foregroundStyle(.red) + .multilineTextAlignment(.leading) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 14) + .padding(.vertical, 10) + .background( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(Color.red.opacity(0.08)) + ) } - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.horizontal, 14) - .padding(.vertical, 10) - .background( - RoundedRectangle(cornerRadius: 12, style: .continuous) - .fill(Color.red.opacity(0.08)) - ) } - - Spacer(minLength: 24) + .frame(maxWidth: 380) + .padding(.horizontal, 20) + .padding(.top, 12) + .padding(.bottom, 16) + .frame(maxWidth: .infinity) } - .frame(maxWidth: 380) - .padding(.horizontal, 24) - .frame(maxWidth: .infinity) + .scrollDismissesKeyboard(.interactively) + + bottomActionBar } - .scrollDismissesKeyboard(.interactively) .background(Color(.systemGroupedBackground)) - .fullScreenCover(isPresented: $scanning) { - scannerSheet + .onChange(of: selectedPhotoItem) { _, newValue in + guard let item = newValue else { return } + photoErrorMessage = nil + Task { + await detectQRCode(from: item) + } + } + .confirmationDialog( + "选择连接节点", + isPresented: Binding( + get: { pendingCloudNodeChoiceInput != nil }, + set: { if !$0 { pendingCloudNodeChoiceInput = nil } } + ), + titleVisibility: .visible + ) { + if let pendingInput = pendingCloudNodeChoiceInput { + Button("官方云服务") { + pendingCloudNodeChoiceInput = nil + executePair(input: pendingInput, cloudPreference: .official) + } + Button("自建云节点") { + let customOrigin = servers.customRelayOrigin + pendingCloudNodeChoiceInput = nil + executePair(input: pendingInput, cloudPreference: .custom(customOrigin)) + } + } + Button("取消", role: .cancel) { + pendingCloudNodeChoiceInput = nil + } + } message: { + Text("检测到你已配置自建云节点,请选择本次配对使用的云节点") } .alert( "选择要远程连接的手机", @@ -111,13 +175,359 @@ struct PairingCodeForm: View { .onAppear { guard !didAppear else { return } didAppear = true - if startWithScanner { - scanning = true + servers.discoverHosts() + } + .onDisappear { + torchOn = false + lanConnectTask?.cancel() + lanConnectTask = nil + } + } + + private var scannerCard: some View { + VStack(spacing: 20) { + QRScannerCameraRepresentable( + zoomFactor: $selectedZoom, + torchOn: $torchOn, + onCode: { code in + let generator = UINotificationFeedbackGenerator() + generator.notificationOccurred(.success) + let cleaned = code.trimmingCharacters(in: .whitespacesAndNewlines) + quickCode = cleaned + torchOn = false + submitQuickCode(overrideInput: cleaned) + }, + onFailure: { message in + localError = message + withAnimation(.spring(response: 0.32, dampingFraction: 0.88)) { + showingScanner = false + } + } + ) + .frame(width: 248, height: 248) + .clipShape(RoundedRectangle(cornerRadius: 46, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 46, style: .continuous) + .strokeBorder(Color.primary.opacity(0.82), lineWidth: 1.8) + ) + .shadow(color: .black.opacity(0.14), radius: 16, y: 6) + + Text("请扫描桌面端「远程连接」中的配对二维码") + .font(.system(size: 16, weight: .medium)) + .foregroundStyle(.primary.opacity(0.85)) + .multilineTextAlignment(.center) + .padding(.horizontal, 12) + + // 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(.systemBackground) : Color.primary) + .frame(width: 44, height: 30) + .background( + Capsule() + .fill(isSelected ? Color.primary : Color.primary.opacity(0.08)) + ) + } + .buttonStyle(.plain) + } + } + + if let photoErrorMessage { + Text(photoErrorMessage) + .font(.caption.weight(.medium)) + .foregroundStyle(.white) + .padding(.horizontal, 14) + .padding(.vertical, 8) + .background(Capsule().fill(Color.red.opacity(0.88))) } } + .padding(.vertical, 28) + .padding(.horizontal, 20) + .frame(maxWidth: .infinity) + .background( + RoundedRectangle(cornerRadius: 28, style: .continuous) + .fill(.ultraThinMaterial) + .overlay( + RoundedRectangle(cornerRadius: 28, style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.75) + ) + ) } - private var inlineCodeAndScanCard: some View { + private var bottomActionBar: some View { + HStack(spacing: 16) { + if showingScanner { + PhotosPicker(selection: $selectedPhotoItem, matching: .images) { + VStack(spacing: 6) { + ZStack { + Circle() + .fill(Color(.secondarySystemGroupedBackground)) + .frame(width: 50, height: 50) + .overlay(Circle().strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.75)) + Image(systemName: "photo.on.rectangle") + .font(.system(size: 19, weight: .semibold)) + .foregroundStyle(.primary) + } + Text("相册") + .font(.caption2.weight(.medium)) + .foregroundStyle(.secondary) + } + } + .buttonStyle(.plain) + + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + torchOn = false + photoErrorMessage = nil + withAnimation(.spring(response: 0.32, dampingFraction: 0.88)) { + showingScanner = false + } + } label: { + HStack(spacing: 8) { + Image(systemName: "keyboard") + .font(.system(size: 16, weight: .semibold)) + Text("使用连接码配对") + .font(.subheadline.weight(.semibold)) + } + .foregroundStyle(.primary) + .padding(.horizontal, 20) + .frame(height: 50) + .background( + Capsule() + .fill(Color(.secondarySystemGroupedBackground)) + .overlay( + Capsule() + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.75) + ) + ) + } + .buttonStyle(.plain) + + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + torchOn.toggle() + } label: { + VStack(spacing: 6) { + ZStack { + Circle() + .fill(torchOn ? Color.yellow : Color(.secondarySystemGroupedBackground)) + .frame(width: 50, height: 50) + .overlay(Circle().strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.75)) + Image(systemName: torchOn ? "flashlight.on.fill" : "flashlight.off.fill") + .font(.system(size: 19, weight: .semibold)) + .foregroundStyle(torchOn ? .black : .primary) + } + Text("手电筒") + .font(.caption2.weight(.medium)) + .foregroundStyle(.secondary) + } + } + .buttonStyle(.plain) + } else { + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + localError = nil + photoErrorMessage = nil + withAnimation(.spring(response: 0.32, dampingFraction: 0.88)) { + showingScanner = true + } + } label: { + HStack(spacing: 8) { + Image(systemName: "qrcode.viewfinder") + .font(.system(size: 16, weight: .semibold)) + Text("扫码配对") + .font(.subheadline.weight(.semibold)) + } + .foregroundStyle(.primary) + .padding(.horizontal, 22) + .frame(height: 50) + .background( + Capsule() + .fill(Color(.secondarySystemGroupedBackground)) + .overlay( + Capsule() + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.75) + ) + ) + } + .buttonStyle(.plain) + } + } + .padding(.top, 8) + .padding(.bottom, 22) + } + + @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 { + UINotificationFeedbackGenerator().notificationOccurred(.success) + let cleaned = detected.trimmingCharacters(in: .whitespacesAndNewlines) + quickCode = cleaned + torchOn = false + submitQuickCode(overrideInput: cleaned) + } else { + UINotificationFeedbackGenerator().notificationOccurred(.error) + photoErrorMessage = "未在图片中识别到二维码" + } + } + + private var discoveredLanCard: some View { + VStack(alignment: .leading, spacing: 8) { + Text("当前 Wi-Fi 发现电脑(免输码,对比连接码即连)") + .font(.caption.weight(.medium)) + .foregroundStyle(.secondary) + .padding(.leading, 4) + + VStack(spacing: 0) { + ForEach(Array(lanHosts.enumerated()), id: \.element.id) { index, host in + if index > 0 { + Divider().padding(.leading, 14) + } + let isBusy = connectingLanHostId == host.id + Button { + connectLanHost(host) + } label: { + HStack(spacing: 10) { + Image(systemName: "desktopcomputer") + .font(.system(size: 16, weight: .medium)) + .foregroundStyle(Color.accentColor) + Text(host.displayName) + .font(.system(size: 14.5, weight: .semibold)) + .foregroundStyle(.primary) + .lineLimit(1) + Spacer() + if isBusy { + ProgressView() + .controlSize(.small) + } else { + Text("连接") + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(.white) + .padding(.horizontal, 12) + .padding(.vertical, 6) + .background( + Capsule(style: .continuous) + .fill(Color.accentColor) + ) + } + } + .padding(.horizontal, 14) + .padding(.vertical, 11) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(connectingLanHostId != nil || submittingCode) + } + } + .background( + RoundedRectangle(cornerRadius: 14, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + .overlay( + RoundedRectangle(cornerRadius: 14, style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.75) + ) + ) + } + } + + private func lanSasComparisonCard(hostName: String, sasCode: String) -> some View { + VStack(spacing: 10) { + Text("连接「\(hostName)」") + .font(.system(size: 15, weight: .semibold)) + Text("对比电脑顶部显示的连接码一致后,点击「连接」") + .font(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + Text(sasCode) + .font(.system(size: 28, weight: .bold, design: .monospaced)) + .monospacedDigit() + .kerning(3) + .foregroundStyle(Color.accentColor) + Button("取消等待") { + lanConnectTask?.cancel() + lanConnectTask = nil + connectingLanHostId = nil + awaitingLanSas = nil + } + .font(.caption.weight(.medium)) + .foregroundStyle(.secondary) + .padding(.top, 2) + } + .frame(maxWidth: .infinity) + .padding(.horizontal, 16) + .padding(.vertical, 16) + .background( + RoundedRectangle(cornerRadius: 14, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + .overlay( + RoundedRectangle(cornerRadius: 14, style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.75) + ) + ) + } + + private func connectLanHost(_ host: DiscoveredLanHost, replaceExistingMobile: Bool = false) { + localError = nil + connectingLanHostId = host.id + lanConnectTask?.cancel() + lanConnectTask = Task { @MainActor in + defer { + connectingLanHostId = nil + awaitingLanSas = nil + } + do { + try await servers.connectViaAccountRequest( + origin: host.origin, + hostId: host.hostId.map(AccountDesktop.rawHostId) ?? "", + hostName: host.displayName, + deviceName: UIDevice.current.name, + accountToken: servers.accountStore?.token, + replaceExistingMobile: replaceExistingMobile, + onAwaitingApproval: { sasCode in + self.awaitingLanSas = (hostName: host.displayName, sasCode: sasCode) + } + ) + UINotificationFeedbackGenerator().notificationOccurred(.success) + } catch is CancellationError { + return + } catch let PairingError.mobileDeviceConflict(existingName) { + localMobileConflict = PendingMobileConflict( + existingDeviceName: existingName, + currentDeviceName: UIDevice.current.name + ) { + connectLanHost(host, replaceExistingMobile: true) + } + } catch { + UINotificationFeedbackGenerator().notificationOccurred(.error) + localError = ServerStore.sanitizeError(error) + } + } + } + + private var inlineCodeCard: some View { VStack(spacing: 10) { HStack(spacing: 8) { HStack(spacing: 6) { @@ -193,26 +603,6 @@ struct PairingCodeForm: View { .disabled(submittingCode) } } - - Button { - localError = nil - scanning = true - } label: { - HStack(spacing: 6) { - Image(systemName: "qrcode.viewfinder") - .font(.system(size: 15, weight: .semibold)) - Text("扫码配对") - .font(.system(size: 14.5, weight: .semibold)) - } - .foregroundStyle(.white) - .frame(maxWidth: .infinity) - .padding(.vertical, 10) - .background( - RoundedRectangle(cornerRadius: 9, style: .continuous) - .fill(Color.accentColor) - ) - } - .buttonStyle(.plain) } .padding(.horizontal, 12) .padding(.vertical, 10) @@ -226,42 +616,6 @@ struct PairingCodeForm: View { ) } - private var scannerSheet: some View { - NavigationStack { - QRScannerView( - onCode: { text in - let cleaned = text.trimmingCharacters(in: .whitespacesAndNewlines) - quickCode = cleaned - scanning = false - Task { @MainActor in - try? await Task.sleep(nanoseconds: 350_000_000) - submitQuickCode(overrideInput: cleaned) - } - }, - onFailure: { message in - localError = message - scanning = false - }, - onManualInputTap: { - scanning = false - } - ) - .ignoresSafeArea() - .navigationTitle("扫码配对") - .navigationBarTitleDisplayMode(.inline) - .toolbarBackground(.hidden, for: .navigationBar) - .toolbarColorScheme(.dark, for: .navigationBar) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("关闭") { - scanning = false - } - .foregroundStyle(.white) - } - } - } - } - private func pasteAndPairIfInvitation() { guard let pasted = UIPasteboard.general.string?.trimmingCharacters(in: .whitespacesAndNewlines), !pasted.isEmpty @@ -275,6 +629,15 @@ struct PairingCodeForm: View { private func submitQuickCode(overrideInput: String? = nil) { let input = (overrideInput ?? quickCode).trimmingCharacters(in: .whitespacesAndNewlines) + guard !input.isEmpty, !submittingCode else { return } + if servers.hasCustomRelayNode && servers.accountStore?.canUseCloudRelay == true { + pendingCloudNodeChoiceInput = input + return + } + executePair(input: input, cloudPreference: .auto) + } + + private func executePair(input: String, cloudPreference: CloudNodePreference) { guard !input.isEmpty, !submittingCode else { return } submittingCode = true localError = nil @@ -285,6 +648,7 @@ struct PairingCodeForm: View { input: input, manualOrigin: initialOrigin ?? "", deviceName: UIDevice.current.name, + cloudPreference: cloudPreference, onConflict: { conflict in localMobileConflict = conflict } diff --git a/App/PromptBar.swift b/App/PromptBar.swift index e1b71ea..ac560ac 100644 --- a/App/PromptBar.swift +++ b/App/PromptBar.swift @@ -1,4 +1,7 @@ +import AVFoundation +import Observation import PhotosUI +import Speech import SwiftUI import UIKit @@ -11,15 +14,6 @@ enum ComposerMenu: Equatable { case agent case model case effort - - var isBottomDrawer: Bool { - switch self { - case .access, .plusAgent, .plusModel, .plusMode, .plusPerms: - return true - case .agent, .model, .effort: - return false - } - } } struct PromptChoice: Identifiable, Equatable { @@ -57,8 +51,8 @@ struct AttachedImageItem: Identifiable, Equatable { } } -/// SwiftUI port of the PromptBar: one rounded dock, a tool row, floating menus for inline pills, -/// and an expandable bottom action drawer when tapping `+`. +/// Unified floating capsule composer (`[ + | TextField | AgentIcon ⌄ | Mic | Nested Circular ↑ ]`), +/// paired with `ThreadSettingsSheet` (`会话设置`). struct PromptBar: View { @Binding var draft: String @Binding var menu: ComposerMenu? @@ -75,8 +69,11 @@ struct PromptBar: View { let accessChoices: [PromptChoice] let extraChoices: [PromptChoice] let effort: PromptEffort? + var placeholder: String = "发消息或提问…" var openFiles: (() -> Void)? = nil + var onRefreshCatalog: (() -> Void)? = nil let send: () -> Void + var sendText: ((String) -> Void)? = nil let stop: () -> Void var pickAgent: ((String) -> Void)? = nil let pickModel: (String) -> Void @@ -86,36 +83,38 @@ struct PromptBar: View { let setEffort: (Int) -> Void @FocusState private var focused: Bool + @State private var localText = "" @State private var selectedPhotoItems: [PhotosPickerItem] = [] @State private var attachedImages: [AttachedImageItem] = [] @State private var previewingAttached: AttachedImageItem? @State private var showPhotoPicker = false @State private var showCameraSheet = false - @State private var showingCustomModelAlert = false - @State private var customModelDraft = "" + @State private var showThreadSettingsSheet = false + @State private var speech = SpeechDictationController() private let spark = Color(red: 0.70, green: 0.62, blue: 1.0) + private var armed: Bool { - isRunning || !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachedImages.isEmpty + isRunning || !localText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachedImages.isEmpty } + private var effortAtMax: Bool { guard let effort else { return false } return effort.levels.count > 1 && effort.index == effort.levels.count - 1 } - private var isPlusOpen: Bool { - menu?.isBottomDrawer == true - } var body: some View { - VStack(spacing: 8) { - if let menu, !menu.isBottomDrawer { - floatingMenuView(menu) - .padding(.horizontal, 12) - .transition(.scale(scale: 0.98, anchor: .bottom).combined(with: .opacity)) + VStack(spacing: 6) { + if let dictationError = speech.errorMessage { + Text(dictationError) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .padding(.horizontal, 16) + .transition(.opacity) } - dockSurface + + capsuleSurface } - .animation(.spring(response: 0.28, dampingFraction: 0.86), value: menu) .photosPicker( isPresented: $showPhotoPicker, selection: $selectedPhotoItems, @@ -137,7 +136,6 @@ struct PromptBar: View { } } selectedPhotoItems.removeAll() - menu = nil } } .sheet(isPresented: $showCameraSheet) { @@ -149,11 +147,33 @@ struct PromptBar: View { AttachedImageItem(token: token, image: captured, fileName: fileName) ) } - menu = nil } .ignoresSafeArea() } - .fullScreenCover(item: $previewingAttached) { item in + .sheet(isPresented: $showThreadSettingsSheet) { + ThreadSettingsSheet( + agentID: agentID, + agentName: agentName, + agentChoices: agentChoices, + modelChoices: modelChoices, + otherModelGroups: otherModelGroups, + otherAgentNote: otherAgentNote, + accessChoices: accessChoices, + extraChoices: extraChoices, + effort: effort, + pickAgent: pickAgent, + pickModel: pickModel, + onAddCustomModel: onAddCustomModel, + pickAccess: pickAccess, + pickExtra: pickExtra, + setEffort: setEffort, + onRefreshCatalog: onRefreshCatalog + ) + .presentationDetents([.large]) + .presentationDragIndicator(.visible) + .presentationCornerRadius(28) + } + .fullScreenCover(item: $previewingAttached) { item in ZoomableImagePreviewSheet( item: PreviewableImageItem( id: item.token, @@ -169,490 +189,352 @@ struct PromptBar: View { } ) } - .alert("自定义 / 中转模型", isPresented: $showingCustomModelAlert) { - TextField("输入模型 ID (如 claude-opus-4-8 / gpt-6-sol)", text: $customModelDraft) - .textInputAutocapitalization(.never) - .autocorrectionDisabled() - Button("取消", role: .cancel) { - customModelDraft = "" + .onAppear { + if localText != draft { + localText = draft } - Button("使用此模型") { - let trimmed = customModelDraft.trimmingCharacters(in: .whitespacesAndNewlines) - customModelDraft = "" - if !trimmed.isEmpty { - onAddCustomModel?(trimmed) - } + } + .onChange(of: draft) { _, externalDraft in + if externalDraft != localText { + localText = externalDraft } - } message: { - Text("如果你在电脑端连接了 API 中转或自建模型网关,可直接输入模型名称并在新对话中使用。") + } + .onChange(of: menu) { _, newValue in + if newValue != nil { + menu = nil + showThreadSettingsSheet = true + } + } + .onDisappear { + speech.stop() } } - // MARK: Dock Surface (Input Field + Bottom `+` Drawer) - - private var dockSurface: some View { - VStack(alignment: .leading, spacing: 0) { - VStack(alignment: .leading, spacing: 8) { - if !attachedImages.isEmpty { - ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 8) { - ForEach(attachedImages) { item in - ZStack(alignment: .topTrailing) { - Button { - previewingAttached = item - } label: { - Image(uiImage: item.image) - .resizable() - .scaledToFill() - .frame(width: 56, height: 56) - .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) - .overlay( - RoundedRectangle(cornerRadius: 10, style: .continuous) - .strokeBorder(Color.primary.opacity(0.12), lineWidth: 0.6) - ) - } - .buttonStyle(.plain) - - Button { - withAnimation { - attachedImages.removeAll { $0.id == item.id } - } - } label: { - Image(systemName: "xmark.circle.fill") - .font(.system(size: 16)) - .foregroundStyle(.white, Color.black.opacity(0.65)) + // MARK: - Unified Floating Capsule Surface + + private var capsuleSurface: some View { + VStack(alignment: .leading, spacing: 8) { + if !attachedImages.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + ForEach(attachedImages) { item in + ZStack(alignment: .topTrailing) { + Button { + previewingAttached = item + } label: { + Image(uiImage: item.image) + .resizable() + .scaledToFill() + .frame(width: 54, height: 54) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .strokeBorder(Color.primary.opacity(0.12), lineWidth: 0.6) + ) + } + .buttonStyle(.plain) + + Button { + withAnimation(.smooth(duration: 0.18)) { + attachedImages.removeAll { $0.id == item.id } } - .offset(x: 4, y: -4) + } label: { + Image(systemName: "xmark.circle.fill") + .font(.system(size: 16)) + .foregroundStyle(.white, Color.black.opacity(0.68)) } + .offset(x: 4, y: -4) } } - .padding(.top, 2) } + .padding(.horizontal, 6) + .padding(.top, 4) } + } + + HStack(alignment: .bottom, spacing: 6) { + attachmentMenuButton - TextField("发消息", text: $draft, axis: .vertical) + TextField(placeholder, text: $localText, axis: .vertical) .lineLimit(1...5) - .font(.system(size: 15.5)) + .font(.system(size: 16)) .focused($focused) - .onChange(of: focused) { _, isFocused in - if isFocused { menu = nil } - } - toolRow - } - .padding(.horizontal, 14) - .padding(.top, 11) - .padding(.bottom, 10) - .contentShape(Rectangle()) - .onTapGesture { focused = true } + .padding(.vertical, 7) + .frame(minHeight: 36) + + threadSettingsButton + + dictationButton - if let menu, menu.isBottomDrawer { - Divider().opacity(0.55) - bottomDrawerContent(menu) - .transition(.move(edge: .bottom).combined(with: .opacity)) + SendButton( + armed: armed, + running: isRunning, + busy: busy, + send: performSend, + stop: stop + ) } } + .padding(.leading, 10) + .padding(.trailing, 8) + .padding(.vertical, 8) .frame(maxWidth: .infinity) .background { - let dock = RoundedRectangle(cornerRadius: 22, style: .continuous) - ZStack { - dock.fill(Color(.secondarySystemGroupedBackground)) - dock - .fill(RadialGradient( - colors: [spark.opacity(0.24), .clear], - center: .bottomLeading, - startRadius: 0, - endRadius: 220 - )) - .opacity(effortAtMax ? 1 : 0) - .animation(.easeInOut(duration: 0.5), value: effortAtMax) - dock.strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.7) - } - .shadow(color: .black.opacity(0.05), radius: 10, x: 0, y: 3) + ComposerCapsuleBackground(effortAtMax: effortAtMax, spark: spark) + .equatable() } .padding(.horizontal, 14) .padding(.bottom, 8) } - private var effectiveModelChoices: [PromptChoice] { - guard onAddCustomModel != nil else { return modelChoices } - var rows = modelChoices - rows.append( - PromptChoice( - id: "__custom_model__", - title: "自定义 / 中转模型…", - detail: "手动输入模型 ID", - icon: "slider.horizontal.3", - selected: false, - enabled: true - ) - ) - return rows - } - - private func handleModelSelection(_ id: String) { - if id == "__custom_model__" { - menu = nil - customModelDraft = "" - showingCustomModelAlert = true - } else { - pickModel(id) - } - } - - private var toolRow: some View { - HStack(spacing: 5) { - ToolButton(icon: "plus", on: isPlusOpen, alert: hasAlert, label: "更多功能") { - focused = false - menu = isPlusOpen ? nil : .access - } - if !agentChoices.isEmpty, let agentName { - PickPill(on: menu == .agent || menu == .plusAgent, label: "选择 AI Agent") { - toggle(.agent) - } content: { - if agentID != nil { AgentIconView(agent: agentID, size: 13) } - Text(agentName).lineLimit(1) - Image(systemName: "chevron.down").font(.system(size: 9, weight: .bold)) - } + private var attachmentMenuButton: some View { + Menu { + Button { + showPhotoPicker = true + } label: { + Label("照片图库", systemImage: "photo.on.rectangle") } - if let modelName { - PickPill(on: menu == .model || menu == .plusModel, label: "选择模型") { - toggle(.model) - } content: { - if agentChoices.isEmpty { - if agentID != nil { AgentIconView(agent: agentID, size: 13) } - } else { - Image(systemName: "cpu").font(.system(size: 10.5, weight: .semibold)) - } - Text(modelName).lineLimit(1) - Image(systemName: "chevron.down").font(.system(size: 9, weight: .bold)) - } + + Button { + showCameraSheet = true + } label: { + Label("拍照", systemImage: "camera") } - if let effort { - PickPill(on: menu == .effort || menu == .plusMode, tint: effortAtMax ? spark : nil, label: "推理强度") { - toggle(.effort) - } content: { - Image(systemName: "sparkles").font(.system(size: 11, weight: .semibold)) - Text(effort.levels[effort.index]).lineLimit(1) + + if let openFiles { + Divider() + Button { + openFiles() + } label: { + Label("浏览项目文件", systemImage: "folder") } - .layoutPriority(1) } - Spacer(minLength: 0) - SendButton( - armed: armed, - running: isRunning, - busy: busy, - send: { - if !attachedImages.isEmpty { - let tokenTag = attachedImages.map { "#\($0.token)" }.joined(separator: " ") - let marker = "[图片附件 ×\(attachedImages.count) \(tokenTag)]" - if draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - draft = marker - } else { - draft += "\n\(marker)" - } - } - attachedImages.removeAll() - menu = nil - send() - }, - stop: stop - ) - } - .fixedSize(horizontal: false, vertical: true) - } - private func toggle(_ target: ComposerMenu) { - focused = false - menu = menu == target ? nil : target - } + Divider() - // MARK: Bottom Drawer (`+` Action Grid & Sub-panels) - - @ViewBuilder - private func bottomDrawerContent(_ kind: ComposerMenu) -> some View { - switch kind { - case .access: - plusActionGrid - case .plusAgent: - drawerSubpanel(title: "选择 AI Agent") { - DrawerChoiceList( - rows: agentChoices, - empty: "没有可用的 AI Agent", - select: { id in - pickAgent?(id) - menu = nil - } - ) - } - case .plusModel: - drawerSubpanel(title: "选择模型") { - DrawerChoiceList( - rows: effectiveModelChoices, - groups: otherModelGroups, - footnote: otherAgentNote, - empty: "电脑端没有配置可选模型", - select: handleModelSelection - ) - } - case .plusMode: - drawerSubpanel(title: "模式与推理") { - VStack(alignment: .leading, spacing: 12) { - if let effort { - EffortMenu(effort: effort, atMax: effortAtMax, spark: spark, change: setEffort) - } - let modeRows = modeAndExtraChoices - if !modeRows.isEmpty { - DrawerChoiceList( - rows: modeRows, - empty: "当前 Agent 无额外模式设置" - ) { id in - if accessChoices.contains(where: { $0.id == id }) { - pickAccess(id) - } else { - pickExtra(id) - } - } - } else if effort == nil { - Text("当前 Agent 没有提供模式设置") - .font(.system(size: 13)) - .foregroundStyle(.secondary) - .padding(.vertical, 16) - .frame(maxWidth: .infinity) + Button { + focused = false + showThreadSettingsSheet = true + } label: { + Label("会话与模型设置", systemImage: "slider.horizontal.3") + } + } label: { + Image(systemName: "plus") + .font(.system(size: 18, weight: .medium)) + .foregroundStyle(.primary.opacity(0.82)) + .frame(width: 34, height: 36) + .contentShape(Rectangle()) + .overlay(alignment: .topTrailing) { + if hasAlert { + Circle() + .fill(Color.orange) + .frame(width: 7, height: 7) + .offset(x: -2, y: 4) } } + } + .accessibilityLabel("添加附件或选项") + } + + private var threadSettingsButton: some View { + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + focused = false + onRefreshCatalog?() + showThreadSettingsSheet = true + } label: { + HStack(spacing: 4) { + AgentIconView(agent: agentID, size: 17) + Image(systemName: "chevron.down") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.secondary) } - case .plusPerms: - drawerSubpanel(title: "权限设置", accent: .orange) { - DrawerChoiceList( - rows: accessChoices, - empty: "当前 Agent 没有提供权限设置", - select: pickAccess - ) - } - default: - EmptyView() + .padding(.horizontal, 7) + .frame(height: 36) + .contentShape(Rectangle()) } - } - - private var modeAndExtraChoices: [PromptChoice] { - let planModes = accessChoices.filter { - $0.id.localizedCaseInsensitiveContains("plan") || $0.title.localizedCaseInsensitiveContains("plan") + .buttonStyle(PressStyle(scale: 0.94)) + .accessibilityLabel("会话设置(当前模型 \(modelName ?? "默认"))") + } + + private var dictationButton: some View { + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + speech.toggle(currentDraft: localText) { updatedText in + localText = updatedText + } + } label: { + Image(systemName: speech.isRecording ? "waveform.circle.fill" : "mic") + .font(.system(size: speech.isRecording ? 20 : 16.5, weight: .regular)) + .foregroundStyle(speech.isRecording ? Color.red : Color.primary.opacity(0.75)) + .symbolEffect(.pulse, isActive: speech.isRecording) + .frame(width: 32, height: 36) + .contentShape(Rectangle()) } - return planModes + extraChoices + .buttonStyle(PressStyle(scale: 0.92)) + .accessibilityLabel(speech.isRecording ? "停止语音输入" : "语音输入") } - private var plusActionGrid: some View { - let columns = Array(repeating: GridItem(.flexible(), spacing: 16), count: 4) - return LazyVGrid(columns: columns, spacing: 18) { - PlusGridTile(title: "相册", systemImage: "photo") { - showPhotoPicker = true - } - PlusGridTile(title: "拍摄", systemImage: "camera") { - showCameraSheet = true - } - PlusGridTile(title: "文件", systemImage: "at") { - menu = nil - openFiles?() - } - if !agentChoices.isEmpty { - PlusGridTile(title: "Agent", systemImage: "person.crop.rectangle.stack") { - menu = .plusAgent - } - } - PlusGridTile(title: "模型", systemImage: "cpu") { - menu = .plusModel - } - PlusGridTile(title: "模式", customIcon: .botMode) { - menu = .plusMode - } - PlusGridTile( - title: "权限", - systemImage: "exclamationmark.shield", - tint: .orange, - badge: hasAlert - ) { - menu = .plusPerms + private func performSend() { + if speech.isRecording { + speech.stop() + } + var composed = localText + if !attachedImages.isEmpty { + let tokenTag = attachedImages.map { "#\($0.token)" }.joined(separator: " ") + let marker = "[图片附件 ×\(attachedImages.count) \(tokenTag)]" + if composed.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + composed = marker + } else { + composed += "\n\(marker)" } } - .padding(.horizontal, 22) - .padding(.top, 18) - .padding(.bottom, 16) - } + let trimmed = composed.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } - private func drawerSubpanel( - title: String, - accent: Color = .primary, - @ViewBuilder content: () -> Content - ) -> some View { - VStack(alignment: .leading, spacing: 10) { - HStack(spacing: 8) { - Button { - menu = .access - } label: { - HStack(spacing: 4) { - Image(systemName: "chevron.left") - .font(.system(size: 12, weight: .bold)) - Text("返回") - .font(.system(size: 13, weight: .medium)) - } - .foregroundStyle(.secondary) - .padding(.vertical, 4) - .padding(.trailing, 8) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) + UIImpactFeedbackGenerator(style: .light).impactOccurred() + localText = "" + draft = "" + attachedImages.removeAll() + menu = nil - Spacer() + if let sendText { + sendText(trimmed) + } else { + draft = trimmed + send() + } + } +} - Text(title) - .font(.system(size: 13, weight: .semibold)) - .foregroundStyle(accent) +// MARK: - Live Speech Dictation Controller - Spacer() +@MainActor +@Observable +private final class SpeechDictationController { + var isRecording = false + var errorMessage: String? - // Balance back button width - Color.clear.frame(width: 44, height: 1) - } - .padding(.horizontal, 16) - .padding(.top, 10) + @ObservationIgnored private var audioEngine: AVAudioEngine? + @ObservationIgnored private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? + @ObservationIgnored private var recognitionTask: SFSpeechRecognitionTask? + @ObservationIgnored private var prefixText = "" - content() - .padding(.horizontal, 12) - .padding(.bottom, 12) + func toggle(currentDraft: String, onUpdate: @escaping @MainActor (String) -> Void) { + if isRecording { + stop() + return } - } + errorMessage = nil + let trimmedPrefix = currentDraft.trimmingCharacters(in: .whitespacesAndNewlines) + prefixText = trimmedPrefix.isEmpty ? "" : (currentDraft + " ") - // MARK: Floating Menus (for inline model / effort pills) - - @ViewBuilder - private func floatingMenuView(_ kind: ComposerMenu) -> some View { - Group { - switch kind { - case .agent: - MenuList( - rows: agentChoices, - empty: "没有可用的 AI Agent", - select: { id in - pickAgent?(id) - menu = nil + SFSpeechRecognizer.requestAuthorization { [weak self] status in + Task { @MainActor in + guard let self else { return } + guard status == .authorized else { + self.presentTemporaryError("请在系统设置中允许语音识别权限") + return + } + AVAudioApplication.requestRecordPermission { [weak self] micGranted in + Task { @MainActor in + guard let self else { return } + guard micGranted else { + self.presentTemporaryError("请在系统设置中允许麦克风权限") + return + } + self.startSession(onUpdate: onUpdate) } - ) - .frame(maxWidth: 250) - case .model: - MenuList( - rows: effectiveModelChoices, - groups: otherModelGroups, - footnote: otherAgentNote, - empty: "电脑端没有配置可选模型", - select: handleModelSelection - ) - .frame(maxWidth: 270) - case .effort: - if let effort { - EffortMenu(effort: effort, atMax: effortAtMax, spark: spark, change: setEffort) - .frame(maxWidth: 260) } - default: - EmptyView() } } - .frame(maxWidth: .infinity, alignment: .leading) } -} -// MARK: - Plus Action Grid Tile & Custom Bot Icon + private func startSession(onUpdate: @escaping @MainActor (String) -> Void) { + stop() -private enum CustomTileGlyph { - case botMode -} - -private struct PlusGridTile: View { - let title: String - var systemImage: String? = nil - var customIcon: CustomTileGlyph? = nil - var tint: Color? = nil - var badge: Bool = false - let action: () -> Void + let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "zh-CN")) + ?? SFSpeechRecognizer() + guard let recognizer, recognizer.isAvailable else { + presentTemporaryError("当前设备暂不支持实时语音转写") + return + } - var body: some View { - Button(action: action) { - VStack(spacing: 8) { - ZStack { - RoundedRectangle(cornerRadius: 16, style: .continuous) - .fill(Color.primary.opacity(0.06)) - .frame(width: 62, height: 62) - - if let customIcon { - switch customIcon { - case .botMode: - BotModeGlyph() - .stroke( - tint ?? Color.primary.opacity(0.82), - style: StrokeStyle(lineWidth: 2.0, lineCap: .round, lineJoin: .round) - ) - .frame(width: 26, height: 26) + do { + let audioSession = AVAudioSession.sharedInstance() + try audioSession.setCategory(.record, mode: .measurement, options: .duckOthers) + try audioSession.setActive(true, options: .notifyOthersOnDeactivation) + + let engine = AVAudioEngine() + let request = SFSpeechAudioBufferRecognitionRequest() + request.shouldReportPartialResults = true + + let inputNode = engine.inputNode + let format = inputNode.outputFormat(forBus: 0) + inputNode.removeTap(onBus: 0) + inputNode.installTap(onBus: 0, bufferSize: 1024, format: format) { buffer, _ in + request.append(buffer) + } + + engine.prepare() + try engine.start() + + self.audioEngine = engine + self.recognitionRequest = request + self.isRecording = true + + let basePrefix = prefixText + self.recognitionTask = recognizer.recognitionTask(with: request) { [weak self] result, error in + Task { @MainActor in + guard let self else { return } + if let result { + let spoken = result.bestTranscription.formattedString + if !spoken.isEmpty { + onUpdate(basePrefix + spoken) + } + if result.isFinal { + self.stop() } - } else if let systemImage { - Image(systemName: systemImage) - .font(.system(size: 23, weight: .regular)) - .foregroundStyle(tint ?? Color.primary.opacity(0.82)) } - } - .overlay(alignment: .topTrailing) { - if badge { - Circle() - .fill(Color.orange) - .frame(width: 8, height: 8) - .offset(x: -2, y: 2) + if error != nil { + self.stop() } } - - Text(title) - .font(.system(size: 12, weight: .medium)) - .foregroundStyle(tint ?? .secondary) - .lineLimit(1) } - .frame(maxWidth: .infinity) - .contentShape(Rectangle()) + } catch { + stop() + presentTemporaryError("无法启动麦克风录音") } - .buttonStyle(PressStyle(scale: 0.94)) } -} -/// Cute rounded-square robot head with antenna, matching the "模式" icon in the mobile design. -private struct BotModeGlyph: Shape { - func path(in rect: CGRect) -> Path { - let w = rect.width - let h = rect.height - var p = Path() - - // Antenna stem + crossbar - p.move(to: CGPoint(x: w * 0.50, y: h * 0.24)) - p.addLine(to: CGPoint(x: w * 0.50, y: h * 0.08)) - p.move(to: CGPoint(x: w * 0.36, y: h * 0.08)) - p.addLine(to: CGPoint(x: w * 0.64, y: h * 0.08)) - - // Rounded head box - let headRect = CGRect(x: w * 0.12, y: h * 0.24, width: w * 0.76, height: h * 0.66) - p.addRoundedRect(in: headRect, cornerSize: CGSize(width: w * 0.20, height: h * 0.20)) - - // Eyes - p.move(to: CGPoint(x: w * 0.36, y: h * 0.48)) - p.addLine(to: CGPoint(x: w * 0.36, y: h * 0.53)) - p.move(to: CGPoint(x: w * 0.64, y: h * 0.48)) - p.addLine(to: CGPoint(x: w * 0.64, y: h * 0.53)) - - // Smile arc - p.move(to: CGPoint(x: w * 0.36, y: h * 0.69)) - p.addQuadCurve( - to: CGPoint(x: w * 0.64, y: h * 0.69), - control: CGPoint(x: w * 0.50, y: h * 0.77) - ) - return p + func stop() { + if let engine = audioEngine { + engine.stop() + engine.inputNode.removeTap(onBus: 0) + } + recognitionRequest?.endAudio() + recognitionTask?.cancel() + audioEngine = nil + recognitionRequest = nil + recognitionTask = nil + if isRecording { + isRecording = false + try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) + } + } + + private func presentTemporaryError(_ text: String) { + errorMessage = text + Task { @MainActor [weak self] in + try? await Task.sleep(for: .seconds(2.8)) + if self?.errorMessage == text { + self?.errorMessage = nil + } + } } } -// MARK: - Camera Capture Fallback Sheet +// MARK: - Camera Capture Sheet private struct CameraCaptureSheet: UIViewControllerRepresentable { let onFinish: (UIImage?) -> Void @@ -688,57 +570,32 @@ private struct CameraCaptureSheet: UIViewControllerRepresentable { } } -// MARK: - Controls +// MARK: - Controls & Animated Send Glyph -private struct ToolButton: View { - let icon: String - let on: Bool - var alert = false - let label: String - let action: () -> Void - - var body: some View { - Button(action: action) { - Image(systemName: icon) - .font(.system(size: 14.5, weight: .semibold)) - .rotationEffect(.degrees(on ? 45 : 0)) - .frame(width: 30, height: 30) - .background( - on ? Color.primary.opacity(0.14) : Color.primary.opacity(0.055), - in: Circle() - ) - .foregroundStyle(on ? Color.primary : Color.primary.opacity(0.75)) - .overlay(alignment: .topTrailing) { - if alert { Circle().fill(.orange).frame(width: 8, height: 8).offset(x: 1, y: -1) } - } - .animation(.spring(duration: 0.25), value: on) - } - .buttonStyle(PressStyle(scale: 0.94)) - .accessibilityLabel(label) - } -} - -private struct PickPill: View { - let on: Bool - var tint: Color? - let label: String - let action: () -> Void - @ViewBuilder let content: () -> Content +private struct ComposerCapsuleBackground: View, Equatable { + let effortAtMax: Bool + let spark: Color var body: some View { - Button(action: action) { - HStack(spacing: 5, content: content) - .font(.system(size: 12.5, weight: .medium)) - .padding(.horizontal, 10) - .frame(height: 30) - .background( - on ? Color.primary.opacity(0.12) : Color.primary.opacity(0.05), - in: Capsule(style: .continuous) - ) - .foregroundStyle(tint ?? (on ? Color.primary : Color.primary.opacity(0.8))) + let pill = RoundedRectangle(cornerRadius: 26, style: .continuous) + ZStack { + pill.fill(Color(.secondarySystemGroupedBackground)) + if effortAtMax { + pill + .fill( + RadialGradient( + colors: [spark.opacity(0.22), .clear], + center: .bottomLeading, + startRadius: 0, + endRadius: 210 + ) + ) + .transition(.opacity) + } + pill.strokeBorder(Color.primary.opacity(0.09), lineWidth: 0.75) } - .buttonStyle(PressStyle(scale: 0.96)) - .accessibilityLabel(label) + .shadow(color: .black.opacity(0.08), radius: 14, x: 0, y: 4) + .animation(.easeInOut(duration: 0.35), value: effortAtMax) } } @@ -763,22 +620,20 @@ private struct SendButton: View { Button(action: running ? stop : send) { SendGlyph(morph: running ? 1 : 0) .frame(width: 15, height: 15) - .frame(width: 30, height: 30) - .foregroundStyle(armed ? Color(.systemBackground) : Color.primary.opacity(0.32)) + .frame(width: 36, height: 36) + .foregroundStyle(armed ? Color(.systemBackground) : Color.primary.opacity(0.36)) .background( - armed ? Color.primary : Color.primary.opacity(0.07), + armed ? Color.primary : Color.primary.opacity(0.08), in: Circle() ) - .animation(.easeOut(duration: 0.2), value: armed) + .animation(.easeOut(duration: 0.18), value: armed) } - .buttonStyle(PressStyle(scale: armed ? 0.95 : 1)) + .buttonStyle(PressStyle(scale: armed ? 0.94 : 1)) .disabled(!armed || (busy && !running)) .accessibilityLabel(running ? "停止" : "发送") } } -// MARK: - Send glyph (arrow morphs into a stop square) - private let arrowPoints: [CGPoint] = [ (12, 4.5), (18.5, 11), (14.25, 11), (14.25, 19.5), (9.75, 19.5), (9.75, 11), (5.5, 11), ].map { CGPoint(x: $0.0, y: $0.1) } @@ -809,7 +664,6 @@ private struct GlyphShape: Shape { } } -/// Squash and tilt while morphing, peaking halfway through. private struct GooEffect: GeometryEffect { var t: Double var direction: Double @@ -841,258 +695,11 @@ private struct SendGlyph: View { } } -// MARK: - Menus & Lists - -private struct DrawerChoiceList: View { - let rows: [PromptChoice] - var groups: [PromptGroup] = [] - var footnote: String? - let empty: String - let select: (String) -> Void - - private var estimatedHeight: CGFloat { - CGFloat(rows.count) * 40 - + groups.reduce(0) { $0 + 30 + CGFloat($1.choices.count) * 40 } - + (footnote == nil ? 0 : 40) - } - - var body: some View { - if rows.isEmpty && groups.isEmpty { - Text(empty) - .font(.system(size: 13)) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity) - .padding(.vertical, 16) - } else { - ScrollView { - VStack(spacing: 2) { - ForEach(rows) { row in - MenuRow(row: row) { select(row.id) } - } - ForEach(groups) { group in - HStack(spacing: 5) { - if group.agentID != nil { AgentIconView(agent: group.agentID, size: 12) } - Text(group.title) - } - .font(.system(size: 11, weight: .medium)) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.horizontal, 8) - .padding(.top, 8) - ForEach(group.choices) { row in MenuRow(row: row) { select(row.id) } } - } - if let footnote { - Text(footnote) - .font(.system(size: 11)) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(8) - } - } - } - .frame(maxHeight: min(estimatedHeight, 240)) - } - } -} - -private struct MenuList: View { - let rows: [PromptChoice] - var groups: [PromptGroup] = [] - var footnote: String? - let empty: String - let select: (String) -> Void - - private var estimatedHeight: CGFloat { - CGFloat(rows.count) * 36 - + groups.reduce(0) { $0 + 28 + CGFloat($1.choices.count) * 36 } - + (footnote == nil ? 0 : 40) - } - - var body: some View { - MenuSurface { - if rows.isEmpty && groups.isEmpty { - Text(empty) - .font(.system(size: 12)) - .foregroundStyle(.secondary) - .frame(height: 36) - .padding(.horizontal, 8) - } else { - ScrollView { - VStack(spacing: 0) { - ForEach(rows) { row in MenuRow(row: row) { select(row.id) } } - ForEach(groups) { group in - HStack(spacing: 5) { - if group.agentID != nil { AgentIconView(agent: group.agentID, size: 12) } - Text(group.title) - } - .font(.system(size: 11, weight: .medium)) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.horizontal, 8) - .padding(.top, 8) - ForEach(group.choices) { row in MenuRow(row: row) { select(row.id) } } - } - if let footnote { - Text(footnote) - .font(.system(size: 11)) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(8) - } - } - } - .frame(height: min(estimatedHeight, 300)) - } - } - } -} - -private struct MenuRow: View { - let row: PromptChoice - let action: () -> Void - - var body: some View { - Button(action: action) { - HStack(spacing: 10) { - if row.agentID != nil { - AgentIconView(agent: row.agentID, size: 16) - .frame(width: 20) - .opacity(row.enabled ? 1 : 0.5) - } else if let icon = row.icon { - Image(systemName: icon) - .font(.system(size: 14)) - .frame(width: 20) - .foregroundStyle(.secondary) - } - Text(row.title).font(.system(size: 13, weight: .medium)).lineLimit(1) - if let detail = row.detail, !detail.isEmpty { - Text(detail) - .font(.system(size: 12)) - .foregroundStyle(.secondary) - .lineLimit(1) - } - Spacer(minLength: 0) - if let tag = row.tag { - Text(tag).font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1) - } - Image(systemName: "checkmark") - .font(.system(size: 11, weight: .heavy)) - .opacity(row.selected ? 1 : 0) - } - .padding(.horizontal, 8) - .frame(height: 36) - .contentShape(Rectangle()) - .foregroundStyle(row.enabled ? Color.primary : Color.primary.opacity(0.4)) - } - .buttonStyle(RowStyle()) - .disabled(!row.enabled) - } -} - -private struct RowStyle: ButtonStyle { - func makeBody(configuration: Configuration) -> some View { - configuration.label - .background( - configuration.isPressed ? Color.primary.opacity(0.08) : .clear, - in: RoundedRectangle(cornerRadius: 8) - ) - } -} - -private struct MenuSurface: View { - @ViewBuilder let content: () -> Content - - var body: some View { - content() - .padding(4) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 12)) - .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.primary.opacity(0.06))) - .shadow(color: .black.opacity(0.08), radius: 10, y: 2) - } -} - -private struct EffortMenu: View { - let effort: PromptEffort - let atMax: Bool - let spark: Color - let change: (Int) -> Void - - var body: some View { - VStack(alignment: .leading, spacing: 0) { - HStack(spacing: 8) { - Text("推理强度").foregroundStyle(.secondary) - Text(effort.levels[effort.index]).fontWeight(.medium) - Spacer() - } - .font(.system(size: 13)) - HStack { - Text("更快") - Spacer() - Text("更强") - } - .font(.system(size: 12)) - .foregroundStyle(.secondary) - .padding(.top, 12) - EffortSlider(levels: effort.levels.count, index: effort.index, atMax: atMax, spark: spark, change: change) - .padding(.top, 8) - } - .padding(.horizontal, 14) - .padding(.top, 12) - .padding(.bottom, 14) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 12)) - .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.primary.opacity(0.06))) - .shadow(color: .black.opacity(0.08), radius: 10, y: 2) - } -} - -private struct EffortSlider: View { - let levels: Int - let index: Int - let atMax: Bool - let spark: Color - let change: (Int) -> Void - - private let edge: CGFloat = 11 - - var body: some View { - GeometryReader { geo in - let usable = max(1, geo.size.width - 2 * edge) - let steps = CGFloat(max(1, levels - 1)) - let x = { (i: Int) in edge + usable * CGFloat(i) / steps } - ZStack(alignment: .leading) { - Capsule().fill(Color.primary.opacity(0.08)) - Capsule() - .fill(atMax ? spark.opacity(0.35) : Color.primary.opacity(0.18)) - .frame(width: index == levels - 1 ? geo.size.width : x(index) + 7) - ForEach(0.. Void diff --git a/App/RequiresServer.swift b/App/RequiresServer.swift index 63081f1..84025d3 100644 --- a/App/RequiresServer.swift +++ b/App/RequiresServer.swift @@ -1,7 +1,7 @@ import CompanionCore import SwiftUI -/// Gate for tabs that read from the paired computer. +/// Gate for destinations that read from the paired computer. struct RequiresServer: View { @Environment(ServerStore.self) private var servers @Binding var selection: AppTab @@ -28,7 +28,9 @@ struct ConnectComputerEmptyState: View { var body: some View { VStack(spacing: 16) { - if isSyncingAccount { + if connectFlow.isAutoConnectingInBackground { + LoadingState(label: "正在连接「\(connectFlow.autoConnectingHostName ?? "你的电脑")」") + } else if isSyncingAccount { LoadingState(label: "正在同步你的电脑") } else { Image(systemName: "desktopcomputer") @@ -59,6 +61,7 @@ struct ConnectComputerEmptyState: View { } } .padding(.horizontal, 24) + .padding(.bottom, WorkspaceNavigationStore.bottomDockClearance) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color(.systemGroupedBackground)) } @@ -66,7 +69,11 @@ struct ConnectComputerEmptyState: View { private func connect() { servers.pairingError = nil if account.isSignedIn { - connectFlow.presentPicker(servers: servers) + if account.desktops.count == 1, let only = account.desktops.first { + connectFlow.connect(.accountDesktop(only), servers: servers, account: account, silentUntilNeeded: true) + } else { + connectFlow.presentPicker(servers: servers) + } } else if let profile = servers.activeProfile, servers.client(for: profile) != nil { servers.connectSavedProfile(profile) } else { diff --git a/App/RootTabView.swift b/App/RootTabView.swift index fc262e3..f52c1b2 100644 --- a/App/RootTabView.swift +++ b/App/RootTabView.swift @@ -1,6 +1,5 @@ import CompanionCore import SwiftUI -import UIKit enum AppTab: Hashable, CaseIterable, Identifiable { case conversations @@ -12,17 +11,27 @@ enum AppTab: Hashable, CaseIterable, Identifiable { var title: String { switch self { - case .conversations: return "对话" + case .conversations: return "会话" case .board: return "看板" - case .space: return "协作空间" + case .space: return "协作" case .settings: return "设置" } } + func localizedTitle(english: Bool) -> String { + guard english else { return title } + switch self { + case .conversations: return "Chats" + case .board: return "Board" + case .space: return "Collab" + case .settings: return "Settings" + } + } + var icon: String { switch self { - case .conversations: return "message" - case .board: return "square.grid.2x2" + case .conversations: return "bubble.left" + case .board: return "chart.bar" case .space: return "person.2" case .settings: return "gearshape" } @@ -30,8 +39,8 @@ enum AppTab: Hashable, CaseIterable, Identifiable { var selectedIcon: String { switch self { - case .conversations: return "message.fill" - case .board: return "square.grid.2x2.fill" + case .conversations: return "bubble.left.fill" + case .board: return "chart.bar.fill" case .space: return "person.2.fill" case .settings: return "gearshape.fill" } @@ -41,137 +50,94 @@ enum AppTab: Hashable, CaseIterable, Identifiable { struct RootTabView: View { @Environment(ServerStore.self) private var servers @Environment(AppAppearanceStore.self) private var appearance - @Namespace private var tabNamespace - @State private var selection: AppTab = .conversations + @State private var navStore = WorkspaceNavigationStore() @State private var attentionCenter = CompanionAttentionCenter() - @State private var isConversationsChromeHidden = false - @State private var isBoardChromeHidden = false - @State private var isSpaceChromeHidden = false - @State private var isLaunchRevealed = false - @State private var isKeyboardVisible = false + @State private var visitedTabs: Set = [.conversations] private var activeClient: HostClient? { guard let profile = servers.activeProfile else { return nil } return servers.client(for: profile) } - private var shouldShowBottomBar: Bool { - if isKeyboardVisible { return false } - switch selection { - case .conversations: - return !isConversationsChromeHidden - case .board: - return !isBoardChromeHidden - case .space: - return !isSpaceChromeHidden - case .settings: - return true + /// Ensures the floating dock is also hidden when disconnected on a server-backed tab? + /// Wait: on Level 1 (`isCurrentTabAtRoot`), even when disconnected, keeping the floating dock + /// visible lets the user switch between `会话 / 看板 / 协作 / 设置` freely! + /// And when disconnected, `conversationsDepth / boardDepth / spaceDepth` reset to 0. + private var shouldShowFloatingDock: Bool { + if activeClient == nil || !servers.isSessionConnected { + return navStore.selection != .settings || navStore.settingsDepth == 0 } - } - - private var isBottomBarRevealed: Bool { - isLaunchRevealed || servers.activeProfile == nil || selection != .conversations + return navStore.isCurrentTabAtRoot } var body: some View { - ZStack(alignment: .bottom) { - ZStack { - RequiresServer(selection: $selection) { client in - ConversationsView( - client: client, - onChromeHiddenChange: { hidden in - withAnimation(.smooth(duration: 0.2)) { - isConversationsChromeHidden = hidden - } - }, - onLaunchRevealedChange: { revealed in - withAnimation(.spring(response: 1.05, dampingFraction: 0.86, blendDuration: 0.2)) { - isLaunchRevealed = revealed - } - }, - onSelectTab: { targetTab in - withAnimation(.smooth(duration: 0.16)) { - selection = targetTab - } - } - ) - } - .opacity(selection == .conversations ? 1 : 0) - .allowsHitTesting(selection == .conversations) + @Bindable var bindableNav = navStore + ZStack { + RequiresServer(selection: $bindableNav.selection) { client in + ConversationsView(client: client, selection: $bindableNav.selection) + } + .opacity(navStore.selection == .conversations ? 1 : 0) + .allowsHitTesting(navStore.selection == .conversations) - if selection == .board { - RequiresServer(selection: $selection) { - BoardView( - client: $0, - onChromeHiddenChange: { hidden in - withAnimation(.smooth(duration: 0.2)) { - isBoardChromeHidden = hidden - } - } - ) - } - .transition(.opacity) - } else if selection == .space { - RequiresServer(selection: $selection) { - CollaborationSpaceView( - client: $0, - onChromeHiddenChange: { hidden in - withAnimation(.smooth(duration: 0.2)) { - isSpaceChromeHidden = hidden - } - } - ) - } - .transition(.opacity) - } else if selection == .settings { - SettingsView() - .transition(.opacity) + if visitedTabs.contains(.board) || navStore.selection == .board { + RequiresServer(selection: $bindableNav.selection) { client in + BoardView(client: client) } + .opacity(navStore.selection == .board ? 1 : 0) + .allowsHitTesting(navStore.selection == .board) } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .safeAreaInset(edge: .bottom, spacing: 0) { - if shouldShowBottomBar { - Color.clear.frame(height: 66) + if visitedTabs.contains(.space) || navStore.selection == .space { + RequiresServer(selection: $bindableNav.selection) { client in + CollaborationSpaceView(client: client) } + .opacity(navStore.selection == .space ? 1 : 0) + .allowsHitTesting(navStore.selection == .space) } - - if shouldShowBottomBar { - bottomNavigationBar - .opacity(isBottomBarRevealed ? 1 : 0) - .offset(y: isBottomBarRevealed ? 0 : 36) - .blur(radius: isBottomBarRevealed ? 0 : 3) - .allowsHitTesting(isBottomBarRevealed) - .transition(.move(edge: .bottom).combined(with: .opacity)) + if visitedTabs.contains(.settings) || navStore.selection == .settings { + SettingsView() + .opacity(navStore.selection == .settings ? 1 : 0) + .allowsHitTesting(navStore.selection == .settings) } } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .environment(navStore) .environment(attentionCenter) + .overlay(alignment: .bottom) { + if shouldShowFloatingDock { + FloatingWorkspaceCapsuleDock(navStore: navStore) + .transition(.move(edge: .bottom).combined(with: .opacity)) + } + } + .animation(.spring(response: 0.30, dampingFraction: 0.86), value: shouldShowFloatingDock) .overlay(alignment: .top) { - if let client = activeClient { - CompanionToastOverlay( - client: client, - center: attentionCenter, - onOpenConversation: { conversation in - selection = .conversations - attentionCenter.openConversation(conversation) + VStack(spacing: 8) { + if let sasNotice = servers.connectedSasNotice { + ConnectedSasCapsuleView(notice: sasNotice) { + withAnimation(.easeOut(duration: 0.18)) { + servers.dismissConnectedSasNotice() + } } - ) + .padding(.top, 6) + .transition(.move(edge: .top).combined(with: .opacity)) + } + if let client = activeClient { + CompanionToastOverlay( + client: client, + center: attentionCenter, + onOpenConversation: { conversation in + navStore.selection = .conversations + attentionCenter.openConversation(conversation) + } + ) + } } + .animation(.spring(response: 0.30, dampingFraction: 0.86), value: servers.connectedSasNotice) } .task(id: servers.activeProfile?.id) { guard let client = activeClient else { return } while !Task.isCancelled { await attentionCenter.poll(client: client) - try? await Task.sleep(for: .milliseconds(1500)) - } - } - .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in - withAnimation(.easeOut(duration: 0.18)) { - isKeyboardVisible = true - } - } - .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in - withAnimation(.easeOut(duration: 0.18)) { - isKeyboardVisible = false + try? await Task.sleep(for: .milliseconds(3500)) } } .dynamicTypeSize(appearance.fontSizePreset.dynamicTypeSize) @@ -180,7 +146,8 @@ struct RootTabView: View { .onAppear { appearance.applyInterfaceStyleToAllWindows(appearance.themeMode.uiInterfaceStyle) } - .onChange(of: selection) { _, newTab in + .onChange(of: navStore.selection) { _, newTab in + visitedTabs.insert(newTab) dismissKeyboard() if newTab == .conversations { NotificationCenter.default.post(name: Notification.Name("vibex.didReturnToConversationsTab"), object: nil) @@ -192,67 +159,50 @@ struct RootTabView: View { .allowsHitTesting(false) ) } +} - private var bottomNavigationBar: some View { - HStack(spacing: 4) { - ForEach(AppTab.allCases) { tab in - let isSelected = selection == tab - Button { - if selection != tab { - UIImpactFeedbackGenerator(style: .light).impactOccurred() - withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { - selection = tab - } - } - } label: { - VStack(spacing: 2.5) { - Image(systemName: isSelected ? tab.selectedIcon : tab.icon) - .font(.system(size: 16.5, weight: isSelected ? .semibold : .regular)) - .frame(height: 19) +private struct ConnectedSasCapsuleView: View { + let notice: ConnectedSasNotice + let onDismiss: () -> Void - Text(tab.title) - .font(.system(size: 10.5, weight: isSelected ? .semibold : .medium)) - .lineLimit(1) - } - .foregroundStyle(isSelected ? Color.accentColor : Color.secondary) - .frame(maxWidth: .infinity) - .padding(.vertical, 6) - .background { - if isSelected { - Capsule(style: .continuous) - .fill(Color.accentColor.opacity(0.11)) - .matchedGeometryEffect(id: "activeTabPill", in: tabNamespace) - } - } - .contentShape(Capsule(style: .continuous)) - } - .buttonStyle(.plain) - .accessibilityLabel(tab.title) + var body: some View { + Button(action: onDismiss) { + HStack(spacing: 8) { + Image(systemName: "checkmark.circle.fill") + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(.green) + + Text("已连接 \(notice.hostName)") + .font(.system(size: 13.5, weight: .semibold)) + .foregroundStyle(.primary) + .lineLimit(1) + + Text("连接码 \(notice.sasCode)") + .font(.system(size: 12, weight: .bold, design: .monospaced)) + .monospacedDigit() + .foregroundStyle(Color.accentColor) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background( + Capsule(style: .continuous) + .fill(Color.accentColor.opacity(0.12)) + ) } + .padding(.horizontal, 14) + .padding(.vertical, 9) + .background( + Capsule(style: .continuous) + .fill(.ultraThinMaterial) + .shadow(color: .black.opacity(0.10), radius: 10, y: 4) + ) + .overlay( + Capsule(style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.6) + ) } - .padding(.horizontal, 5) - .padding(.vertical, 4) - .background( - .ultraThinMaterial, - in: Capsule(style: .continuous) - ) - .overlay( - Capsule(style: .continuous) - .strokeBorder( - LinearGradient( - colors: [ - Color.white.opacity(0.24), - Color.primary.opacity(0.08), - ], - startPoint: .top, - endPoint: .bottom - ), - lineWidth: 0.6 - ) - ) - .shadow(color: .black.opacity(0.12), radius: 12, y: 4) - .padding(.horizontal, 22) - .padding(.bottom, 6) + .buttonStyle(.plain) + .padding(.horizontal, 16) + .accessibilityLabel("已连接 \(notice.hostName),连接码 \(notice.sasCode)") } } diff --git a/App/SearchCard.swift b/App/SearchCard.swift index f340bb4..a6ec22c 100644 --- a/App/SearchCard.swift +++ b/App/SearchCard.swift @@ -69,6 +69,93 @@ struct ConnectedDeviceBar: View { } } +/// Unified native-feel search bar used across primary tabs (`会话`, `协作空间`, etc.): +/// crisp single-layer surface (no clipped cell shadows), focus accent ring, instant clear button, +/// and smooth trailing `取消` button when active. +struct UnifiedSearchBar: View { + @Binding var query: String + let placeholder: String + + @FocusState private var isFocused: Bool + + private var isActive: Bool { + isFocused || !query.isEmpty + } + + var body: some View { + HStack(spacing: 8) { + HStack(spacing: 8) { + Image(systemName: "magnifyingglass") + .font(.system(size: 14.5, weight: .medium)) + .foregroundStyle(isFocused ? Color.accentColor : Color.secondary) + + TextField(placeholder, text: $query) + .font(.system(size: 15)) + .foregroundStyle(.primary) + .focused($isFocused) + .textFieldStyle(.plain) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .submitLabel(.search) + .onSubmit { + isFocused = false + } + + if !query.isEmpty { + Button { + query = "" + } label: { + Image(systemName: "xmark.circle.fill") + .font(.system(size: 15)) + .foregroundStyle(.tertiary) + .frame(width: 24, height: 24) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("清除搜索") + } + } + .padding(.horizontal, 12) + .frame(height: 40) + .background( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .strokeBorder( + isFocused ? Color.accentColor.opacity(0.45) : Color.primary.opacity(0.06), + lineWidth: isFocused ? 1.0 : 0.6 + ) + ) + .contentShape(Rectangle()) + .onTapGesture { + if !isFocused { + isFocused = true + } + } + + if isActive { + Button { + withAnimation(.easeOut(duration: 0.18)) { + query = "" + isFocused = false + } + dismissKeyboard() + } label: { + Text("取消") + .font(.system(size: 14.5, weight: .medium)) + .foregroundStyle(Color.accentColor) + .padding(.leading, 2) + } + .buttonStyle(.plain) + .transition(.move(edge: .trailing).combined(with: .opacity)) + } + } + .animation(.easeOut(duration: 0.18), value: isActive) + } +} + /// SwiftUI port of the SearchList + GlideMenu card: /// a 40pt input row with clear button, live-filtered GlideMenu results, and a centered empty state. struct SearchListCard: View { @@ -248,7 +335,6 @@ struct SearchListCard: View { GeometryReader { geo in RoundedRectangle(cornerRadius: 12, style: .continuous) .fill(Color(.secondarySystemGroupedBackground)) - .shadow(color: .black.opacity(0.06), radius: 10, y: 3) .onAppear { cardGlobalFrame = geo.frame(in: .global) } diff --git a/App/ServerStore.swift b/App/ServerStore.swift index d7d8cc3..8a29b90 100644 --- a/App/ServerStore.swift +++ b/App/ServerStore.swift @@ -12,17 +12,21 @@ struct ServerProfile: Codable, Identifiable, Hashable { var hostId: String? = nil var hostName: String? = nil - var isCloudService: Bool { + static func isCloudOrigin(_ origin: String) -> Bool { let lower = origin.lowercased() return lower.contains("/t/") || lower.hasPrefix("https://") } + var isCloudService: Bool { + ServerProfile.isCloudOrigin(origin) + } + var channelBadgeText: String { - isCloudService ? "云服务 Beta" : "局域网" + isCloudService ? "云中继" : "局域网" } var transportChannelLabel: String { - isCloudService ? "VibeX 云服务 · Beta" : "LAN 局域网直连" + isCloudService ? "VibeX 云中继 · Beta" : "LAN 局域网直连" } var displayHost: String { @@ -69,12 +73,47 @@ struct PendingCloudFallbackPrompt: Identifiable { let rttMs: Int } +struct ConnectedSasNotice: Identifiable, Equatable { + let id = UUID() + let hostName: String + let sasCode: String +} + +enum CloudNodePreference: Equatable { + case auto + case official + case custom(String) +} + @Observable final class ServerStore { private(set) var profiles: [ServerProfile] private let defaults: UserDefaults private static let key = "server-profiles" private static let autoConnectKey = "server-auto-connect" + private static let customRelayKey = "vibex.customRelayOrigin" + + var customRelayOrigin: String { + didSet { + let normalized = Self.normalizeOrigin(customRelayOrigin) + if normalized != customRelayOrigin { + customRelayOrigin = normalized + return + } + defaults.set(normalized, forKey: Self.customRelayKey) + } + } + + var hasCustomRelayNode: Bool { + !customRelayOrigin.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + func isCustomRelayOrigin(_ origin: String) -> Bool { + guard hasCustomRelayNode else { return false } + let normalized = Self.normalizeOrigin(origin) + let customBase = Self.normalizeOrigin(customRelayOrigin) + return normalized == customBase || normalized.hasPrefix("\(customBase)/") + } // Auto-connect switch (whether to automatically connect to paired computer on launch) var autoConnect: Bool { @@ -93,6 +132,7 @@ final class ServerStore { var pairingInProgress: Bool = false var pairingError: String? var pendingCloudFallback: PendingCloudFallbackPrompt? + var connectedSasNotice: ConnectedSasNotice? var isPresentingPairSheet: Bool = false var connectionSuccessCount: Int = 0 @@ -103,14 +143,21 @@ final class ServerStore { private var discoverTask: Task? private var telemetryLoopTask: Task? + private var sasNoticeTask: Task? private var declinedCloudFallbackProfileIds = Set() weak var accountStore: VibeXAccountStore? + private(set) var isCloudRelayAuthorized: Bool = false + + func setCloudRelayAuthorized(_ authorized: Bool) { + isCloudRelayAuthorized = authorized + } init(defaults: UserDefaults = .standard) { self.defaults = defaults let decoded = (defaults.data(forKey: Self.key)) .flatMap { try? JSONDecoder().decode([ServerProfile].self, from: $0) } ?? [] self.profiles = decoded + self.customRelayOrigin = Self.normalizeOrigin(defaults.string(forKey: Self.customRelayKey) ?? "") let savedAutoConnect = defaults.object(forKey: Self.autoConnectKey) as? Bool ?? true self.autoConnect = savedAutoConnect self.isSessionConnected = savedAutoConnect || decoded.isEmpty @@ -182,14 +229,16 @@ final class ServerStore { return true } - /// Asks the desktop to approve this phone for the signed-in VibeX account, then adopts the issued credential. + /// Connects directly when both devices share one VibeX account (issuing the credential immediately + /// and surfacing the 4-digit SAS code non-blockingly), or waits for 1-click desktop confirmation + /// when connecting without a matching account. @MainActor func connectViaAccountRequest( origin: String, hostId: String, hostName: String, deviceName: String, - accountToken: String, + accountToken: String?, replaceExistingMobile: Bool, onAwaitingApproval: @MainActor (String) -> Void ) async throws { @@ -206,26 +255,55 @@ final class ServerStore { replaceExistingMobile: replaceExistingMobile, accountToken: accountToken ) - onAwaitingApproval(requested.sasCode) - let approved = try await client.awaitConnectApproval(origin: parsed, requestId: requested.requestId) + let approved: DeviceConnectRequestResult + let wasAutoApproved: Bool + if requested.status == "approved", requested.credential != nil { + approved = requested + wasAutoApproved = true + } else { + wasAutoApproved = false + onAwaitingApproval(requested.sasCode) + approved = try await client.awaitConnectApproval(origin: parsed, requestId: requested.requestId) + } guard let credential = approved.credential else { throw PairingError.connectExpired } try KeychainStore.save(credential.access_token, account: credential.device_id) let capabilities = try? await HostClient(origin: parsed, accessToken: credential.access_token).checkCapabilities() let resolvedName = (approved.hostName ?? hostName) .replacingOccurrences(of: ".local", with: "") .trimmingCharacters(in: .whitespacesAndNewlines) - adopt( - ServerProfile( - id: credential.device_id, - origin: parsed.value, - deviceName: deviceName, - serverVersion: capabilities?.server_version ?? "", - protocolVersion: capabilities?.protocol_version ?? PairingClient.clientProtocolVersion, - scopes: credential.scopes, - hostId: approved.hostId.isEmpty ? hostId : AccountDesktop.rawHostId(approved.hostId), - hostName: resolvedName.isEmpty ? nil : resolvedName - ) + let profile = ServerProfile( + id: credential.device_id, + origin: parsed.value, + deviceName: deviceName, + serverVersion: capabilities?.server_version ?? "", + protocolVersion: capabilities?.protocol_version ?? PairingClient.clientProtocolVersion, + scopes: credential.scopes, + hostId: approved.hostId.isEmpty ? (hostId.isEmpty ? nil : hostId) : AccountDesktop.rawHostId(approved.hostId), + hostName: resolvedName.isEmpty ? nil : resolvedName ) + adopt(profile) + if wasAutoApproved, !approved.sasCode.isEmpty { + presentConnectedSasNotice(hostName: profile.displayHost, sasCode: approved.sasCode) + } + } + + @MainActor + func presentConnectedSasNotice(hostName: String, sasCode: String) { + sasNoticeTask?.cancel() + let notice = ConnectedSasNotice(hostName: hostName, sasCode: sasCode) + connectedSasNotice = notice + sasNoticeTask = Task { @MainActor [weak self] in + try? await Task.sleep(for: .milliseconds(4500)) + guard !Task.isCancelled, self?.connectedSasNotice?.id == notice.id else { return } + self?.connectedSasNotice = nil + } + } + + @MainActor + func dismissConnectedSasNotice() { + sasNoticeTask?.cancel() + sasNoticeTask = nil + connectedSasNotice = nil } /// `input` is a pasted or scanned invitation, or a bare 8-digit connection code. @@ -237,6 +315,7 @@ final class ServerStore { manualOrigin: String = "", deviceName: String, replaceExistingMobile: Bool = false, + cloudPreference: CloudNodePreference = .auto, onConflict: @escaping @MainActor (PendingMobileConflict) -> Void ) async throws { let client = PairingClient() @@ -256,29 +335,112 @@ final class ServerStore { for reach in invitation.reachability where reach.origin.contains("/t/") { PairingClient.rememberRelayBase(reach.origin) } + let allowOfficialCloud = accountStore?.canUseCloudRelay == true + let customBase: String? = { + switch cloudPreference { + case let .custom(url): + let norm = Self.normalizeOrigin(url) + return norm.isEmpty ? nil : norm + case .auto: + return hasCustomRelayNode ? customRelayOrigin : nil + case .official: + return nil + } + }() + let allowCloud = allowOfficialCloud || customBase != nil let directOriginText = manualOrigin.trimmingCharacters(in: .whitespacesAndNewlines) - if !directOriginText.isEmpty, let directOrigin = try? HostOrigin.parse(directOriginText) { + if !directOriginText.isEmpty, + let directOrigin = try? HostOrigin.parse(directOriginText), + allowCloud || !ServerProfile.isCloudOrigin(directOrigin.value) + { session = try await client.redeem( origin: directOrigin, pairingToken: invitation.pairing_token, deviceName: deviceName, replaceExistingMobile: replaceExistingMobile ) - } else { + } else if case let .custom(customNode) = cloudPreference { + let normCustom = Self.normalizeOrigin(customNode) + let hostId = invitation.host_id.trimmingCharacters(in: .whitespacesAndNewlines) + let customOriginText = normCustom.contains("/t/") || hostId.isEmpty ? normCustom : "\(normCustom)/t/\(hostId)" + if let parsedCustom = try? HostOrigin.parse(customOriginText) { + session = try await client.redeem( + origin: parsedCustom, + pairingToken: invitation.pairing_token, + deviceName: deviceName, + replaceExistingMobile: replaceExistingMobile + ) + } else { + throw PairingError.missingInput("自建云节点地址格式无效") + } + } else if allowOfficialCloud { session = try await client.redeem( invitation: invitation, deviceName: deviceName, replaceExistingMobile: replaceExistingMobile ) + } else { + let lanReachability = invitation.reachability.filter { !ServerProfile.isCloudOrigin($0.origin) } + guard !lanReachability.isEmpty else { + throw PairingError.missingInput("云中继连接需要先登录 VibeX 账号,或请确保手机与电脑在同一局域网") + } + var lastError: Error = PairingError.unreachable + var lanSession: CompanionSession? + for reach in lanReachability { + guard let parsed = try? HostOrigin.parse(reach.origin) else { continue } + do { + lanSession = try await client.redeem( + origin: parsed, + pairingToken: invitation.pairing_token, + deviceName: deviceName, + replaceExistingMobile: replaceExistingMobile + ) + break + } catch let err as PairingError { + lastError = err + switch err { + case .codeAlreadyUsed, .codeExpired, .codeInvalid, .notCompanionInvitation, .mobileDeviceConflict: + throw err + default: + continue + } + } catch { + lastError = error + continue + } + } + guard let matched = lanSession else { + throw lastError + } + session = matched } } else { + let allowOfficialCloud = accountStore?.canUseCloudRelay == true + let customNodeBase: String? = { + switch cloudPreference { + case let .custom(url): + let norm = Self.normalizeOrigin(url) + return norm.isEmpty ? nil : norm + case .auto: + return hasCustomRelayNode ? customRelayOrigin : nil + case .official: + return nil + } + }() + let allowCloud = allowOfficialCloud || customNodeBase != nil var candidateUrls: [String] = [] func appendCandidate(_ raw: String) { let normalized = Self.normalizeOrigin(raw) guard !normalized.isEmpty, !candidateUrls.contains(normalized) else { return } + if ServerProfile.isCloudOrigin(normalized) && !allowOfficialCloud && !isCustomRelayOrigin(normalized) { + return + } candidateUrls.append(normalized) } + if case let .custom(customNode) = cloudPreference { + appendCandidate(customNode) + } if !manualOrigin.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { appendCandidate(manualOrigin) } @@ -431,19 +593,33 @@ final class ServerStore { pendingCloudFallback = nil } + /// The desktop revokes a phone when another phone connects, it signs out, or the user removes it. + private static let revokedFailureReason = "连接授权已失效" + private static let revokedNotice = "电脑已收回本机的连接授权,请重新连接" + + /// The account relay URL of a desktop signed in to the same account. It lets the phone reach + /// that desktop off-LAN even when the profile never learned a published origin. + @MainActor + private func accountTenantOrigin(for hostId: String) -> String? { + guard let accountStore, accountStore.isSignedIn, accountStore.canUseCloudRelay else { return nil } + let rawHostId = AccountDesktop.rawHostId(hostId) + guard let desktop = accountStore.desktops.first(where: { $0.hostId == rawHostId }) else { return nil } + return desktop.cloudOrigin(relayBase: accountStore.relayBase) + } + @MainActor func handleActiveCredentialRevoked(_ profile: ServerProfile) { guard !isPresentingPairSheet else { isOnline = false realtimeRttMs = nil - connectionFailureReason = "已被其他手机接管下线" + connectionFailureReason = Self.revokedFailureReason return } forget(profile) isOnline = false realtimeRttMs = nil - connectionFailureReason = "已被其他手机接管下线" - pairingError = "当前电脑已切换至其他手机远程连接,本机已强制下线并清除凭据,下次需重新连接" + connectionFailureReason = Self.revokedFailureReason + pairingError = Self.revokedNotice } @MainActor @@ -463,6 +639,19 @@ final class ServerStore { } } + @MainActor + func handleAccountSignOut() { + isCloudRelayAuthorized = false + if activeProfile?.isCloudService == true { + isOnline = false + realtimeRttMs = nil + connectionFailureReason = "请登录 VibeX 账号" + } + Task { @MainActor [weak self] in + await self?.refreshActiveTelemetry() + } + } + @MainActor func refreshActiveTelemetry() async { guard let active = activeProfile else { @@ -472,6 +661,41 @@ final class ServerStore { return } + let canUseCloud = accountStore?.canUseCloudRelay == true || isCustomRelayOrigin(active.origin) + if active.isCloudService && !canUseCloud { + // Cloud relay requires an active signed-in VibeX account; only allow LAN fallback. + if let hostId = active.hostId, !hostId.isEmpty { + let candidates = await PairingClient.resolveHostRendezvous( + hostId: hostId, + knownOrigins: profiles.map(\.origin) + ) + for candidate in candidates where !ServerProfile.isCloudOrigin(candidate) { + if let probe = await PairingClient.probeHostHealth( + originUrl: candidate, + timeoutSeconds: 1.5, + expectedHostId: hostId + ) { + if let idx = profiles.firstIndex(where: { $0.id == active.id }) { + profiles[idx].origin = probe.host.origin + profiles[idx].hostName = active.hostName ?? probe.host.displayName + persist() + } + if let updatedActive = activeProfile { + guard await verifyActiveTokenNotRevoked(updatedActive) else { return } + } + isOnline = true + realtimeRttMs = probe.rttMs + connectionFailureReason = nil + return + } + } + } + isOnline = false + realtimeRttMs = nil + connectionFailureReason = "请登录 VibeX 账号" + return + } + if let probe = await PairingClient.probeHostHealth( originUrl: active.origin, timeoutSeconds: 1.5, @@ -497,18 +721,22 @@ final class ServerStore { // If the computer switched to or from Cloud Service and we know its hostId, try rendezvous origins if let hostId = active.hostId, !hostId.isEmpty { - let candidates = await PairingClient.resolveHostRendezvous( + var candidates = await PairingClient.resolveHostRendezvous( hostId: hostId, knownOrigins: profiles.map(\.origin) ) + if let accountOrigin = accountTenantOrigin(for: hostId), !candidates.contains(accountOrigin) { + candidates.append(accountOrigin) + } for candidate in candidates where candidate != active.origin { if let probe = await PairingClient.probeHostHealth( originUrl: candidate, timeoutSeconds: 1.5, expectedHostId: hostId ) { - // If the user originally connected via LAN direct, ask before switching to Cloud Service! - if !active.isCloudService && probe.host.isCloudService { + // Seamlessly switch to Cloud Service when the user's account allows cloud relay; + // only prompt if the user is not signed into an account with cloud relay permission. + if !active.isCloudService && probe.host.isCloudService && accountStore?.canUseCloudRelay == false { isOnline = false realtimeRttMs = nil connectionFailureReason = "局域网已断开" @@ -698,6 +926,9 @@ final class ServerStore { } func client(for profile: ServerProfile) -> HostClient? { + if profile.isCloudService && !isCloudRelayAuthorized && !isCustomRelayOrigin(profile.origin) { + return nil + } guard let origin = try? HostOrigin.parse(profile.origin), let token = KeychainStore.read(account: profile.id) else { return nil } diff --git a/App/SettingsView.swift b/App/SettingsView.swift index a9c03d3..3ba6e66 100644 --- a/App/SettingsView.swift +++ b/App/SettingsView.swift @@ -1,19 +1,31 @@ import CompanionCore import SwiftUI +private enum SettingsRoute: Hashable { + case account + case pairedComputers + case skillsHub + case font + case notifications + case about +} + struct SettingsView: View { @Environment(ServerStore.self) private var servers @Environment(AppAppearanceStore.self) private var appearance @Environment(VibeXAccountStore.self) private var account + @Environment(WorkspaceNavigationStore.self) private var navStore + @Environment(AppUpdateStore.self) private var appUpdates + @State private var path: [SettingsRoute] = [] + @State private var cacheSizeText: String = "" + @State private var cacheClearedBanner = false var body: some View { - NavigationStack { + NavigationStack(path: $path) { List { // 1. VibeX 账号(唯一顶栏个人中心) Section { - NavigationLink { - VibeXAccountSettingsView() - } label: { + NavigationLink(value: SettingsRoute.account) { HStack(spacing: 12) { MemberBotAvatarView( config: appearance.avatarConfig, @@ -22,7 +34,7 @@ struct SettingsView: View { ) VStack(alignment: .leading, spacing: 3) { HStack(spacing: 6) { - Text(account.isSignedIn ? (account.user?.resolvedDisplayName ?? "VibeX 账号") : "VibeX 账号") + Text(account.isSignedIn ? (account.user?.resolvedDisplayName ?? appearance.l("VibeX 账号", "VibeX Account")) : appearance.l("VibeX 账号", "VibeX Account")) .font(.body.weight(.semibold)) .foregroundStyle(.primary) .lineLimit(1) @@ -39,12 +51,12 @@ struct SettingsView: View { } } if account.isSignedIn, let user = account.user { - Text("\(user.email ?? user.accountIdentifier ?? user.resolvedDisplayName) · 跨端同步与模型额度") + Text("\(user.email ?? user.accountIdentifier ?? user.resolvedDisplayName) · \(appearance.l("跨端同步", "Synced"))") .font(.caption) .foregroundStyle(.secondary) .lineLimit(1) } else { - Text("登录以跨端同步电脑、查看订阅与模型额度") + Text(appearance.l("跨端同步电脑与模型额度", "Sync desktops & model credits")) .font(.caption) .foregroundStyle(.secondary) .lineLimit(1) @@ -52,9 +64,12 @@ struct SettingsView: View { } Spacer(minLength: 6) if !account.isSignedIn { - Text("未登录") - .font(.caption) - .foregroundStyle(.secondary) + Text(appearance.l("去登录", "Sign In")) + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background(Capsule().fill(Color.accentColor.opacity(0.12))) + .foregroundStyle(Color.accentColor) } } } @@ -63,41 +78,40 @@ struct SettingsView: View { // 2. 工作站与扩展 Section { - NavigationLink { - PairedComputersSettingsView() - } label: { + NavigationLink(value: SettingsRoute.pairedComputers) { HStack(spacing: 10) { settingsIconBadge( systemImage: "desktopcomputer", tint: .blue ) - Text("连接") + Text(appearance.l("连接", "Connection")) .font(.subheadline.weight(.medium)) Spacer(minLength: 6) if let active = servers.activeProfile { + let online = servers.isSessionConnected && servers.isOnline HStack(spacing: 5) { Circle() - .fill(Color.green) + .fill(online ? Color.green : Color.secondary.opacity(0.55)) .frame(width: 6.5, height: 6.5) Text(active.displayHost) .font(.caption) .foregroundStyle(.secondary) .lineLimit(1) - Text(active.channelBadgeText) + Text(online ? (active.isCloudService ? appearance.l("云中继", "Cloud") : appearance.l("局域网", "LAN")) : appearance.l("离线", "Offline")) .font(.caption2.weight(.semibold)) .padding(.horizontal, 6) .padding(.vertical, 1.5) .background( Capsule().fill( - active.isCloudService + online && active.isCloudService ? Color.accentColor.opacity(0.14) : Color.secondary.opacity(0.12) ) ) - .foregroundStyle(active.isCloudService ? Color.accentColor : .secondary) + .foregroundStyle(online && active.isCloudService ? Color.accentColor : .secondary) } } else { - Text("未连接") + Text(appearance.l("未连接", "Disconnected")) .font(.caption) .foregroundStyle(.secondary) } @@ -105,18 +119,16 @@ struct SettingsView: View { } .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) - NavigationLink { - SkillsHubSettingsView() - } label: { + NavigationLink(value: SettingsRoute.skillsHub) { HStack(spacing: 10) { settingsIconBadge( systemImage: "sparkles.rectangle.stack.fill", tint: .purple ) - Text("技能与扩展") + Text(appearance.l("技能与扩展", "Skills & Extensions")) .font(.subheadline.weight(.medium)) Spacer() - Text("技能 · MCP · 插件") + Text(appearance.l("技能 · MCP · 插件", "Skills · MCP · Plugins")) .font(.caption) .foregroundStyle(.secondary) } @@ -131,93 +143,234 @@ struct SettingsView: View { systemImage: appearance.themeMode.icon, tint: .indigo ) - Text("主题") + Text(appearance.l("主题", "Theme")) .font(.subheadline.weight(.medium)) Spacer(minLength: 8) - Picker("主题", selection: Binding( + Picker(appearance.l("主题", "Theme"), selection: Binding( get: { appearance.themeMode }, set: { appearance.setThemeModeWithTopRightReveal($0) } )) { ForEach(AppThemeMode.allCases) { mode in - Text(mode.title).tag(mode) + Text(mode.localizedTitle(english: appearance.languageMode == .en)).tag(mode) } } .pickerStyle(.segmented) .labelsHidden() - .frame(maxWidth: 210) + .frame(maxWidth: 186) } .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) - NavigationLink { - FontSettingsDetailView() - } label: { + HStack(spacing: 10) { + settingsIconBadge( + systemImage: "globe", + tint: .blue + ) + Text(appearance.l("语言", "Language")) + .font(.subheadline.weight(.medium)) + Spacer(minLength: 8) + Picker(appearance.l("语言", "Language"), selection: Binding( + get: { appearance.languageMode }, + set: { appearance.languageMode = $0 } + )) { + ForEach(AppLanguageMode.allCases) { lang in + Text(lang.title).tag(lang) + } + } + .pickerStyle(.segmented) + .labelsHidden() + .frame(maxWidth: 164) + } + .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + + NavigationLink(value: SettingsRoute.font) { HStack(spacing: 10) { settingsIconBadge( systemImage: "textformat.size", tint: .orange ) - Text("字体") + Text(appearance.l("字体", "Font")) .font(.subheadline.weight(.medium)) Spacer() - Text("\(appearance.fontStylePreset.shortTitle) · \(appearance.fontSizePreset.title)") + Text("\(appearance.fontStylePreset.localizedShortTitle(english: appearance.languageMode == .en)) · \(appearance.fontSizePreset.localizedTitle(english: appearance.languageMode == .en))") .font(.caption) .foregroundStyle(.secondary) } } .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) - NavigationLink { - NotificationSettingsDetailView() - } label: { + NavigationLink(value: SettingsRoute.notifications) { HStack(spacing: 10) { settingsIconBadge( systemImage: "bell.badge.fill", tint: .red ) - Text("通知") + Text(appearance.l("通知", "Notifications")) .font(.subheadline.weight(.medium)) Spacer() - Text(appearance.systemNotificationStatusText) + Text(appearance.systemNotificationStatusTextLocalized) .font(.caption) .foregroundStyle(.secondary) } } .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) + + HStack(spacing: 10) { + settingsIconBadge( + systemImage: "shield.lefthalf.filled", + tint: .green + ) + Toggle(isOn: Binding( + get: { appearance.confirmHighRiskApproval }, + set: { appearance.confirmHighRiskApproval = $0 } + )) { + VStack(alignment: .leading, spacing: 2) { + Text(appearance.l("高危审批保护", "Approval Guard")) + .font(.subheadline.weight(.medium)) + Text(appearance.l("允许命令与文件操作前二次确认", "Confirm before allowing commands")) + .font(.caption2) + .foregroundStyle(.secondary) + } + } + } + .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) } - // 4. 关于 VibeX + // 4. 清理缓存 & 关于 Dimo Section { - NavigationLink { - AboutVibeXDetailView() + Button { + clearLocalCache() } label: { + HStack(spacing: 10) { + settingsIconBadge( + systemImage: "trash.fill", + tint: .orange + ) + Text(appearance.l("清理缓存", "Clear Cache")) + .font(.subheadline.weight(.medium)) + .foregroundStyle(.primary) + Spacer() + if cacheClearedBanner { + Text(appearance.l("已清理", "Cleared")) + .font(.caption.weight(.medium)) + .foregroundStyle(.green) + } else if !cacheSizeText.isEmpty { + Text(cacheSizeText) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + } + } + .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) + + NavigationLink(value: SettingsRoute.about) { HStack(spacing: 10) { settingsIconBadge( systemImage: "info.circle.fill", tint: .teal ) - Text("关于 VibeX") + Text(appearance.l("关于 Dimo", "About Dimo")) .font(.subheadline.weight(.medium)) Spacer() - Text(currentVersionLabel) - .font(.caption.monospacedDigit()) - .foregroundStyle(.secondary) + if appUpdates.hasUpdate, let release = appUpdates.latestRelease { + Text("新版本 v\(release.version)") + .font(.caption2.monospacedDigit().weight(.semibold)) + .padding(.horizontal, 7) + .padding(.vertical, 2.5) + .background(Capsule().fill(Color.red.opacity(0.14))) + .foregroundStyle(Color.red) + } else { + Text(currentVersionLabel) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } } } .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) } } + .task { + cacheSizeText = Self.computeCacheSizeString() + } .listSectionSpacing(10) .contentMargins(.top, 4, for: .scrollContent) - .navigationTitle("设置") + .safeAreaPadding(.bottom, WorkspaceNavigationStore.bottomDockClearance) + .navigationTitle(appearance.l("设置", "Settings")) .navigationBarTitleDisplayMode(.inline) + .navigationDestination(for: SettingsRoute.self) { route in + switch route { + case .account: + VibeXAccountSettingsView() + case .pairedComputers: + PairedComputersSettingsView() + case .skillsHub: + SkillsHubSettingsView() + case .font: + FontSettingsDetailView() + case .notifications: + NotificationSettingsDetailView() + case .about: + AboutVibeXDetailView() + } + } + } + .onAppear { + navStore.settingsDepth = path.count + } + .onChange(of: path.count) { _, count in + navStore.settingsDepth = count } } private var currentVersionLabel: String { - if let active = servers.activeProfile { - return "v\(active.serverVersion)" + "v\(appUpdates.currentVersion)" + } + + private func clearLocalCache() { + URLCache.shared.removeAllCachedResponses() + let fm = FileManager.default + let tmpDir = fm.temporaryDirectory + if let items = try? fm.contentsOfDirectory(at: tmpDir, includingPropertiesForKeys: nil) { + for item in items { + try? fm.removeItem(at: item) + } + } + if let cacheDir = fm.urls(for: .cachesDirectory, in: .userDomainMask).first, + let items = try? fm.contentsOfDirectory(at: cacheDir, includingPropertiesForKeys: nil) + { + for item in items { + try? fm.removeItem(at: item) + } + } + cacheSizeText = Self.computeCacheSizeString() + UINotificationFeedbackGenerator().notificationOccurred(.success) + withAnimation { + cacheClearedBanner = true + } + Task { @MainActor in + try? await Task.sleep(for: .seconds(1.8)) + withAnimation { + cacheClearedBanner = false + } } - return "v0.4.5" + } + + private static func computeCacheSizeString() -> String { + var bytes = Int64(URLCache.shared.currentDiskUsage) + let fm = FileManager.default + let dirs = [ + fm.temporaryDirectory, + fm.urls(for: .cachesDirectory, in: .userDomainMask).first, + ].compactMap { $0 } + for dir in dirs { + if let enumerator = fm.enumerator(at: dir, includingPropertiesForKeys: [.fileSizeKey]) { + for case let fileURL as URL in enumerator { + if let size = try? fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize { + bytes += Int64(size) + } + } + } + } + return ByteCountFormatter.string(fromByteCount: max(0, bytes), countStyle: .file) } private func settingsIconBadge(systemImage: String, tint: Color) -> some View { @@ -450,6 +603,18 @@ struct PairedComputersSettingsView: View { } } } + + Section { + TextField("https://relay.example.com", text: Bindable(servers).customRelayOrigin) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .keyboardType(.URL) + .font(.subheadline.monospaced()) + } header: { + Text("自建云节点(可选)") + } footer: { + Text("填写后,扫码配对时可选择使用官方云服务或你的自建节点;未填写则默认局域网优先。") + } } .navigationTitle("连接") .navigationBarTitleDisplayMode(.inline) @@ -460,7 +625,7 @@ struct PairedComputersSettingsView: View { await servers.refreshActiveTelemetry() } .sheet(isPresented: $showingPairSheet) { - PairView(startWithScanner: false, initialOrigin: servers.activeProfile?.origin) + PairView(startWithScanner: true, initialOrigin: servers.activeProfile?.origin) } } @@ -1492,75 +1657,91 @@ struct FontSettingsDetailView: View { struct NotificationSettingsDetailView: View { @Environment(AppAppearanceStore.self) private var appearance + @Environment(\.scenePhase) private var scenePhase var body: some View { @Bindable var bindableAppearance = appearance Form { - Section("系统推送权限") { + Section(appearance.l("系统推送权限", "System Permission")) { HStack { - VStack(alignment: .leading, spacing: 3) { - Text("iOS 系统通知状态") - .font(.body.weight(.medium)) - Text(appearance.systemNotificationStatusText) - .font(.caption) - .foregroundStyle(.secondary) - } + Text(appearance.l("iOS 系统通知", "iOS Notifications")) + .font(.body.weight(.medium)) Spacer() - Button("请求/刷新权限") { - Task { - await appearance.requestSystemNotificationPermission() + switch appearance.notificationAuthorizationStatus { + case .authorized, .provisional, .ephemeral: + Text(appearance.l("已开启", "Enabled")) + .font(.subheadline.weight(.medium)) + .foregroundStyle(.green) + case .denied: + Button(appearance.l("前往系统设置", "Open Settings")) { + if let url = URL(string: UIApplication.openSettingsURLString) { + UIApplication.shared.open(url) + } } + .font(.subheadline.weight(.medium)) + case .notDetermined: + Text(appearance.l("未开启", "Not Set")) + .font(.subheadline) + .foregroundStyle(.secondary) + @unknown default: + Text(appearance.systemNotificationStatusTextLocalized) + .font(.subheadline) + .foregroundStyle(.secondary) } - .buttonStyle(.borderedProminent) - .controlSize(.small) } } - Section("事件提醒") { - Toggle("任务完成通知", isOn: $bindableAppearance.notifyTurnCompleted) - Toggle("权限审批与提问提醒", isOn: $bindableAppearance.notifyApprovalRequired) - Toggle("协作空间 @ 与新消息通知", isOn: $bindableAppearance.notifyCollabMessages) + Section(appearance.l("事件提醒", "Alerts")) { + Toggle(appearance.l("前台静默(使用 App 时不弹横幅)", "Mute in Foreground"), isOn: $bindableAppearance.muteForegroundNotifications) + Toggle(appearance.l("任务完成通知", "Task Completed"), isOn: $bindableAppearance.notifyTurnCompleted) + Toggle(appearance.l("权限审批与提问提醒", "Approval & Questions"), isOn: $bindableAppearance.notifyApprovalRequired) + Toggle(appearance.l("协作空间 @ 与新消息通知", "Collab @ & Messages"), isOn: $bindableAppearance.notifyCollabMessages) } - Section("声音与触感") { - Toggle("消息提示音", isOn: $bindableAppearance.notificationSound) - Toggle("触感震动反馈 (Haptics)", isOn: $bindableAppearance.hapticFeedback) + Section(appearance.l("声音与触感", "Sound & Haptics")) { + Toggle(appearance.l("消息提示音", "Notification Sound"), isOn: $bindableAppearance.notificationSound) + Toggle(appearance.l("触感震动反馈 (Haptics)", "Haptic Feedback"), isOn: $bindableAppearance.hapticFeedback) } } - .navigationTitle("通知") + .navigationTitle(appearance.l("通知", "Notifications")) .navigationBarTitleDisplayMode(.inline) .task { await appearance.refreshNotificationAuthorizationStatus() + if appearance.notificationAuthorizationStatus == .notDetermined { + await appearance.requestSystemNotificationPermission() + } + } + .onChange(of: scenePhase) { _, phase in + if phase == .active { + Task { await appearance.refreshNotificationAuthorizationStatus() } + } } } } -// MARK: - 7. 关于 VibeX 详情页 +// MARK: - 7. 关于 Dimo 详情页 struct AboutVibeXDetailView: View { @Environment(ServerStore.self) private var servers + @Environment(AppUpdateStore.self) private var appUpdates + @Environment(AppAppearanceStore.self) private var appearance var body: some View { List { Section { VStack(spacing: 10) { - ZStack { - RoundedRectangle(cornerRadius: 20, style: .continuous) - .fill( - LinearGradient( - colors: [Color.accentColor, Color.indigo], - startPoint: .topLeading, - endPoint: .bottomTrailing - ) - ) - .frame(width: 72, height: 72) - Image(systemName: "sparkles") - .font(.system(size: 32, weight: .bold)) - .foregroundStyle(.white) - } - Text("VibeX Companion") + Image("dimo_logo") + .resizable() + .aspectRatio(contentMode: .fit) + .frame(width: 72, height: 72) + .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 18, style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.75) + ) + Text("Dimo") .font(.title3.weight(.bold)) - Text("本地优先的多智能体研发工作台 iOS 伴侣端") + Text(appearance.l("VibeX 桌面端伴侣客户端", "VibeX Desktop Companion")) .font(.caption) .foregroundStyle(.secondary) } @@ -1568,24 +1749,55 @@ struct AboutVibeXDetailView: View { .padding(.vertical, 12) } - Section("版本与协议信息") { - LabeledContent("iOS 客户端版本", value: "v0.4.5") - LabeledContent("远程通讯协议", value: "Remote Protocol v1") + Section(appearance.l("版本与在线更新", "Version & Updates")) { + LabeledContent(appearance.l("客户端版本", "Client Version"), value: "v\(appUpdates.currentVersion) (#\(appUpdates.currentBuild))") if let active = servers.activeProfile { - LabeledContent("已连接桌面端", value: active.serverName) - LabeledContent("桌面端版本", value: "v\(active.serverVersion)") - LabeledContent("桌面端地址", value: active.origin) + LabeledContent(appearance.l("已连接桌面端", "Connected Desktop"), value: active.serverName) + LabeledContent( + appearance.l("连接方式", "Connection"), + value: active.isCloudService ? appearance.l("VibeX 云中继 · Beta", "VibeX Cloud Relay · Beta") : appearance.l("LAN 局域网直连", "LAN Direct") + ) + if !active.serverVersion.isEmpty { + LabeledContent(appearance.l("桌面端版本", "Desktop Version"), value: "v\(active.serverVersion)") + } } - } - Section("核心能力") { - Label("实时同步桌面端项目与会话流", systemImage: "bubble.left.and.bubble.right.fill") - Label("四列敏捷看板与 Token 用量统计", systemImage: "square.grid.2x2.fill") - Label("多 Bot 协作空间与动态 3D 表情头像", systemImage: "person.2.fill") - Label("工作区文件树浏览与代码预览", systemImage: "folder.fill") + Button { + if appUpdates.hasUpdate { + appUpdates.isSheetPresented = true + } else { + Task { await appUpdates.checkForUpdate(manual: true) } + } + } label: { + HStack(spacing: 8) { + Image(systemName: appUpdates.hasUpdate ? "arrow.down.app.fill" : "arrow.clockwise") + .foregroundStyle(appUpdates.hasUpdate ? Color.red : Color.accentColor) + if appUpdates.checking { + Text(appearance.l("正在检查更新…", "Checking for updates…")) + } else if appUpdates.hasUpdate, let release = appUpdates.latestRelease { + Text(appearance.l("发现新版本 v\(release.version) · 前往 TestFlight 更新", "Update v\(release.version) available")) + .fontWeight(.semibold) + .foregroundStyle(Color.red) + } else { + Text(appearance.l("检查更新", "Check for Updates")) + .fontWeight(.medium) + } + Spacer() + if appUpdates.checking { + ProgressView() + } + } + } + .disabled(appUpdates.checking) + + if let msg = appUpdates.manualStatusMessage { + Text(msg) + .font(.caption) + .foregroundStyle(.secondary) + } } } - .navigationTitle("关于 VibeX") + .navigationTitle(appearance.l("关于 Dimo", "About Dimo")) .navigationBarTitleDisplayMode(.inline) } } @@ -1594,4 +1806,5 @@ struct AboutVibeXDetailView: View { SettingsView() .environment(ServerStore(defaults: UserDefaults(suiteName: "preview")!)) .environment(AppAppearanceStore(defaults: UserDefaults(suiteName: "preview")!)) + .environment(AppUpdateStore(defaults: UserDefaults(suiteName: "preview")!)) } diff --git a/App/ThreadSettingsSheet.swift b/App/ThreadSettingsSheet.swift new file mode 100644 index 0000000..afe8615 --- /dev/null +++ b/App/ThreadSettingsSheet.swift @@ -0,0 +1,843 @@ +import SwiftUI +import UIKit + +private enum ThreadSettingsFilter: Equatable { + case all + case favorites + case provider(String) +} + +private enum ThreadSettingsSubroute: Hashable { + case effort + case runtime +} + +/// Modal "会话设置" (Thread settings) sheet modeled after modern mobile coding agent UX: +/// grouped collapsible provider model catalogs with favorites & hidden-model management, +/// reasoning/runtime option rows, custom relay model entry, and a floating bottom search + filter bar. +struct ThreadSettingsSheet: View { + let agentID: String? + let agentName: String? + let agentChoices: [PromptChoice] + let modelChoices: [PromptChoice] + let otherModelGroups: [PromptGroup] + let otherAgentNote: String? + let accessChoices: [PromptChoice] + let extraChoices: [PromptChoice] + let effort: PromptEffort? + let pickAgent: ((String) -> Void)? + let pickModel: (String) -> Void + let onAddCustomModel: ((String) -> Void)? + let pickAccess: (String) -> Void + let pickExtra: (String) -> Void + let setEffort: (Int) -> Void + var onRefreshCatalog: (() -> Void)? = nil + + @Environment(\.dismiss) private var dismiss + @AppStorage("vibex.favoriteModelKeys") private var favoriteModelKeysRaw = "" + @AppStorage("vibex.hiddenModelKeys") private var hiddenModelKeysRaw = "" + + @State private var navPath: [ThreadSettingsSubroute] = [] + @State private var collapsedGroupIDs: Set = [] + @State private var initialGroupOrder: [String] = [] + @State private var didApplyDefaultCollapse = false + @State private var manageHiddenModels = false + @State private var searchQuery = "" + @State private var activeFilter: ThreadSettingsFilter = .all + @State private var showingCustomModelAlert = false + @State private var customModelDraft = "" + + private var favoriteKeys: Set { + Set( + favoriteModelKeysRaw + .split(separator: "|") + .map { String($0).trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + ) + } + + private var hiddenKeys: Set { + Set( + hiddenModelKeysRaw + .split(separator: "|") + .map { String($0).trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + ) + } + + private func toggleFavorite(_ key: String) { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + var next = favoriteKeys + if next.contains(key) { + next.remove(key) + } else { + next.insert(key) + } + favoriteModelKeysRaw = next.sorted().joined(separator: "|") + } + + private func toggleHidden(_ key: String) { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + var next = hiddenKeys + if next.contains(key) { + next.remove(key) + } else { + next.insert(key) + } + hiddenModelKeysRaw = next.sorted().joined(separator: "|") + } + + private var primaryProviderTitle: String { + if let agentName, !agentName.isEmpty { return agentName } + return AgentBrand.displayName(agentID) + } + + private var rawProviderGroups: [PromptGroup] { + var result: [PromptGroup] = [] + if !modelChoices.isEmpty { + result.append( + PromptGroup( + title: primaryProviderTitle, + agentID: agentID, + choices: modelChoices + ) + ) + } + result.append(contentsOf: otherModelGroups) + return result + } + + private var allProviderGroups: [PromptGroup] { + let raw = rawProviderGroups + guard !initialGroupOrder.isEmpty else { return raw } + let orderMap = Dictionary(uniqueKeysWithValues: initialGroupOrder.enumerated().map { ($1, $0) }) + return raw.enumerated().sorted { lhs, rhs in + let lRank = orderMap[lhs.element.id] ?? (1_000 + lhs.offset) + let rRank = orderMap[rhs.element.id] ?? (1_000 + rhs.offset) + if lRank != rRank { return lRank < rRank } + return lhs.offset < rhs.offset + }.map(\.element) + } + + private var isSearchingModels: Bool { + !searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + private func syncGroupPresentationState() { + let currentIDs = rawProviderGroups.map(\.id) + for id in currentIDs where !initialGroupOrder.contains(id) { + initialGroupOrder.append(id) + } + if !didApplyDefaultCollapse, rawProviderGroups.count > 1 { + let totalChoices = rawProviderGroups.reduce(0) { $0 + $1.choices.count } + if rawProviderGroups.count >= 3 || totalChoices > 8 { + let secondaryIDs = otherModelGroups.map(\.id) + collapsedGroupIDs.formUnion(secondaryIDs) + } + didApplyDefaultCollapse = true + } + } + + private func favoriteStorageKey(for row: PromptChoice, groupAgentID: String?) -> String { + let provider = (row.agentID ?? groupAgentID ?? "default").lowercased() + return "\(provider)::\(row.title.lowercased())" + } + + private func filteredChoices(in group: PromptGroup) -> [PromptChoice] { + let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + if case .provider(let filterTitle) = activeFilter, filterTitle != group.title { + return [] + } + let visible = group.choices.filter { row in + let storageKey = favoriteStorageKey(for: row, groupAgentID: group.agentID) + if !manageHiddenModels && !row.selected && hiddenKeys.contains(storageKey) { + return false + } + if activeFilter == .favorites && !favoriteKeys.contains(storageKey) && !row.selected { + return false + } + guard !q.isEmpty else { return true } + let matchesTitle = row.title.lowercased().contains(q) + let matchesTag = (row.tag ?? "").lowercased().contains(q) + let matchesGroup = group.title.lowercased().contains(q) + return matchesTitle || matchesTag || matchesGroup + } + // Float favorites gently to the top within each provider group while preserving relative order + return visible.sorted { lhs, rhs in + let lFav = favoriteKeys.contains(favoriteStorageKey(for: lhs, groupAgentID: group.agentID)) + let rFav = favoriteKeys.contains(favoriteStorageKey(for: rhs, groupAgentID: group.agentID)) + if lFav != rFav { return lFav && !rFav } + return false + } + } + + var body: some View { + NavigationStack(path: $navPath) { + VStack(spacing: 0) { + headerBar + + ScrollView { + VStack(alignment: .leading, spacing: 18) { + if !isSearchingModels && (effort != nil || !accessChoices.isEmpty || !extraChoices.isEmpty) { + optionsSection + } + + providerCatalogSections + + if let otherAgentNote, !otherAgentNote.isEmpty, !isSearchingModels { + Text(otherAgentNote) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .padding(.horizontal, 6) + } + + if !isSearchingModels { + catalogManagementSection + } + } + .padding(.horizontal, 16) + .padding(.top, 8) + .padding(.bottom, 90) + } + .scrollDismissesKeyboard(.interactively) + } + .background(Color(.systemGroupedBackground).ignoresSafeArea()) + .toolbar(.hidden, for: .navigationBar) + .safeAreaInset(edge: .bottom) { + bottomSearchAndFilterBar + } + .navigationDestination(for: ThreadSettingsSubroute.self) { route in + switch route { + case .effort: + effortSubpage + case .runtime: + runtimeSubpage + } + } + } + .onAppear { + syncGroupPresentationState() + onRefreshCatalog?() + } + .onChange(of: otherModelGroups.map(\.id)) { _, _ in + syncGroupPresentationState() + } + .alert("添加自定义 / 中转模型", isPresented: $showingCustomModelAlert) { + TextField("输入模型 ID (如 claude-opus-4-8 / gpt-6-sol)", text: $customModelDraft) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + Button("取消", role: .cancel) { + customModelDraft = "" + } + Button("使用此模型") { + let trimmed = customModelDraft.trimmingCharacters(in: .whitespacesAndNewlines) + customModelDraft = "" + if !trimmed.isEmpty { + onAddCustomModel?(trimmed) + } + } + } message: { + Text("若桌面端已配置 API 中转或网关,输入模型 ID 即可直接切换。") + } + } + + // MARK: - Top Header (`✕` · `会话设置` · `✓`) + + private var headerBar: some View { + HStack { + Button { + dismiss() + } label: { + Image(systemName: "xmark") + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(.primary) + .frame(width: 38, height: 38) + .background( + Circle() + .fill(Color(.secondarySystemGroupedBackground)) + .shadow(color: .black.opacity(0.06), radius: 6, x: 0, y: 2) + ) + .overlay( + Circle() + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.6) + ) + } + .buttonStyle(.plain) + .accessibilityLabel("关闭") + + Spacer() + + Text("会话设置") + .font(.system(size: 17, weight: .bold)) + .foregroundStyle(.primary) + + Spacer() + + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + dismiss() + } label: { + Image(systemName: "checkmark") + .font(.system(size: 15, weight: .bold)) + .foregroundStyle(Color(.systemBackground)) + .frame(width: 38, height: 38) + .background( + Circle() + .fill(Color.primary) + .shadow(color: .black.opacity(0.14), radius: 6, x: 0, y: 2) + ) + } + .buttonStyle(.plain) + .accessibilityLabel("完成") + } + .padding(.horizontal, 16) + .padding(.top, 14) + .padding(.bottom, 10) + } + + // MARK: - Provider & Model Sections + + @ViewBuilder + private var providerCatalogSections: some View { + let groupsWithRows = allProviderGroups.compactMap { group -> (PromptGroup, [PromptChoice])? in + let rows = filteredChoices(in: group) + return rows.isEmpty ? nil : (group, rows) + } + + if groupsWithRows.isEmpty { + VStack(spacing: 8) { + Image(systemName: "magnifyingglass") + .font(.system(size: 24)) + .foregroundStyle(.tertiary) + Text("没有匹配的模型") + .font(.system(size: 14, weight: .medium)) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 28) + .background( + RoundedRectangle(cornerRadius: 16, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + } else { + ForEach(groupsWithRows, id: \.0.id) { group, rows in + let isCollapsed = collapsedGroupIDs.contains(group.id) + && !isSearchingModels + && activeFilter != .provider(group.title) + VStack(alignment: .leading, spacing: 8) { + Button { + withAnimation(.spring(response: 0.26, dampingFraction: 0.86)) { + if collapsedGroupIDs.contains(group.id) { + collapsedGroupIDs.remove(group.id) + } else { + collapsedGroupIDs.insert(group.id) + } + } + } label: { + HStack(spacing: 7) { + if group.agentID != nil { + AgentIconView(agent: group.agentID, size: 16) + } + Text(group.title) + .font(.system(size: 13.5, weight: .semibold)) + .foregroundStyle(rows.contains(where: \.selected) ? .primary : .secondary) + Spacer() + if isCollapsed { + if let selectedRow = rows.first(where: \.selected) { + Text(selectedRow.title) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(.secondary) + .lineLimit(1) + } else { + Text("\(rows.count)") + .font(.system(size: 12, weight: .medium)) + .monospacedDigit() + .foregroundStyle(.tertiary) + } + } + Image(systemName: isCollapsed ? "chevron.down" : "chevron.up") + .font(.system(size: 11.5, weight: .semibold)) + .foregroundStyle(.tertiary) + } + .padding(.horizontal, 4) + .padding(.vertical, 2) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + if !isCollapsed { + VStack(spacing: 0) { + ForEach(Array(rows.enumerated()), id: \.element.id) { idx, row in + modelRowView( + row: row, + groupAgentID: group.agentID, + isDefaultHint: idx == 0 && (row.tag == nil || !row.title.lowercased().contains("custom")) + ) + if idx < rows.count - 1 { + Divider() + .padding(.leading, 16) + } + } + } + .background( + RoundedRectangle(cornerRadius: 16, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + } + } + } + } + } + + private func modelRowView( + row: PromptChoice, + groupAgentID: String?, + isDefaultHint: Bool + ) -> some View { + let storageKey = favoriteStorageKey(for: row, groupAgentID: groupAgentID) + let isFavorite = favoriteKeys.contains(storageKey) + let isHidden = hiddenKeys.contains(storageKey) + + return HStack(spacing: 10) { + Button { + guard row.enabled else { return } + UISelectionFeedbackGenerator().selectionChanged() + pickModel(row.id) + } label: { + HStack(spacing: 8) { + Text(row.title) + .font(.system(size: 15, weight: row.selected ? .semibold : .medium)) + .foregroundStyle( + !row.enabled + ? Color.secondary.opacity(0.55) + : (isHidden ? Color.secondary : Color.primary) + ) + .lineLimit(1) + + if isDefaultHint { + badgePill("默认") + } else if let tag = row.tag, !tag.isEmpty, tag.count <= 10 { + badgePill(tag) + } + + Spacer(minLength: 4) + + if row.selected { + Image(systemName: "checkmark") + .font(.system(size: 13.5, weight: .bold)) + .foregroundStyle(.primary) + } + } + .padding(.vertical, 12) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(!row.enabled) + + if manageHiddenModels { + Button { + toggleHidden(storageKey) + } label: { + Image(systemName: isHidden ? "eye.slash" : "eye") + .font(.system(size: 14)) + .foregroundStyle(isHidden ? Color.orange : Color.secondary) + .frame(width: 28, height: 28) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(isHidden ? "取消隐藏模型" : "隐藏模型") + } + + Button { + toggleFavorite(storageKey) + } label: { + Image(systemName: isFavorite ? "star.fill" : "star") + .font(.system(size: 14.5)) + .foregroundStyle(isFavorite ? Color.yellow : Color.secondary.opacity(0.65)) + .frame(width: 28, height: 28) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(isFavorite ? "取消收藏" : "收藏模型") + } + .padding(.horizontal, 16) + } + + private func badgePill(_ text: String) -> some View { + Text(text) + .font(.system(size: 10.5, weight: .semibold)) + .foregroundStyle(.secondary) + .padding(.horizontal, 7) + .padding(.vertical, 2.5) + .background( + Capsule(style: .continuous) + .fill(Color(.tertiarySystemFill)) + ) + } + + // MARK: - Options Section (`会话参数`: Reasoning / Extra / Runtime) + + private var optionsSection: some View { + VStack(alignment: .leading, spacing: 8) { + Text("会话参数") + .font(.system(size: 13.5, weight: .semibold)) + .foregroundStyle(.secondary) + .padding(.horizontal, 4) + + VStack(spacing: 0) { + if let effort, !effort.levels.isEmpty { + let safeIndex = min(max(effort.index, 0), effort.levels.count - 1) + let useInlineChips = effort.levels.count <= 4 && effort.levels.allSatisfy { $0.count <= 6 } + + if useInlineChips { + HStack(spacing: 10) { + Text("推理强度") + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.primary) + + Spacer(minLength: 6) + + HStack(spacing: 3) { + ForEach(Array(effort.levels.enumerated()), id: \.offset) { idx, level in + let active = idx == safeIndex + Button { + guard idx != safeIndex else { return } + UISelectionFeedbackGenerator().selectionChanged() + setEffort(idx) + } label: { + Text(level) + .font(.system(size: 13, weight: active ? .semibold : .medium)) + .foregroundStyle(active ? Color.primary : Color.secondary) + .padding(.horizontal, 11) + .padding(.vertical, 5.5) + .background( + Capsule(style: .continuous) + .fill(active ? Color(.systemBackground) : Color.clear) + .shadow( + color: active ? .black.opacity(0.08) : .clear, + radius: 3, + x: 0, + y: 1 + ) + ) + .contentShape(Capsule()) + } + .buttonStyle(.plain) + } + } + .padding(3) + .background( + Capsule(style: .continuous) + .fill(Color(.tertiarySystemFill)) + ) + } + .padding(.horizontal, 16) + .padding(.vertical, 9.5) + } else { + disclosureRow( + label: "推理强度", + value: effort.levels[safeIndex] + ) { + navPath.append(.effort) + } + } + + if !extraChoices.isEmpty || !accessChoices.isEmpty { + Divider().padding(.leading, 16) + } + } + + ForEach(Array(extraChoices.enumerated()), id: \.element.id) { idx, extra in + disclosureRow( + label: extra.title, + value: extra.tag + ) { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + pickExtra(extra.id) + } + + if idx < extraChoices.count - 1 || !accessChoices.isEmpty { + Divider().padding(.leading, 16) + } + } + + if !accessChoices.isEmpty { + let currentRuntime = accessChoices.first(where: \.selected)?.title + ?? accessChoices.first?.title + disclosureRow( + label: "运行权限", + value: currentRuntime + ) { + navPath.append(.runtime) + } + } + } + .background( + RoundedRectangle(cornerRadius: 16, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + } + } + + private func disclosureRow( + label: String, + value: String?, + action: @escaping () -> Void + ) -> some View { + Button(action: action) { + HStack(spacing: 8) { + Text(label) + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.primary) + + Spacer(minLength: 8) + + if let value, !value.isEmpty { + Text(value) + .font(.system(size: 14.5)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + + Image(systemName: "chevron.right") + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(.tertiary) + } + .padding(.horizontal, 16) + .padding(.vertical, 13) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + + // MARK: - Catalog Management Section (`模型目录`) + + private var catalogManagementSection: some View { + VStack(alignment: .leading, spacing: 8) { + Text("模型目录") + .font(.system(size: 13.5, weight: .semibold)) + .foregroundStyle(.secondary) + .padding(.horizontal, 4) + + VStack(spacing: 0) { + HStack { + Text("管理隐藏模型") + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.primary) + Spacer() + Toggle("管理隐藏模型", isOn: $manageHiddenModels) + .labelsHidden() + } + .padding(.horizontal, 16) + .padding(.vertical, 9) + + if onAddCustomModel != nil { + Divider().padding(.leading, 16) + + Button { + customModelDraft = "" + showingCustomModelAlert = true + } label: { + HStack(spacing: 8) { + Text("自定义 / 中转模型…") + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.primary) + Spacer() + Image(systemName: "plus.circle") + .font(.system(size: 16, weight: .medium)) + .foregroundStyle(Color.accentColor) + } + .padding(.horizontal, 16) + .padding(.vertical, 13) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + } + .background( + RoundedRectangle(cornerRadius: 16, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + } + } + + // MARK: - Subpages (`推理强度` & `运行权限`) + + private var effortSubpage: some View { + List { + if let effort { + ForEach(Array(effort.levels.enumerated()), id: \.offset) { idx, level in + Button { + UISelectionFeedbackGenerator().selectionChanged() + setEffort(idx) + navPath.removeLast() + } label: { + HStack { + Text(level) + .font(.system(size: 15, weight: idx == effort.index ? .semibold : .regular)) + .foregroundStyle(.primary) + Spacer() + if idx == effort.index { + Image(systemName: "checkmark") + .font(.system(size: 14, weight: .semibold)) + .foregroundStyle(Color.accentColor) + } + } + } + .buttonStyle(.plain) + } + } + } + .navigationTitle("推理强度") + .navigationBarTitleDisplayMode(.inline) + } + + private var runtimeSubpage: some View { + List { + ForEach(accessChoices) { choice in + Button { + UISelectionFeedbackGenerator().selectionChanged() + pickAccess(choice.id) + navPath.removeLast() + } label: { + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 3) { + Text(choice.title) + .font(.system(size: 15, weight: choice.selected ? .semibold : .regular)) + .foregroundStyle(.primary) + if let detail = choice.detail, !detail.isEmpty { + Text(detail) + .font(.system(size: 12.5)) + .foregroundStyle(.secondary) + } + } + Spacer() + if choice.selected { + Image(systemName: "checkmark") + .font(.system(size: 14, weight: .semibold)) + .foregroundStyle(Color.accentColor) + } + } + .padding(.vertical, 2) + } + .buttonStyle(.plain) + } + } + .navigationTitle("运行权限") + .navigationBarTitleDisplayMode(.inline) + } + + // MARK: - Bottom Floating Filter + Search Capsule Bar + + private var bottomSearchAndFilterBar: some View { + HStack(spacing: 10) { + Menu { + Button { + activeFilter = .all + } label: { + HStack { + Label("全部模型", systemImage: "square.grid.2x2") + if activeFilter == .all { Image(systemName: "checkmark") } + } + } + + Button { + activeFilter = .favorites + } label: { + HStack { + Label("仅显示收藏", systemImage: "star") + if activeFilter == .favorites { Image(systemName: "checkmark") } + } + } + + if allProviderGroups.count > 1 { + Divider() + ForEach(allProviderGroups) { group in + Button { + activeFilter = .provider(group.title) + } label: { + HStack { + Text(group.title) + if activeFilter == .provider(group.title) { + Image(systemName: "checkmark") + } + } + } + } + } + } label: { + ZStack(alignment: .topTrailing) { + Image(systemName: "line.3.horizontal.decrease") + .font(.system(size: 16, weight: .semibold)) + .foregroundStyle(.primary) + .frame(width: 44, height: 44) + .background( + Circle() + .fill(Color(.secondarySystemGroupedBackground)) + .shadow(color: .black.opacity(0.10), radius: 10, x: 0, y: 4) + ) + .overlay( + Circle() + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.7) + ) + + if activeFilter != .all { + Circle() + .fill(Color.accentColor) + .frame(width: 9, height: 9) + .offset(x: -2, y: 2) + } + } + } + .accessibilityLabel("筛选模型") + + HStack(spacing: 8) { + Image(systemName: "magnifyingglass") + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.secondary) + + TextField("搜索模型…", text: $searchQuery) + .font(.system(size: 15)) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + + if !searchQuery.isEmpty { + Button { + searchQuery = "" + } label: { + Image(systemName: "xmark.circle.fill") + .font(.system(size: 15)) + .foregroundStyle(.tertiary) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, 14) + .frame(height: 44) + .background( + Capsule(style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + .shadow(color: .black.opacity(0.10), radius: 10, x: 0, y: 4) + ) + .overlay( + Capsule(style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.7) + ) + } + .padding(.horizontal, 16) + .padding(.top, 8) + .padding(.bottom, 10) + .background( + LinearGradient( + colors: [ + Color(.systemGroupedBackground).opacity(0), + Color(.systemGroupedBackground).opacity(0.92), + Color(.systemGroupedBackground), + ], + startPoint: .top, + endPoint: .bottom + ) + .ignoresSafeArea() + ) + } +} diff --git a/App/VibeXAccountStore.swift b/App/VibeXAccountStore.swift index 3f37d46..dca2b43 100644 --- a/App/VibeXAccountStore.swift +++ b/App/VibeXAccountStore.swift @@ -202,7 +202,7 @@ final class VibeXAccountStore { } var canUseCloudRelay: Bool { - overview?.relayPermission != false + isSignedIn && (overview?.relayPermission != false) } init(defaults: UserDefaults = .standard) { @@ -224,6 +224,7 @@ final class VibeXAccountStore { func attach(serverStore: ServerStore) { self.attachedServerStore = serverStore serverStore.accountStore = self + serverStore.setCloudRelayAuthorized(canUseCloudRelay) if isSignedIn { Task { await syncHosts(with: serverStore) } } @@ -328,6 +329,7 @@ final class VibeXAccountStore { cloudSavedHosts = [] lastSyncedAt = nil requiresLogin = true + attachedServerStore?.handleAccountSignOut() if let oldToken, !oldToken.isEmpty { _ = try? await performRawRequest( @@ -355,6 +357,7 @@ final class VibeXAccountStore { authenticated: true ) overview = fetched + attachedServerStore?.setCloudRelayAuthorized(canUseCloudRelay) if let encoded = try? JSONEncoder().encode(fetched) { defaults.set(encoded, forKey: Self.cachedOverviewKey) } diff --git a/App/VibeXCompanionApp.swift b/App/VibeXCompanionApp.swift index 4a48b29..be1a489 100644 --- a/App/VibeXCompanionApp.swift +++ b/App/VibeXCompanionApp.swift @@ -2,10 +2,12 @@ import SwiftUI @main struct VibeXCompanionApp: App { + @Environment(\.scenePhase) private var scenePhase @State private var servers = ServerStore() @State private var appearance = AppAppearanceStore() @State private var account = VibeXAccountStore() @State private var connectFlow = DesktopConnectFlow() + @State private var appUpdates = AppUpdateStore() private var showsLogin: Bool { !account.isSignedIn && (servers.profiles.isEmpty || account.requiresLogin) @@ -24,11 +26,24 @@ struct VibeXCompanionApp: App { .environment(appearance) .environment(account) .environment(connectFlow) + .environment(appUpdates) + .environment(\.locale, appearance.effectiveLocale) .task { account.attach(serverStore: servers) + appUpdates.checkIfDue() + } + .onChange(of: scenePhase) { _, phase in + if phase == .active { + appUpdates.checkIfDue() + } } .onChange(of: account.completedSignIns) { _, _ in - connectFlow.presentPicker(servers: servers) + connectFlow.autoConnectOnSignIn(servers: servers, account: account) + } + .onChange(of: account.desktops.count) { _, count in + if count == 1 { + connectFlow.autoConnectInitialIfNeeded(servers: servers, account: account) + } } .onChange(of: servers.connectionSuccessCount) { _, _ in account.waiveLoginRequirement() @@ -43,6 +58,12 @@ struct VibeXCompanionApp: App { PairView() .environment(servers) } + .sheet(isPresented: $appUpdates.isSheetPresented) { + if let release = appUpdates.latestRelease { + AppUpdateSheet(release: release) + .environment(appUpdates) + } + } .alert( "局域网已断开,是否切换至云服务?", isPresented: Binding( diff --git a/Info.plist b/Info.plist index 5964b42..69fede3 100644 --- a/Info.plist +++ b/Info.plist @@ -17,6 +17,10 @@ 发现在局域网内运行的 VibeX 电脑并建立实时连接 NSPhotoLibraryUsageDescription 从相册选择配对二维码图片或向对话附加图片 + NSMicrophoneUsageDescription + 使用麦克风录制语音输入并转写为对话文字 + NSSpeechRecognitionUsageDescription + 将语音输入实时识别为发送给 AI 助手的文字 NSSupportsLiveActivities NSSupportsLiveActivitiesFrequentUpdates diff --git a/Sources/CompanionCore/AgentCatalog.swift b/Sources/CompanionCore/AgentCatalog.swift index 888e1dc..bd75857 100644 --- a/Sources/CompanionCore/AgentCatalog.swift +++ b/Sources/CompanionCore/AgentCatalog.swift @@ -1,10 +1,12 @@ import Foundation -/// An Agent configured in the desktop's settings, as listed by `conversation_catalog`. +/// An Agent configured in the desktop's settings, as listed by `conversation_catalog` +/// and gated for local installation eligibility via `agent_management_bar`. public struct CatalogAgent: Equatable, Sendable, Identifiable { public let id: String public let displayName: String public let usable: Bool + public let lifecycle: String? public let currentModeID: String? public let modes: [SessionMode] public let options: [ConfigOption] @@ -13,6 +15,7 @@ public struct CatalogAgent: Equatable, Sendable, Identifiable { id: String, displayName: String, usable: Bool, + lifecycle: String? = nil, currentModeID: String?, modes: [SessionMode], options: [ConfigOption] @@ -20,6 +23,7 @@ public struct CatalogAgent: Equatable, Sendable, Identifiable { self.id = id self.displayName = displayName self.usable = usable + self.lifecycle = lifecycle self.currentModeID = currentModeID self.modes = modes self.options = options @@ -154,28 +158,90 @@ public enum AgentCatalogParser { return [] } - public static func agents(from catalog: JSONValue) -> [CatalogAgent] { - (catalog["agents"]?.arrayValue ?? []).compactMap { item in + public static func agents(from catalog: JSONValue, managementBar: JSONValue? = nil) -> [CatalogAgent] { + let rawAgents = catalog["agents"]?.arrayValue ?? [] + + var managementRunnableIDs: Set? + var managementPositions: [String: Int] = [:] + if let barRows = managementBar?.arrayValue, !barRows.isEmpty { + var runnable = Set() + for (idx, row) in barRows.enumerated() { + guard let id = row["agent_id"]?.stringValue ?? row["agentId"]?.stringValue else { continue } + let pos: Int = { + if case .number(let n)? = row["position"] { return Int(n) } + return idx + }() + managementPositions[id] = pos + + let enabled = (row["enabled"] == .bool(true)) + let retired = (row["retired"] == .bool(true)) + let lifecycle = (row["lifecycle"]?.stringValue ?? "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + let activeOp = (row["active_operation"]?.stringValue ?? row["activeOperation"]?.stringValue ?? "") + .trimmingCharacters(in: .whitespacesAndNewlines) + let localPath = (row["local_runtime"]?["path"]?.stringValue ?? row["localRuntime"]?["path"]?.stringValue ?? "") + .trimmingCharacters(in: .whitespacesAndNewlines) + if enabled && !retired && activeOp.isEmpty && (lifecycle == "ready" || !localPath.isEmpty) { + runnable.insert(id) + } + } + managementRunnableIDs = runnable + } + + let hasLifecycleSignal = rawAgents.contains { + !($0["lifecycle"]?.stringValue ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + let indexed: [(Int, CatalogAgent)] = rawAgents.enumerated().compactMap { originalIdx, item in guard let id = item["id"]?.stringValue else { return nil } - var usable = false - if case .bool(let flag)? = item["usable"] { usable = flag } + var catalogUsable = false + if case .bool(let flag)? = item["usable"] { catalogUsable = flag } + + let rawLifecycle = item["lifecycle"]?.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines) + let normalizedLifecycle = (rawLifecycle?.isEmpty == false) ? rawLifecycle : nil let rawModes = parseJSONArray(item["sessionModes"] ?? item["session_modes"] ?? item["sessionModesJson"] ?? item["session_modes_json"]) let rawOptions = parseJSONArray(item["sessionConfig"] ?? item["session_config"] ?? item["sessionConfigJson"] ?? item["session_config_json"]) - return CatalogAgent( + let modes = rawModes.compactMap(SessionStateBuilder.mode) + let options = rawOptions.compactMap(SessionStateBuilder.option) + + let effectiveUsable: Bool + if let managementRunnableIDs { + effectiveUsable = catalogUsable && managementRunnableIDs.contains(id) + } else if hasLifecycleSignal { + let isInstalledByCatalog = (normalizedLifecycle?.lowercased() == "ready") || !options.isEmpty || !modes.isEmpty + effectiveUsable = catalogUsable && isInstalledByCatalog + } else { + effectiveUsable = catalogUsable + } + + let agent = CatalogAgent( id: id, displayName: item["displayName"]?.stringValue ?? item["display_name"]?.stringValue ?? id, - usable: usable, + usable: effectiveUsable, + lifecycle: normalizedLifecycle, currentModeID: item["currentMode"]?.stringValue ?? item["current_mode"]?.stringValue, - modes: rawModes.compactMap(SessionStateBuilder.mode), - options: rawOptions.compactMap(SessionStateBuilder.option) + modes: modes, + options: options ) + return (originalIdx, agent) + } + + guard !managementPositions.isEmpty else { + return indexed.map(\.1) } + return indexed.sorted { lhs, rhs in + let lPos = managementPositions[lhs.1.id] ?? (10_000 + lhs.0) + let rPos = managementPositions[rhs.1.id] ?? (10_000 + rhs.0) + if lPos != rPos { return lPos < rPos } + return lhs.0 < rhs.0 + }.map(\.1) } } extension HostClient { public func agentCatalog() async throws -> [CatalogAgent] { - let catalog: JSONValue = try await call("conversation_catalog", as: JSONValue.self) - return AgentCatalogParser.agents(from: catalog) + async let catalogTask = call("conversation_catalog", as: JSONValue.self) + async let managementBarTask = try? call("agent_management_bar", as: JSONValue.self) + let (catalog, managementBar) = try await (catalogTask, managementBarTask) + return AgentCatalogParser.agents(from: catalog, managementBar: managementBar) } } diff --git a/Sources/CompanionCore/HostModels.swift b/Sources/CompanionCore/HostModels.swift index 3f89b6c..e75c48b 100644 --- a/Sources/CompanionCore/HostModels.swift +++ b/Sources/CompanionCore/HostModels.swift @@ -51,9 +51,21 @@ public struct ConversationListItem: Decodable, Identifiable, Equatable, Sendable public var updatedAt: Date? { Self.parseDate(updated_at) } static func parseDate(_ text: String) -> Date? { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return nil } let fractional = ISO8601DateFormatter() fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds] - return fractional.date(from: text) ?? ISO8601DateFormatter().date(from: text) + if let d = fractional.date(from: trimmed) ?? ISO8601DateFormatter().date(from: trimmed) { + return d + } + let sqlite = DateFormatter() + sqlite.locale = Locale(identifier: "en_US_POSIX") + sqlite.timeZone = TimeZone(secondsFromGMT: 0) + for fmt in ["yyyy-MM-dd HH:mm:ss.SSSSSS", "yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss"] { + sqlite.dateFormat = fmt + if let d = sqlite.date(from: trimmed) { return d } + } + return nil } } @@ -167,6 +179,28 @@ public struct TimelineItem: Identifiable, Equatable, Sendable { public var segments: [TimelineSegment] = [] public var durationMs: Int? + public init( + id: String, + role: Role, + text: String, + thinking: String = "", + tools: [ToolStep] = [], + plan: [PlanTask] = [], + changes: [FileChangeItem] = [], + segments: [TimelineSegment] = [], + durationMs: Int? = nil + ) { + self.id = id + self.role = role + self.text = text + self.thinking = thinking + self.tools = tools + self.plan = plan + self.changes = changes + self.segments = segments + self.durationMs = durationMs + } + public var hasTrace: Bool { !thinking.isEmpty || !tools.isEmpty || !changes.isEmpty } } diff --git a/Sources/CompanionCore/PairingClient.swift b/Sources/CompanionCore/PairingClient.swift index c828a03..ec2eb04 100644 --- a/Sources/CompanionCore/PairingClient.swift +++ b/Sources/CompanionCore/PairingClient.swift @@ -891,7 +891,7 @@ public struct URLSessionTransport: HttpTransport { } } - var request = URLRequest(url: target, timeoutInterval: isPrivateLan ? 0.85 : 10) + var request = URLRequest(url: target, timeoutInterval: isPrivateLan ? 15 : 20) request.httpMethod = method for (key, value) in headers { request.setValue(value, forHTTPHeaderField: key) } request.setValue(e2ee.clientPublicKeyBase64, forHTTPHeaderField: E2eeSessionManager.headerClientPub) diff --git a/Tests/CompanionCoreTests/HostClientTests.swift b/Tests/CompanionCoreTests/HostClientTests.swift index bc2f32b..c6dafec 100644 --- a/Tests/CompanionCoreTests/HostClientTests.swift +++ b/Tests/CompanionCoreTests/HostClientTests.swift @@ -288,6 +288,35 @@ private final class RecordingTransport: HttpTransport, @unchecked Sendable { #expect(agents[0].currentModeID == "full") } +@Test func catalogMarksUninstalledBuiltInAgentsUnusableViaManagementBarAndLifecycleFallback() throws { + let catalogRaw = """ + {"projects":[],"workspaces":[],"agents":[ + {"id":"claude_code","usable":true,"lifecycle":"ready","displayName":"Claude Code", + "sessionConfig":[{"key":"model","label":"Model","category":"model","value":"opus","choices":[{"value":"opus","label":"Opus 5 (opus)"}]}]}, + {"id":"codex","usable":true,"lifecycle":"ready","displayName":"Codex", + "sessionConfig":[{"key":"model","label":"Model","category":"model","value":"gpt-6-sol","choices":[{"value":"gpt-6-sol","label":"GPT-6 Sol"}]}]}, + {"id":"pi","usable":true,"lifecycle":null,"displayName":"Pi"}, + {"id":"opencode","usable":true,"lifecycle":null,"displayName":"OpenCode"} + ]} + """ + let barRaw = """ + [ + {"agent_id":"claude_code","display_name":"Claude Code","enabled":true,"retired":false,"position":0,"lifecycle":"ready","active_operation":null}, + {"agent_id":"codex","display_name":"Codex","enabled":true,"retired":false,"position":1,"lifecycle":"ready","active_operation":null}, + {"agent_id":"pi","display_name":"Pi","enabled":true,"retired":false,"position":2,"lifecycle":"uninstalled","active_operation":null}, + {"agent_id":"opencode","display_name":"OpenCode","enabled":true,"retired":false,"position":3,"lifecycle":"uninstalled","active_operation":null} + ] + """ + let catalog = try JSONDecoder().decode(JSONValue.self, from: Data(catalogRaw.utf8)) + let bar = try JSONDecoder().decode(JSONValue.self, from: Data(barRaw.utf8)) + + let withBar = AgentCatalogParser.agents(from: catalog, managementBar: bar) + #expect(withBar.filter(\.usable).map(\.id) == ["claude_code", "codex"]) + + let fallbackOnly = AgentCatalogParser.agents(from: catalog, managementBar: nil) + #expect(fallbackOnly.filter(\.usable).map(\.id) == ["claude_code", "codex"]) +} + @Test func liveControlsSnapshotYieldsModesAndOptions() throws { let raw = """ {"modes":[{"id":"ro","label":"Read-only"}],"current_mode":"ro","config_options":[ diff --git a/Tests/CompanionCoreTests/PairingClientTests.swift b/Tests/CompanionCoreTests/PairingClientTests.swift index 52eb64c..49a306b 100644 --- a/Tests/CompanionCoreTests/PairingClientTests.swift +++ b/Tests/CompanionCoreTests/PairingClientTests.swift @@ -237,6 +237,25 @@ private struct OfflineTransport: HttpTransport { #expect(host.displayName == "ltfdeMacBook-Pro") } +@Test func requestConnectReturnsImmediateCredentialWhenSameAccountAutoApproved() async throws { + let autoApprovedJSON = """ + {"request_id":"req-auto","host_id":"host-abc","host_name":"MacStudio.local","sas_code":"1204","status":"approved","credential":\(credentialJSON)} + """ + let transport = ScriptedTransport([autoApprovedJSON], statuses: [201]) + let client = PairingClient(transport: transport) + let origin = try HostOrigin.parse("http://192.168.1.10:17891") + + let result = try await client.requestConnect( + origin: origin, + deviceName: "iPhone 16 Pro", + accountToken: "vbx_user_token" + ) + #expect(result.status == "approved") + #expect(result.sasCode == "1204") + #expect(result.credential?.access_token == "device-token") + #expect(transport.requests.count == 1) +} + @Test func e2eeHandshakeAndEncryptionRoundTrip() throws { let clientA = E2eeSessionManager() let clientB = E2eeSessionManager() diff --git a/VibeXCompanion.xcodeproj/project.pbxproj b/VibeXCompanion.xcodeproj/project.pbxproj index 1d3cb05..54209d7 100644 --- a/VibeXCompanion.xcodeproj/project.pbxproj +++ b/VibeXCompanion.xcodeproj/project.pbxproj @@ -260,16 +260,16 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 4; + CURRENT_PROJECT_VERSION = 6; DEVELOPMENT_TEAM = DD67H4228U; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = Info.plist; - INFOPLIST_KEY_CFBundleDisplayName = VibeX; + INFOPLIST_KEY_CFBundleDisplayName = Dimo; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; INFOPLIST_KEY_UILaunchScreen_Generation = YES; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortraitUpsideDown"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; - MARKETING_VERSION = 0.4.5; + MARKETING_VERSION = 0.4.7; PRODUCT_BUNDLE_IDENTIFIER = dev.vibex.companion.ios; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; @@ -284,16 +284,16 @@ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 4; + CURRENT_PROJECT_VERSION = 6; DEVELOPMENT_TEAM = DD67H4228U; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = Info.plist; - INFOPLIST_KEY_CFBundleDisplayName = VibeX; + INFOPLIST_KEY_CFBundleDisplayName = Dimo; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; INFOPLIST_KEY_UILaunchScreen_Generation = YES; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortraitUpsideDown"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; - MARKETING_VERSION = 0.4.5; + MARKETING_VERSION = 0.4.7; PRODUCT_BUNDLE_IDENTIFIER = dev.vibex.companion.ios; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; @@ -307,17 +307,17 @@ buildSettings = { ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 4; + CURRENT_PROJECT_VERSION = 6; DEVELOPMENT_TEAM = DD67H4228U; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = TaskWidgetInfo.plist; - INFOPLIST_KEY_CFBundleDisplayName = "VibeX 任务"; + INFOPLIST_KEY_CFBundleDisplayName = "Dimo 任务"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MARKETING_VERSION = 0.4.5; + MARKETING_VERSION = 0.4.7; PRODUCT_BUNDLE_IDENTIFIER = dev.vibex.companion.ios.TaskWidget; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; @@ -332,17 +332,17 @@ buildSettings = { ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 4; + CURRENT_PROJECT_VERSION = 6; DEVELOPMENT_TEAM = DD67H4228U; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = TaskWidgetInfo.plist; - INFOPLIST_KEY_CFBundleDisplayName = "VibeX 任务"; + INFOPLIST_KEY_CFBundleDisplayName = "Dimo 任务"; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MARKETING_VERSION = 0.4.5; + MARKETING_VERSION = 0.4.7; PRODUCT_BUNDLE_IDENTIFIER = dev.vibex.companion.ios.TaskWidget; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES;