diff --git a/.gitignore b/.gitignore index 4cfbcdae6..cadd51742 100644 --- a/.gitignore +++ b/.gitignore @@ -82,6 +82,7 @@ __pycache__/ src-tauri/gen/ src-tauri/tauri.dev.generated.conf.json src-tauri/binaries/ +plugins/computer-use/bin/ **/.codeg-fs-*.tmp **/*.cstemp diff --git a/crates/agents/src/parsers/acp_native.rs b/crates/agents/src/parsers/acp_native.rs index 8fbf86ff8..8459fd054 100644 --- a/crates/agents/src/parsers/acp_native.rs +++ b/crates/agents/src/parsers/acp_native.rs @@ -338,6 +338,7 @@ struct PendingTurn { duration_ms: Option, model: Option, agent_message_id: Option, + last_text_message_id: Option, has_content: bool, } @@ -890,12 +891,20 @@ fn apply_update( } let p = open_turn!(); p.last_at_ms = at_ms; + let chunk_message_id = chunk + .message_id + .as_ref() + .map(|id| id.to_string()) + .filter(|id| !id.trim().is_empty()); if p.agent_message_id.is_none() { - p.agent_message_id = chunk - .message_id - .as_ref() - .map(|id| id.to_string()) - .filter(|id| !id.trim().is_empty()); + p.agent_message_id = chunk_message_id.clone(); + } + let message_id_changed = matches!( + (&p.last_text_message_id, &chunk_message_id), + (Some(prev), Some(curr)) if prev != curr + ); + if chunk_message_id.is_some() { + p.last_text_message_id = chunk_message_id; } match &chunk.content { agent_client_protocol::schema::v1::ContentBlock::Image(image) => { @@ -910,6 +919,14 @@ fn apply_update( } other => { let text = content_block_text(other); + if message_id_changed + && !text.is_empty() + && let Some(ContentBlock::Text { text: existing }) = p.blocks.last_mut() + && !existing.is_empty() + && !existing.ends_with('\n') + { + existing.push('\n'); + } p.push_text(&text, false); } } diff --git a/crates/application/src/domain.rs b/crates/application/src/domain.rs index 6d1e8616b..7c0ae832f 100644 --- a/crates/application/src/domain.rs +++ b/crates/application/src/domain.rs @@ -134,7 +134,7 @@ domain_commands! { PluginActionCatalog => "plugin_action_catalog" / "plugin.read", PluginControlCatalog => "plugin_control_catalog" / "plugin.read", OfficialProductMcpState => "official_product_mcp_state" / "plugin.read", - CollaborationCall => "collaboration_call" / "application.call", + CollaborationCall => "collaboration_call" / "conversation.write", PluginMcpStatus => "plugin_mcp_status" / "plugin.read", PluginMcpEnsureRunning => "plugin_mcp_ensure_running" / "plugin.write", PluginProductDetail => "plugin_product_detail" / "plugin.read", @@ -197,9 +197,9 @@ domain_commands! { RepoCheckoutBranch => "checkout_repo_branch" / "application.call", RepoCreateBranch => "create_repo_branch" / "application.call", RepoDeleteBranch => "delete_repo_branch" / "application.call", - WorkspaceList => "get_workspaces" / "application.call", - WorkspaceListByProject => "get_project_workspaces" / "application.call", - WorkspaceGet => "get_workspace" / "application.call", + WorkspaceList => "get_workspaces" / "conversation.read", + WorkspaceListByProject => "get_project_workspaces" / "conversation.read", + WorkspaceGet => "get_workspace" / "conversation.read", WorkspaceCount => "get_workspace_count" / "application.call", WorkspaceRepos => "get_workspace_repos" / "application.call", WorkspaceGitStatus => "get_workspace_git_status" / "application.call", @@ -243,18 +243,18 @@ domain_commands! { ConversationEventsSince => "conversation_events_since" / "conversation.read", ConversationEnsureSessionControls => "conversation_ensure_session_controls" / "conversation.write", ConversationTouch => "conversation_touch" / "conversation.write", - SessionList => "get_sessions" / "application.call", - SessionSummaries => "get_session_summaries" / "application.call", - SessionGet => "get_session" / "application.call", - SessionCreate => "create_session" / "application.call", - SessionCreateProjectRoot => "create_project_root_session" / "application.call", + SessionList => "get_sessions" / "conversation.read", + SessionSummaries => "get_session_summaries" / "conversation.read", + SessionGet => "get_session" / "conversation.read", + SessionCreate => "create_session" / "conversation.write", + SessionCreateProjectRoot => "create_project_root_session" / "conversation.write", SessionCreateProject => "create_project_session" / "application.call", - SessionEnsureWorkspace => "ensure_project_workspace" / "application.call", - SessionRename => "rename_session" / "application.call", - SessionUpdateStatus => "update_session_status" / "application.call", - SessionMarkViewed => "mark_session_viewed" / "application.call", - SessionSetPinned => "set_session_pinned" / "application.call", - SessionDelete => "delete_session" / "application.call", + SessionEnsureWorkspace => "ensure_project_workspace" / "conversation.write", + SessionRename => "rename_session" / "conversation.write", + SessionUpdateStatus => "update_session_status" / "conversation.write", + SessionMarkViewed => "mark_session_viewed" / "conversation.write", + SessionSetPinned => "set_session_pinned" / "conversation.write", + SessionDelete => "delete_session" / "conversation.write", FileTree => "get_file_tree" / "application.call", FileRead => "read_file_content" / "application.call", FileSave => "save_file_content" / "application.call", @@ -276,13 +276,13 @@ domain_commands! { TerminalClose => "close_terminal" / "application.call", TerminalAttach => "attach_terminal" / "application.call", TerminalSnapshot => "terminal_snapshot" / "application.call", - AgentManagementBar => "agent_management_bar" / "application.call", + AgentManagementBar => "agent_management_bar" / "conversation.read", AgentManagementDetail => "agent_management_detail" / "application.call", AgentManagementSetEnabled => "agent_management_set_enabled" / "application.call", AgentManagementRefresh => "agent_management_refresh" / "application.call", AgentCapabilityCatalog => "agent_capability_catalog" / "application.call", AgentSkillsList => "list_agent_skills" / "application.call", - UserSystemInfo => "get_user_system_info" / "application.call", + UserSystemInfo => "get_user_system_info" / "conversation.read", ArtifactList => "artifact_list" / "artifact.read", ArtifactOpenPreview => "artifact_open_preview" / "artifact.preview", ArtifactClosePreview => "artifact_close_preview" / "artifact.preview", @@ -336,7 +336,7 @@ domain_commands! { AgentRefreshCapabilityCatalog => "agent_refresh_capability_catalog" / "application.call", AgentCapabilityCatalogFresh => "agent_capability_catalog_fresh" / "application.call", AgentListLiveTerminals => "agent_list_live_terminals" / "application.call", - AgentPlanUsage => "agent_plan_usage" / "application.call", + AgentPlanUsage => "agent_plan_usage" / "conversation.read", FrontendPreferencesGet => "get_frontend_preferences" / "application.call", FrontendPreferencesUpdate => "update_frontend_preferences" / "application.call", ProjectWorktreeSettingsGet => "get_project_worktree_settings" / "application.call", @@ -486,8 +486,8 @@ domain_commands! { GetClaudeSettings => "get_claude_settings" / "application.call", UpdateClaudeSettings => "update_claude_settings" / "application.call", GetClaudeSettingsPath => "get_claude_settings_path" / "application.call", - ScanLocalSkills => "scan_local_skills" / "application.call", - ReadLocalSkill => "read_local_skill" / "application.call", + ScanLocalSkills => "scan_local_skills" / "conversation.read", + ReadLocalSkill => "read_local_skill" / "conversation.read", SearchSkillMarket => "search_skill_market" / "application.call", GetMarketSkillDetail => "get_market_skill_detail" / "application.call", InstallMarketSkill => "install_market_skill" / "application.call", @@ -496,7 +496,7 @@ domain_commands! { ReadAgentSkill => "read_agent_skill" / "application.call", SaveAgentSkill => "save_agent_skill" / "application.call", DeleteAgentSkill => "delete_agent_skill" / "application.call", - McpScanLocal => "mcp_scan_local" / "application.call", + McpScanLocal => "mcp_scan_local" / "conversation.read", McpListMarketplaces => "mcp_list_marketplaces" / "application.call", McpSearchMarketplace => "mcp_search_marketplace" / "application.call", McpGetMarketplaceServerDetail => "mcp_get_marketplace_server_detail" / "application.call", @@ -570,7 +570,7 @@ domain_commands! { StartWorkspaceDevServer => "start_workspace_dev_server" / "application.call", GetFirstUserMessage => "get_first_user_message" / "application.call", RespondToApproval => "respond_to_approval" / "application.call", - GetProjectUsageStatistics => "get_project_usage_statistics" / "application.call", + GetProjectUsageStatistics => "get_project_usage_statistics" / "conversation.read", ClearLocalAppData => "clear_local_app_data" / "application.call", CheckAppRelease => "check_app_release" / "application.call", ApplyHostUpgrade => "apply_host_upgrade" / "application.call", diff --git a/crates/remote-protocol/src/device_auth.rs b/crates/remote-protocol/src/device_auth.rs index ae066cec8..2880e3400 100644 --- a/crates/remote-protocol/src/device_auth.rs +++ b/crates/remote-protocol/src/device_auth.rs @@ -128,6 +128,7 @@ impl DevicePermissionPreset { "conversation.question", "conversation.cancel", "conversation.steer", + "plugin.read", "artifact.read", "workflow.read", "automation.read", diff --git a/crates/server/src/domains.rs b/crates/server/src/domains.rs index 3a773f82f..dadf40ed9 100644 --- a/crates/server/src/domains.rs +++ b/crates/server/src/domains.rs @@ -2001,7 +2001,16 @@ impl ServerApplicationDomains { } async fn user_system_info(&self) -> Result { - crate::host::catalog::config::user_system_info(self).await + let mut value = crate::host::catalog::config::user_system_info(self).await?; + if let (Some(object), Ok(catalog)) = ( + value.as_object_mut(), + self.plugin_control_catalog().await, + ) { + if let Some(plugins) = catalog.get("plugins").cloned() { + object.insert("plugins".to_string(), plugins); + } + } + Ok(value) } async fn artifact_list(&self, args: Value) -> Result { diff --git a/crates/server/src/host/collaboration.rs b/crates/server/src/host/collaboration.rs index eb832ffd9..78775befe 100644 --- a/crates/server/src/host/collaboration.rs +++ b/crates/server/src/host/collaboration.rs @@ -742,7 +742,11 @@ impl HostCollaborationHost { .await .map_err(host_error)? { - let avatar = optional_text(input, &["avatar"]); + let avatar = input.get("avatar").and_then(|v| match v { + Value::String(s) if !s.trim().is_empty() => Some(s.trim().to_string()), + Value::Object(_) => Some(v.to_string()), + _ => None, + }); let color = optional_text(input, &["color"]); if avatar.is_some() || color.is_some() { sidebar::update_member_profile( @@ -947,12 +951,22 @@ impl HostCollaborationHost { ) .await .map_err(host_error)?; - let is_supervisor = if let Some(ref mid) = identity_member_id { - collaboration::is_member_supervisor(&self.pool, mid) + let (is_supervisor, avatar, color) = if let Some(ref mid) = identity_member_id { + let sup = collaboration::is_member_supervisor(&self.pool, mid) .await - .unwrap_or(false) + .unwrap_or(false); + let profile: Option<(Option, Option)> = sqlx::query_as( + "SELECT avatar, color FROM collaboration_members WHERE id = ?", + ) + .bind(mid) + .fetch_optional(&self.pool) + .await + .ok() + .flatten(); + let (av, col) = profile.unwrap_or((None, None)); + (sup, av, col) } else { - false + (false, None, None) }; let mut value = serde_json::to_value(&member).map_err(|error| { CollaborationHostError::new("conversation_control_failed", error.to_string()) @@ -960,6 +974,12 @@ impl HostCollaborationHost { if let Some(object) = value.as_object_mut() { object.insert("identity_member_id".into(), json!(identity_member_id)); object.insert("is_supervisor".into(), json!(is_supervisor)); + if let Some(av) = avatar { + object.insert("avatar".into(), json!(av)); + } + if let Some(col) = color { + object.insert("color".into(), json!(col)); + } } listed.push(value); } diff --git a/crates/server/src/host/events.rs b/crates/server/src/host/events.rs index 3715ed3c5..742ede8ee 100644 --- a/crates/server/src/host/events.rs +++ b/crates/server/src/host/events.rs @@ -56,7 +56,7 @@ pub const HOST_EVENT_CHANNELS: &[HostEventChannel] = &[ HostEventChannel { prefix: "workspace-sessions-changed", durability: EventDurability::Invalidation, - required_scope: "application.call", + required_scope: "conversation.read", }, HostEventChannel { prefix: "workspace-focus-conversation", @@ -86,7 +86,7 @@ pub const HOST_EVENT_CHANNELS: &[HostEventChannel] = &[ HostEventChannel { prefix: "desktop-session-attention", durability: EventDurability::BestEffort, - required_scope: "application.call", + required_scope: "conversation.read", }, HostEventChannel { prefix: "file-tree-stream", diff --git a/crates/server/src/host/workspace_files.rs b/crates/server/src/host/workspace_files.rs index 7de92c346..f016c924b 100644 --- a/crates/server/src/host/workspace_files.rs +++ b/crates/server/src/host/workspace_files.rs @@ -6,10 +6,12 @@ //! credential files. A scratch workspace's root can be the user's home directory, //! so the policy cannot rely on the root being a clean project. +use std::collections::HashMap; use std::path::{Component, Path, PathBuf}; use application::ApplicationError; -use db::models::workspace_repo::WorkspaceRepo; +use db::models::{project::Project, workspace_repo::WorkspaceRepo}; +use deployment::Deployment; use serde::{Deserialize, Serialize}; use serde_json::Value; use uuid::Uuid; @@ -62,33 +64,59 @@ struct FileContent { struct ProjectSummary { id: Uuid, name: String, + root_path: String, + parent_project_id: Option, + is_git: bool, + is_home: bool, workspace_ids: Vec, } impl ServerApplicationDomains { - /// Projects with the workspaces they own, so a client can group conversations by project. + /// Imported projects (matching the desktop's "已导入项目" list) with their workspaces, + /// ensuring each project has a root workspace so Companion devices can start conversations in it. pub(crate) async fn conversation_projects(&self) -> Result { - let rows = sqlx::query_as::<_, (Uuid, String, Uuid)>( - r#"SELECT p.id, p.name, w.id - FROM workspaces w - JOIN projects p ON p.id = w.project_id - ORDER BY p.name COLLATE NOCASE, w.created_at"#, + let _ = self + .deployment + .project() + .migrate_multi_repo_projects(&self.pool, self.deployment.repo()) + .await; + let _ = self + .deployment + .project() + .ensure_home_project(&self.pool, self.deployment.repo()) + .await; + let projects = Project::find_all(&self.pool) + .await + .map_err(internal_error)?; + for project in &projects { + let _ = self.ensure_root_workspace(project.id, None).await; + } + let rows = sqlx::query_as::<_, (Uuid, Uuid)>( + r#"SELECT project_id, id + FROM workspaces + WHERE project_id IS NOT NULL + ORDER BY use_worktree ASC, created_at DESC"#, ) .fetch_all(&self.pool) .await .map_err(internal_error)?; - let mut projects: Vec = Vec::new(); - for (id, name, workspace_id) in rows { - match projects.iter_mut().find(|project| project.id == id) { - Some(project) => project.workspace_ids.push(workspace_id), - None => projects.push(ProjectSummary { - id, - name, - workspace_ids: vec![workspace_id], - }), - } + let mut by_project: HashMap> = HashMap::new(); + for (project_id, workspace_id) in rows { + by_project.entry(project_id).or_default().push(workspace_id); } - serialize(projects) + let summaries: Vec = projects + .into_iter() + .map(|project| ProjectSummary { + workspace_ids: by_project.remove(&project.id).unwrap_or_default(), + id: project.id, + name: project.name, + root_path: project.root_path, + parent_project_id: project.parent_project_id, + is_git: project.is_git, + is_home: project.is_home, + }) + .collect(); + serialize(summaries) } /// The directory the Agent works in; scratch workspaces have one even without a repository. diff --git a/crates/server/src/host_ops/mod.rs b/crates/server/src/host_ops/mod.rs index a8be49abb..d5ca7e897 100644 --- a/crates/server/src/host_ops/mod.rs +++ b/crates/server/src/host_ops/mod.rs @@ -1513,7 +1513,7 @@ impl ServerApplicationDomains { } } - async fn ensure_root_workspace( + pub(crate) async fn ensure_root_workspace( &self, project_id: Uuid, branch: Option<&str>, diff --git a/docs/protocol/v1/generated/swift/RemoteProtocolModels.swift b/docs/protocol/v1/generated/swift/RemoteProtocolModels.swift index 5e3a9ebff..bd2eccd82 100644 --- a/docs/protocol/v1/generated/swift/RemoteProtocolModels.swift +++ b/docs/protocol/v1/generated/swift/RemoteProtocolModels.swift @@ -2,7 +2,7 @@ import Foundation -public enum JSONValue: Codable, Equatable { +public enum JSONValue: Codable, Equatable, Sendable { case null case bool(Bool) case number(Double) diff --git a/mobile/ios/App/AgentIconView.swift b/mobile/ios/App/AgentIconView.swift new file mode 100644 index 000000000..2e0df1ab5 --- /dev/null +++ b/mobile/ios/App/AgentIconView.swift @@ -0,0 +1,168 @@ +import SwiftUI +import UIKit + +/// Mirrors `frontend/src/components/agents/AgentIcon.tsx`: built-in brand +/// artwork lives in `AgentIcons.xcassets` (light/dark variants), unknown +/// agents fall back to a generic glyph. +enum AgentBrand { + static func normalizedKey(_ agent: String?) -> String? { + guard let raw = agent?.trimmingCharacters(in: .whitespacesAndNewlines), + !raw.isEmpty else { return nil } + let key = raw.lowercased().replacingOccurrences(of: "-", with: "_") + switch key { + case "gemini": return "antigravity" + case "claude": return "claude_code" + case "kimi": return "kimi_code" + case "deepseek", "dsh": return "deepseek_harness" + case "qodercli": return "qoder" + case "kirocli", "kiro_cli": return "kiro" + case "traex", "traecli", "trae_cli": return "trae" + case "commandcode", "cmdc": return "command_code" + case "oh_my_pi", "ohmypi": return "omp" + case "mimo", "mimocode": return "mimo_code" + default: return key + } + } + + private static let displayNames: [String: String] = [ + "claude_code": "Claude Code", + "codex": "Codex", + "antigravity": "Google Antigravity", + "openclaw": "OpenClaw", + "opencode": "OpenCode", + "cline": "Cline", + "hermes": "Hermes Agent", + "codebuddy": "CodeBuddy", + "kimi_code": "Kimi Code", + "pi": "Pi", + "grok": "Grok", + "cursor": "Cursor", + "deepseek_harness": "DeepSeek Harness", + "qoder": "Qoder", + "kiro": "Kiro CLI", + "auggie": "Auggie", + "trae": "TRAE CLI", + "command_code": "Command Code", + "zcode": "ZCode", + "omp": "OMP", + "mimo_code": "MiMo Code", + ] + + /// Human name for an agent id; prefers the host-provided name when it is + /// more than the raw id. + static func displayName(_ agent: String?, hostName: String? = nil) -> String { + if let hostName, !hostName.isEmpty, hostName != agent { return hostName } + guard let key = normalizedKey(agent) else { return agent ?? "Agent" } + return displayNames[key] ?? agent ?? "Agent" + } + + static func image(_ agent: String?) -> UIImage? { + guard let key = normalizedKey(agent) else { return nil } + return UIImage(named: "agent_\(key)") + } + + /// Best-effort agent for aggregate rows that only carry a model id + /// (usage by model). Returns nil when the vendor is ambiguous. + static func inferAgent(fromModel model: String?) -> String? { + guard let m = model?.lowercased(), !m.isEmpty else { return nil } + if m.contains("claude") || m.contains("opus") || m.contains("sonnet") || m.contains("haiku") { + return "claude_code" + } + if m.hasPrefix("gpt") || m.contains("codex") || m.hasPrefix("o3") || m.hasPrefix("o4") { + return "codex" + } + if m.contains("gemini") { return "antigravity" } + if m.contains("grok") { return "grok" } + if m.contains("deepseek") { return "deepseek_harness" } + if m.contains("kimi") { return "kimi_code" } + if m.contains("mimo") { return "mimo_code" } + return nil + } +} + +extension UIImage { + /// System menus draw `UIImage`s at their intrinsic size, so brand marks are + /// redrawn at menu-icon size with their original colors preserved. + func resizedForMenu(_ side: CGFloat = 20) -> UIImage { + let scale = min(side / max(size.width, 1), side / max(size.height, 1)) + let target = CGSize(width: size.width * scale, height: size.height * scale) + let renderer = UIGraphicsImageRenderer(size: CGSize(width: side, height: side)) + let light = imageAsset?.image(with: UITraitCollection(userInterfaceStyle: .light)) ?? self + let dark = imageAsset?.image(with: UITraitCollection(userInterfaceStyle: .dark)) ?? self + func draw(_ img: UIImage) -> UIImage { + renderer.image { _ in + img.draw(in: CGRect( + x: (side - target.width) / 2, y: (side - target.height) / 2, + width: target.width, height: target.height + )) + }.withRenderingMode(.alwaysOriginal) + } + let asset = UIImageAsset() + asset.register(draw(light), with: UITraitCollection(userInterfaceStyle: .light)) + asset.register(draw(dark), with: UITraitCollection(userInterfaceStyle: .dark)) + return asset.image(with: UITraitCollection.current) + } +} + +/// Label for agent rows inside `Menu` / `Picker`, where only `UIImage`-backed +/// icons render reliably. +struct AgentMenuLabel: View { + let agentID: String? + var hostName: String? + + var body: some View { + Label { + Text(AgentBrand.displayName(agentID, hostName: hostName)) + } icon: { + if let image = AgentBrand.image(agentID) { + Image(uiImage: image.resizedForMenu()) + } else { + Image(systemName: "cpu") + } + } + } +} + +struct AgentIconView: View { + let agent: String? + var size: CGFloat = 16 + + var body: some View { + Group { + if let image = AgentBrand.image(agent) { + Image(uiImage: image) + .resizable() + .interpolation(.high) + .scaledToFit() + } else { + Image(systemName: "cpu") + .resizable() + .scaledToFit() + .foregroundStyle(.secondary) + .padding(size * 0.08) + } + } + .frame(width: size, height: size) + .accessibilityLabel(AgentBrand.displayName(agent)) + } +} + +/// Model label prefixed with the agent that runs it. Use wherever a model +/// name is shown so the agent is always visible alongside it. +struct AgentModelLabel: View { + let agent: String? + let model: String? + var iconSize: CGFloat = 14 + var spacing: CGFloat = 4 + + var body: some View { + HStack(spacing: spacing) { + if agent != nil { AgentIconView(agent: agent, size: iconSize) } + if let model, !model.isEmpty { + Text(model).lineLimit(1) + } else if agent != nil { + Text(AgentBrand.displayName(agent)).lineLimit(1) + } + } + } +} diff --git a/mobile/ios/App/AgentIcons.xcassets/AppIcon.appiconset/AppIcon-1024.png b/mobile/ios/App/AgentIcons.xcassets/AppIcon.appiconset/AppIcon-1024.png new file mode 100644 index 000000000..12e2cbe78 Binary files /dev/null and b/mobile/ios/App/AgentIcons.xcassets/AppIcon.appiconset/AppIcon-1024.png differ diff --git a/mobile/ios/App/AgentIcons.xcassets/AppIcon.appiconset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..f22e10cde --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images" : [ + { + "filename" : "AppIcon-1024.png", + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/mobile/ios/App/AgentIcons.xcassets/Contents.json b/mobile/ios/App/AgentIcons.xcassets/Contents.json new file mode 100644 index 000000000..c47b5f2f1 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_antigravity.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_antigravity.imageset/Contents.json new file mode 100644 index 000000000..81ec6a54b --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_antigravity.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "antigravity-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_antigravity.imageset/antigravity-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_antigravity.imageset/antigravity-light.svg new file mode 100644 index 000000000..5a575991f --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_antigravity.imageset/antigravity-light.svg @@ -0,0 +1,7 @@ + + Google Antigravity + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_auggie.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_auggie.imageset/Contents.json new file mode 100644 index 000000000..5b5024992 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_auggie.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "auggie-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_auggie.imageset/auggie-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_auggie.imageset/auggie-light.svg new file mode 100644 index 000000000..2e74a9a89 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_auggie.imageset/auggie-light.svg @@ -0,0 +1,5 @@ + + Auggie + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_claude_code.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_claude_code.imageset/Contents.json new file mode 100644 index 000000000..a7fc24891 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_claude_code.imageset/Contents.json @@ -0,0 +1,25 @@ +{ + "images": [ + { + "filename": "claude_code-light.svg", + "idiom": "universal" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "filename": "claude_code-dark.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_claude_code.imageset/claude_code-dark.svg b/mobile/ios/App/AgentIcons.xcassets/agent_claude_code.imageset/claude_code-dark.svg new file mode 100644 index 000000000..dc7cc8233 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_claude_code.imageset/claude_code-dark.svg @@ -0,0 +1,3 @@ + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_claude_code.imageset/claude_code-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_claude_code.imageset/claude_code-light.svg new file mode 100644 index 000000000..93157d6ad --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_claude_code.imageset/claude_code-light.svg @@ -0,0 +1,3 @@ + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_cline.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_cline.imageset/Contents.json new file mode 100644 index 000000000..f9b40eaab --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_cline.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "cline-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_cline.imageset/cline-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_cline.imageset/cline-light.svg new file mode 100644 index 000000000..871ee372e --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_cline.imageset/cline-light.svg @@ -0,0 +1,4 @@ + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_codebuddy.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_codebuddy.imageset/Contents.json new file mode 100644 index 000000000..5c41a14f9 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_codebuddy.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "codebuddy-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_codebuddy.imageset/codebuddy-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_codebuddy.imageset/codebuddy-light.svg new file mode 100644 index 000000000..54491fc36 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_codebuddy.imageset/codebuddy-light.svg @@ -0,0 +1,3 @@ + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_codex.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_codex.imageset/Contents.json new file mode 100644 index 000000000..bdcee3c74 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_codex.imageset/Contents.json @@ -0,0 +1,25 @@ +{ + "images": [ + { + "filename": "codex-light.svg", + "idiom": "universal" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "filename": "codex-dark.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_codex.imageset/codex-dark.svg b/mobile/ios/App/AgentIcons.xcassets/agent_codex.imageset/codex-dark.svg new file mode 100644 index 000000000..c2c476fce --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_codex.imageset/codex-dark.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_codex.imageset/codex-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_codex.imageset/codex-light.svg new file mode 100644 index 000000000..10036a75d --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_codex.imageset/codex-light.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_command_code.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_command_code.imageset/Contents.json new file mode 100644 index 000000000..6c43dc048 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_command_code.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "command_code-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_command_code.imageset/command_code-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_command_code.imageset/command_code-light.svg new file mode 100644 index 000000000..e5d2c85d8 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_command_code.imageset/command_code-light.svg @@ -0,0 +1,11 @@ + + Command Code + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_cursor.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_cursor.imageset/Contents.json new file mode 100644 index 000000000..5f2982ce7 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_cursor.imageset/Contents.json @@ -0,0 +1,25 @@ +{ + "images": [ + { + "filename": "cursor-light.svg", + "idiom": "universal" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "filename": "cursor-dark.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_cursor.imageset/cursor-dark.svg b/mobile/ios/App/AgentIcons.xcassets/agent_cursor.imageset/cursor-dark.svg new file mode 100644 index 000000000..0f6b1e70f --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_cursor.imageset/cursor-dark.svg @@ -0,0 +1,3 @@ + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_cursor.imageset/cursor-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_cursor.imageset/cursor-light.svg new file mode 100644 index 000000000..89d3c5834 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_cursor.imageset/cursor-light.svg @@ -0,0 +1,3 @@ + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_deepseek_harness.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_deepseek_harness.imageset/Contents.json new file mode 100644 index 000000000..4f53add59 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_deepseek_harness.imageset/Contents.json @@ -0,0 +1,25 @@ +{ + "images": [ + { + "filename": "deepseek_harness-light.svg", + "idiom": "universal" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "filename": "deepseek_harness-dark.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_deepseek_harness.imageset/deepseek_harness-dark.svg b/mobile/ios/App/AgentIcons.xcassets/agent_deepseek_harness.imageset/deepseek_harness-dark.svg new file mode 100644 index 000000000..b97da3714 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_deepseek_harness.imageset/deepseek_harness-dark.svg @@ -0,0 +1,3 @@ + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_deepseek_harness.imageset/deepseek_harness-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_deepseek_harness.imageset/deepseek_harness-light.svg new file mode 100644 index 000000000..a4bf263af --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_deepseek_harness.imageset/deepseek_harness-light.svg @@ -0,0 +1,3 @@ + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_grok.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_grok.imageset/Contents.json new file mode 100644 index 000000000..a7108d038 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_grok.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "grok-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_grok.imageset/grok-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_grok.imageset/grok-light.svg new file mode 100644 index 000000000..fd48dde76 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_grok.imageset/grok-light.svg @@ -0,0 +1,3 @@ + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_hermes.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_hermes.imageset/Contents.json new file mode 100644 index 000000000..e89592aaa --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_hermes.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images": [ + { + "filename": "hermes-light.png", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_hermes.imageset/hermes-light.png b/mobile/ios/App/AgentIcons.xcassets/agent_hermes.imageset/hermes-light.png new file mode 100644 index 000000000..977a7ba41 Binary files /dev/null and b/mobile/ios/App/AgentIcons.xcassets/agent_hermes.imageset/hermes-light.png differ diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_kimi_code.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_kimi_code.imageset/Contents.json new file mode 100644 index 000000000..84fbf3608 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_kimi_code.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "kimi_code-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_kimi_code.imageset/kimi_code-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_kimi_code.imageset/kimi_code-light.svg new file mode 100644 index 000000000..4ba6e25c4 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_kimi_code.imageset/kimi_code-light.svg @@ -0,0 +1,3 @@ + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_kiro.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_kiro.imageset/Contents.json new file mode 100644 index 000000000..d6dc581ae --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_kiro.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "kiro-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_kiro.imageset/kiro-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_kiro.imageset/kiro-light.svg new file mode 100644 index 000000000..15b74b05c --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_kiro.imageset/kiro-light.svg @@ -0,0 +1,10 @@ + + Kiro CLI + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_mimo_code.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_mimo_code.imageset/Contents.json new file mode 100644 index 000000000..27300acec --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_mimo_code.imageset/Contents.json @@ -0,0 +1,25 @@ +{ + "images": [ + { + "filename": "mimo_code-light.svg", + "idiom": "universal" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "filename": "mimo_code-dark.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_mimo_code.imageset/mimo_code-dark.svg b/mobile/ios/App/AgentIcons.xcassets/agent_mimo_code.imageset/mimo_code-dark.svg new file mode 100644 index 000000000..73a121255 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_mimo_code.imageset/mimo_code-dark.svg @@ -0,0 +1,4 @@ + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_mimo_code.imageset/mimo_code-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_mimo_code.imageset/mimo_code-light.svg new file mode 100644 index 000000000..f4f40fcfa --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_mimo_code.imageset/mimo_code-light.svg @@ -0,0 +1,4 @@ + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_omp.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_omp.imageset/Contents.json new file mode 100644 index 000000000..bd0b6e87a --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_omp.imageset/Contents.json @@ -0,0 +1,25 @@ +{ + "images": [ + { + "filename": "omp-light.svg", + "idiom": "universal" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "filename": "omp-dark.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_omp.imageset/omp-dark.svg b/mobile/ios/App/AgentIcons.xcassets/agent_omp.imageset/omp-dark.svg new file mode 100644 index 000000000..e8e5a6517 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_omp.imageset/omp-dark.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_omp.imageset/omp-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_omp.imageset/omp-light.svg new file mode 100644 index 000000000..a3f625327 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_omp.imageset/omp-light.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_openclaw.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_openclaw.imageset/Contents.json new file mode 100644 index 000000000..fc8c87cf3 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_openclaw.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "openclaw-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_openclaw.imageset/openclaw-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_openclaw.imageset/openclaw-light.svg new file mode 100644 index 000000000..425fa0440 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_openclaw.imageset/openclaw-light.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_opencode.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_opencode.imageset/Contents.json new file mode 100644 index 000000000..4965c75a1 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_opencode.imageset/Contents.json @@ -0,0 +1,25 @@ +{ + "images": [ + { + "filename": "opencode-light.svg", + "idiom": "universal" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "filename": "opencode-dark.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_opencode.imageset/opencode-dark.svg b/mobile/ios/App/AgentIcons.xcassets/agent_opencode.imageset/opencode-dark.svg new file mode 100644 index 000000000..c48bacf16 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_opencode.imageset/opencode-dark.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_opencode.imageset/opencode-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_opencode.imageset/opencode-light.svg new file mode 100644 index 000000000..968c3461a --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_opencode.imageset/opencode-light.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_pi.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_pi.imageset/Contents.json new file mode 100644 index 000000000..1637839f7 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_pi.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "pi-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_pi.imageset/pi-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_pi.imageset/pi-light.svg new file mode 100644 index 000000000..11fa7c3f7 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_pi.imageset/pi-light.svg @@ -0,0 +1,4 @@ + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_qoder.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_qoder.imageset/Contents.json new file mode 100644 index 000000000..f9009808c --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_qoder.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "qoder-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_qoder.imageset/qoder-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_qoder.imageset/qoder-light.svg new file mode 100644 index 000000000..417d83693 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_qoder.imageset/qoder-light.svg @@ -0,0 +1,3 @@ + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_trae.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_trae.imageset/Contents.json new file mode 100644 index 000000000..37ae73dfc --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_trae.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "trae-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_trae.imageset/trae-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_trae.imageset/trae-light.svg new file mode 100644 index 000000000..e4322b12d --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_trae.imageset/trae-light.svg @@ -0,0 +1,10 @@ + + TRAE CLI + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_zcode.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/agent_zcode.imageset/Contents.json new file mode 100644 index 000000000..bdf998459 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_zcode.imageset/Contents.json @@ -0,0 +1,15 @@ +{ + "images": [ + { + "filename": "zcode-light.svg", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + }, + "properties": { + "preserves-vector-representation": true + } +} \ No newline at end of file diff --git a/mobile/ios/App/AgentIcons.xcassets/agent_zcode.imageset/zcode-light.svg b/mobile/ios/App/AgentIcons.xcassets/agent_zcode.imageset/zcode-light.svg new file mode 100644 index 000000000..315f69c38 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/agent_zcode.imageset/zcode-light.svg @@ -0,0 +1,15 @@ + + ZCode + + + + + + + + + + + + + diff --git a/mobile/ios/App/AgentIcons.xcassets/vibex_logo.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/vibex_logo.imageset/Contents.json new file mode 100644 index 000000000..dd2654164 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/vibex_logo.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images": [ + { + "filename": "app-logo-light-default.png", + "idiom": "universal" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "filename": "app-logo-dark.png", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/mobile/ios/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-dark.png b/mobile/ios/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-dark.png new file mode 100644 index 000000000..79a395e7f Binary files /dev/null and b/mobile/ios/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-dark.png differ diff --git a/mobile/ios/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-light-default.png b/mobile/ios/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-light-default.png new file mode 100644 index 000000000..265680116 Binary files /dev/null and b/mobile/ios/App/AgentIcons.xcassets/vibex_logo.imageset/app-logo-light-default.png differ diff --git a/mobile/ios/App/AgentIcons.xcassets/vibex_logo_lite.imageset/Contents.json b/mobile/ios/App/AgentIcons.xcassets/vibex_logo_lite.imageset/Contents.json new file mode 100644 index 000000000..bfc9ba615 --- /dev/null +++ b/mobile/ios/App/AgentIcons.xcassets/vibex_logo_lite.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images": [ + { + "filename": "app-logo-light-lite.png", + "idiom": "universal" + }, + { + "appearances": [ + { + "appearance": "luminosity", + "value": "dark" + } + ], + "filename": "app-logo-dark-lite.png", + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/mobile/ios/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-dark-lite.png b/mobile/ios/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-dark-lite.png new file mode 100644 index 000000000..84380595b Binary files /dev/null and b/mobile/ios/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-dark-lite.png differ diff --git a/mobile/ios/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-light-lite.png b/mobile/ios/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-light-lite.png new file mode 100644 index 000000000..deeb244a4 Binary files /dev/null and b/mobile/ios/App/AgentIcons.xcassets/vibex_logo_lite.imageset/app-logo-light-lite.png differ diff --git a/mobile/ios/App/AppAppearanceStore.swift b/mobile/ios/App/AppAppearanceStore.swift new file mode 100644 index 000000000..0c762f208 --- /dev/null +++ b/mobile/ios/App/AppAppearanceStore.swift @@ -0,0 +1,395 @@ +import CompanionCore +import Observation +import QuartzCore +import SwiftUI +import UIKit +import UserNotifications + +enum AppThemeMode: String, CaseIterable, Identifiable { + case system + case light + case dark + + var id: String { rawValue } + + var title: String { + switch self { + case .system: return "跟随系统" + case .light: return "浅色" + case .dark: return "深色" + } + } + + var subtitle: String { + switch self { + case .system: return "自动跟随系统外观" + case .light: return "明亮清爽浅色外观" + case .dark: return "专注护眼深色外观" + } + } + + var icon: String { + switch self { + case .system: return "circle.lefthalf.filled" + case .light: return "sun.max.fill" + case .dark: return "moon.stars.fill" + } + } + + var colorScheme: ColorScheme? { + switch self { + case .system: return nil + case .light: return .light + case .dark: return .dark + } + } + + var uiInterfaceStyle: UIUserInterfaceStyle { + switch self { + case .system: return .unspecified + case .light: return .light + case .dark: return .dark + } + } +} + +enum AppFontSizePreset: String, CaseIterable, Identifiable { + case small + case standard + case mediumLarge + case large + case extraLarge + + var id: String { rawValue } + + var title: String { + switch self { + case .small: return "小" + case .standard: return "标准" + case .mediumLarge: return "中大" + case .large: return "大" + case .extraLarge: return "特大" + } + } + + var scaleLabel: String { + switch self { + case .small: return "90%" + case .standard: return "100%" + case .mediumLarge: return "110%" + case .large: return "120%" + case .extraLarge: return "135%" + } + } + + var pointPreviewSize: CGFloat { + switch self { + case .small: return 13.5 + case .standard: return 15.0 + case .mediumLarge: return 16.5 + case .large: return 18.0 + case .extraLarge: return 20.0 + } + } + + var dynamicTypeSize: DynamicTypeSize { + switch self { + case .small: return .small + case .standard: return .large + case .mediumLarge: return .xLarge + case .large: return .xxLarge + case .extraLarge: return .xxxLarge + } + } +} + +enum AppFontStylePreset: String, CaseIterable, Identifiable { + case system + case rounded + case serif + case monospaced + + var id: String { rawValue } + + var title: String { + switch self { + case .system: return "系统默认 (SF Pro / 苹方)" + case .rounded: return "圆体 (SF Rounded)" + case .serif: return "衬线 (New York / 宋体)" + case .monospaced: return "等宽代码 (SF Mono)" + } + } + + var shortTitle: String { + switch self { + case .system: return "系统默认" + case .rounded: return "圆体" + case .serif: return "衬线" + case .monospaced: return "等宽" + } + } + + var subtitle: String { + switch self { + case .system: return "清晰均衡的 Apple 原生无衬线字体" + case .rounded: return "柔和现代的几何圆角字体" + case .serif: return "适合长文阅读的经典衬线字体" + case .monospaced: return "字符等宽对齐,适合代码与终端重度用户" + } + } + + var fontDesign: Font.Design { + switch self { + case .system: return .default + case .rounded: return .rounded + case .serif: return .serif + case .monospaced: return .monospaced + } + } +} + +@MainActor +@Observable +final class AppAppearanceStore { + private let defaults: UserDefaults + + // 1. Profile + var userName: String { + didSet { defaults.set(userName, forKey: "vibex.profile.userName") } + } + var userHandle: String { + didSet { defaults.set(userHandle, forKey: "vibex.profile.userHandle") } + } + var userRoleTitle: String { + didSet { defaults.set(userRoleTitle, forKey: "vibex.profile.userRoleTitle") } + } + var userBio: String { + didSet { defaults.set(userBio, forKey: "vibex.profile.userBio") } + } + var userAvatarJSON: String { + didSet { defaults.set(userAvatarJSON, forKey: "vibex.profile.userAvatarJSON") } + } + + // 2. Theme + var themeMode: AppThemeMode { + didSet { defaults.set(themeMode.rawValue, forKey: "vibex.appearance.themeMode") } + } + + // 3. Font + var fontSizePreset: AppFontSizePreset { + didSet { defaults.set(fontSizePreset.rawValue, forKey: "vibex.appearance.fontSize") } + } + var fontStylePreset: AppFontStylePreset { + didSet { defaults.set(fontStylePreset.rawValue, forKey: "vibex.appearance.fontStyle") } + } + + // 4. Notifications + var notifyTurnCompleted: Bool { + didSet { defaults.set(notifyTurnCompleted, forKey: "vibex.notify.turnCompleted") } + } + var notifyApprovalRequired: Bool { + didSet { defaults.set(notifyApprovalRequired, forKey: "vibex.notify.approvalRequired") } + } + var notifyCollabMessages: Bool { + didSet { defaults.set(notifyCollabMessages, forKey: "vibex.notify.collabMessages") } + } + var notificationSound: Bool { + didSet { defaults.set(notificationSound, forKey: "vibex.notify.sound") } + } + var hapticFeedback: Bool { + didSet { defaults.set(hapticFeedback, forKey: "vibex.notify.haptic") } + } + var systemNotificationStatusText: String = "已启用" + + private weak var activeOverlayView: UIView? + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + self.userName = defaults.string(forKey: "vibex.profile.userName") ?? "LTF" + self.userHandle = defaults.string(forKey: "vibex.profile.userHandle") ?? "@ltf" + self.userRoleTitle = defaults.string(forKey: "vibex.profile.userRoleTitle") ?? "VibeX Creator" + self.userBio = defaults.string(forKey: "vibex.profile.userBio") ?? "本地优先 AI 协同工作流与多智能体架构" + self.userAvatarJSON = + defaults.string(forKey: "vibex.profile.userAvatarJSON") + ?? CollabBotAvatarConfig(color: "#1584ff", shape: .cloud).jsonString + + let rawTheme = defaults.string(forKey: "vibex.appearance.themeMode") ?? AppThemeMode.system.rawValue + self.themeMode = AppThemeMode(rawValue: rawTheme) ?? .system + + let rawSize = defaults.string(forKey: "vibex.appearance.fontSize") ?? AppFontSizePreset.standard.rawValue + self.fontSizePreset = AppFontSizePreset(rawValue: rawSize) ?? .standard + + let rawStyle = defaults.string(forKey: "vibex.appearance.fontStyle") ?? AppFontStylePreset.system.rawValue + self.fontStylePreset = AppFontStylePreset(rawValue: rawStyle) ?? .system + + 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 + self.notificationSound = defaults.object(forKey: "vibex.notify.sound") as? Bool ?? true + self.hapticFeedback = defaults.object(forKey: "vibex.notify.haptic") as? Bool ?? true + + Task { + applyInterfaceStyleToAllWindows(themeMode.uiInterfaceStyle) + await refreshNotificationAuthorizationStatus() + } + } + + var avatarConfig: CollabBotAvatarConfig { + get { + CollabBotAvatarConfig.resolve( + rawAvatar: userAvatarJSON, + rawColor: nil, + fallbackSeed: userName + ) + } + set { userAvatarJSON = newValue.jsonString } + } + + /// Switches the theme and animates a CoreAnimation circular reveal expanding from the top-right corner (`右上角展开`). + func setThemeModeWithTopRightReveal(_ newMode: AppThemeMode) { + guard newMode != themeMode else { return } + + if hapticFeedback { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + } + + guard let window = Self.keyWindow() else { + themeMode = newMode + return + } + + // Remove any previous in-flight overlay + activeOverlayView?.removeFromSuperview() + + // 1. Snapshot the OLD appearance before switching + let renderer = UIGraphicsImageRenderer(bounds: window.bounds) + let oldSnapshot = renderer.image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: false) + } + + // 2. Place the OLD snapshot on top of the window so the screen stays visually stable + let overlay = UIImageView(image: oldSnapshot) + overlay.frame = window.bounds + overlay.contentMode = .scaleToFill + overlay.isUserInteractionEnabled = false + window.addSubview(overlay) + activeOverlayView = overlay + + // 3. Switch the underlying live window & SwiftUI hierarchy to the NEW theme immediately + themeMode = newMode + applyInterfaceStyleToAllWindows(newMode.uiInterfaceStyle) + + // 4. Cut out an expanding circle starting from the TOP-RIGHT corner (`CGPoint(x: width - 34, y: 68)`) + // on the old snapshot using an Even-Odd CAShapeLayer mask + CABasicAnimation on the GPU render server! + let bounds = window.bounds + let topRightOrigin = CGPoint( + x: bounds.maxX - 34, + y: max(window.safeAreaInsets.top + 20, 64) + ) + let startRadius: CGFloat = 1.0 + let maxRadius: CGFloat = hypot(bounds.width, bounds.height) * 1.08 + + let startCircleRect = CGRect( + x: topRightOrigin.x - startRadius, + y: topRightOrigin.y - startRadius, + width: startRadius * 2, + height: startRadius * 2 + ) + let endCircleRect = CGRect( + x: topRightOrigin.x - maxRadius, + y: topRightOrigin.y - maxRadius, + width: maxRadius * 2, + height: maxRadius * 2 + ) + + let startMaskPath = UIBezierPath(rect: bounds) + startMaskPath.append(UIBezierPath(ovalIn: startCircleRect)) + + let endMaskPath = UIBezierPath(rect: bounds) + endMaskPath.append(UIBezierPath(ovalIn: endCircleRect)) + + let maskLayer = CAShapeLayer() + maskLayer.fillRule = .evenOdd + maskLayer.path = endMaskPath.cgPath + overlay.layer.mask = maskLayer + + // Subtle expanding wave ring from the top-right corner + let ringLayer = CAShapeLayer() + ringLayer.fillColor = UIColor.clear.cgColor + ringLayer.strokeColor = UIColor.systemBlue.withAlphaComponent(0.45).cgColor + ringLayer.lineWidth = 2.0 + ringLayer.path = UIBezierPath(ovalIn: endCircleRect).cgPath + window.layer.addSublayer(ringLayer) + + let duration: CFTimeInterval = 0.56 + let timing = CAMediaTimingFunction(controlPoints: 0.22, 1.0, 0.36, 1.0) + + let maskAnim = CABasicAnimation(keyPath: "path") + maskAnim.fromValue = startMaskPath.cgPath + maskAnim.toValue = endMaskPath.cgPath + maskAnim.duration = duration + maskAnim.timingFunction = timing + maskAnim.fillMode = .forwards + maskLayer.add(maskAnim, forKey: "topRightCircularReveal") + + let ringAnim = CABasicAnimation(keyPath: "path") + ringAnim.fromValue = UIBezierPath(ovalIn: startCircleRect).cgPath + ringAnim.toValue = UIBezierPath(ovalIn: endCircleRect).cgPath + ringAnim.duration = duration + ringAnim.timingFunction = timing + ringLayer.add(ringAnim, forKey: "topRightRingExpand") + + let ringFade = CABasicAnimation(keyPath: "opacity") + ringFade.fromValue = 1.0 + ringFade.toValue = 0.0 + ringFade.duration = duration + ringFade.timingFunction = CAMediaTimingFunction(name: .easeIn) + ringLayer.opacity = 0.0 + ringLayer.add(ringFade, forKey: "topRightRingFade") + + Task { @MainActor in + try? await Task.sleep(for: .milliseconds(580)) + if self.activeOverlayView === overlay { + overlay.removeFromSuperview() + self.activeOverlayView = nil + } + ringLayer.removeFromSuperlayer() + } + } + + func applyInterfaceStyleToAllWindows(_ style: UIUserInterfaceStyle) { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + for scene in scenes { + for window in scene.windows { + window.overrideUserInterfaceStyle = style + } + } + } + + func refreshNotificationAuthorizationStatus() async { + let settings = await UNUserNotificationCenter.current().notificationSettings() + switch settings.authorizationStatus { + case .authorized, .provisional, .ephemeral: + systemNotificationStatusText = "系统通知已开启" + case .denied: + systemNotificationStatusText = "系统通知已关闭" + case .notDetermined: + systemNotificationStatusText = "待授权" + @unknown default: + systemNotificationStatusText = "未知" + } + } + + func requestSystemNotificationPermission() async { + _ = try? await UNUserNotificationCenter.current().requestAuthorization( + options: [.alert, .badge, .sound] + ) + await refreshNotificationAuthorizationStatus() + } + + private static func keyWindow() -> UIWindow? { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + return scenes.flatMap(\.windows).first(where: \.isKeyWindow) + ?? scenes.flatMap(\.windows).first + } +} diff --git a/mobile/ios/App/ApprovalCard.swift b/mobile/ios/App/ApprovalCard.swift index a84841d67..326c97e26 100644 --- a/mobile/ios/App/ApprovalCard.swift +++ b/mobile/ios/App/ApprovalCard.swift @@ -1,216 +1,567 @@ import CompanionCore import SwiftUI -/// Human-in-the-loop question card: one question at a time, the stack slides between them, single-choice -/// answers advance on their own and multi-select waits for Continue. +/// SwiftUI port of VibeX desktop's `AgentQuestionCard`: collapsible header with position badge (`1 / N`), +/// single/multi-select option rows with `(Recommended)` badge, toggleable custom answer option row, +/// and pagination/submit footer (`上一题`, `跳过`, `下一题` / `提交`). struct ApprovalCard: View { let request: PendingQuestion - let submit: (JSONValue?) async -> Void + let busy: Bool + let respond: (JSONValue?) -> Void - private let questions: [FormQuestion] @State private var index = 0 @State private var answers: [String: QuestionAnswer] = [:] - @State private var sent = false - @State private var pendingAdvance: Task? + @State private var collapsed = false + @FocusState private var customInputFocused: Bool - init(request: PendingQuestion, submit: @escaping (JSONValue?) async -> Void) { - self.request = request - self.submit = submit - self.questions = QuestionForm.questions(for: request) - } - - private var question: FormQuestion { questions[index] } - private var isLast: Bool { index == questions.count - 1 } - private var answer: QuestionAnswer { answers[question.id] ?? QuestionAnswer() } + private var questions: [FormQuestion] { QuestionForm.questions(for: request) } var body: some View { - if sent { - Label("答案已发送", systemImage: "checkmark.circle.fill") - .font(.system(size: 12.5, weight: .medium)) - .foregroundStyle(.green) - .padding(.vertical, 6) - .padding(.horizontal, 10) - .background(Color.green.opacity(0.12), in: Capsule()) - .transition(.scale(scale: 0.95).combined(with: .opacity)) - } else { - card - .transition(.move(edge: .bottom).combined(with: .opacity)) + let items = questions + let safeIndex = min(max(0, index), max(0, items.count - 1)) + if items.indices.contains(safeIndex) { + card(items: items, activeIndex: safeIndex, current: items[safeIndex]) } } - private var card: some View { - VStack(spacing: 0) { - ZStack(alignment: .topLeading) { - questionView - .id(index) - .transition(.asymmetric( - insertion: .move(edge: .bottom).combined(with: .opacity), - removal: .move(edge: .top).combined(with: .opacity) - )) + private func card(items: [FormQuestion], activeIndex: Int, current: FormQuestion) -> some View { + let headerTitle = current.header.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ? "问题确认" + : current.header + return VStack(alignment: .leading, spacing: 0) { + // MARK: Header (`agent-question-header`) + Button { + withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { + collapsed.toggle() + } + } label: { + HStack(spacing: 8) { + Text("\(activeIndex + 1) / \(items.count)") + .font(.system(size: 11.5, weight: .semibold, design: .monospaced)) + .foregroundStyle(.secondary) + .padding(.horizontal, 7) + .padding(.vertical, 2.5) + .background( + Color.primary.opacity(0.06), + in: Capsule() + ) + + Text(headerTitle) + .font(.system(size: 13.5, weight: .semibold)) + .foregroundStyle(.primary) + .lineLimit(1) + + Text("刚刚") + .font(.system(size: 11.5)) + .foregroundStyle(.tertiary) + + Spacer(minLength: 4) + + Image(systemName: collapsed ? "chevron.down" : "chevron.up") + .font(.system(size: 11.5, weight: .semibold)) + .foregroundStyle(.secondary) + .frame(width: 24, height: 24) + .background(Color.primary.opacity(0.04), in: Circle()) + } + .padding(.horizontal, 14) + .padding(.vertical, 11) + .contentShape(Rectangle()) } - .padding(16) - .frame(maxWidth: .infinity, alignment: .leading) - .clipped() - footer - .padding(.horizontal, 12) - .padding(.vertical, 10) - } - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 16)) - .overlay(RoundedRectangle(cornerRadius: 16).stroke(Color.primary.opacity(0.06))) - .shadow(color: .black.opacity(0.06), radius: 8, y: 2) - .animation(.timingCurve(0.22, 1, 0.36, 1, duration: 0.36), value: index) - .onDisappear { pendingAdvance?.cancel() } - } + .buttonStyle(.plain) - private var questionView: some View { - VStack(alignment: .leading, spacing: 10) { - Text(question.text).font(.system(size: 14, weight: .medium)) - VStack(alignment: .leading, spacing: 2) { - ForEach(question.choices) { choice in optionRow(choice) } - TextField("其他…", text: customText) - .font(.system(size: 13)) - .padding(.vertical, 6) - .padding(.leading, 22) - .submitLabel(.send) - .onSubmit { if !answer.isEmpty { advance() } } + if !collapsed { + Divider().opacity(0.45) + + VStack(alignment: .leading, spacing: 12) { + // Prompt text (`agent-question-card-prompt`) + if !current.text.isEmpty { + Text(current.text) + .font(.system(size: 14, weight: .medium)) + .foregroundStyle(.primary) + .fixedSize(horizontal: false, vertical: true) + } + + // Options (`agent-question-options`) + VStack(spacing: 7) { + ForEach(current.choices) { choice in + choiceRow(choice, in: current) + } + + customToggleRow(for: current) + + if isCustomActive(in: current) { + customTextField(for: current) + .transition(.opacity.combined(with: .move(edge: .top))) + } + } + + // Footer (`agent-question-footer`) + footer(items: items, activeIndex: activeIndex) + } + .padding(.horizontal, 14) + .padding(.top, 12) + .padding(.bottom, 13) } } + .background( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .strokeBorder(Color.primary.opacity(0.10), lineWidth: 0.75) + ) + .shadow(color: .black.opacity(0.05), radius: 8, y: 2) } - private func optionRow(_ choice: QuestionChoice) -> some View { - let on = answer.selected.contains(choice.value) + private func choiceRow(_ choice: QuestionChoice, in question: FormQuestion) -> some View { + let selected = (answers[question.id]?.selected ?? []).contains(choice.value) return Button { - toggle(choice) + UIImpactFeedbackGenerator(style: .light).impactOccurred() + toggle(choice.value, in: question) } label: { - HStack(alignment: .top, spacing: 8) { - indicator(on: on) - VStack(alignment: .leading, spacing: 1) { - Text(choice.label) - .font(.system(size: 13)) - .foregroundStyle(on ? Color.primary : Color.primary.opacity(0.7)) + HStack(alignment: .top, spacing: 10) { + optionIndicator(selected: selected, multiSelect: question.multiSelect) + .padding(.top, 2) + + VStack(alignment: .leading, spacing: 3) { + HStack(spacing: 6) { + Text(choice.label) + .font(.system(size: 13.5, weight: selected ? .semibold : .regular)) + .foregroundStyle(.primary) + .multilineTextAlignment(.leading) + + if choice.recommended { + Text("推荐") + .font(.system(size: 10.5, weight: .semibold)) + .foregroundStyle(Color.accentColor) + .padding(.horizontal, 6) + .padding(.vertical, 1.5) + .background( + Color.accentColor.opacity(0.12), + in: Capsule() + ) + } + } + if let description = choice.description, !description.isEmpty { - Text(description).font(.system(size: 11)).foregroundStyle(.secondary) + Text(description) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) } } + Spacer(minLength: 0) } - .padding(.vertical, 6) + .padding(.horizontal, 11) + .padding(.vertical, 9) + .background( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(selected ? Color.accentColor.opacity(0.10) : Color(.tertiarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .strokeBorder( + selected ? Color.accentColor.opacity(0.55) : Color.primary.opacity(0.07), + lineWidth: selected ? 1.1 : 0.6 + ) + ) .contentShape(Rectangle()) } .buttonStyle(.plain) - .accessibilityAddTraits(on ? .isSelected : []) + .disabled(busy) } - private func indicator(on: Bool) -> some View { - ZStack { - if question.multiSelect { - RoundedRectangle(cornerRadius: 5) - .fill(on ? Color.primary : .clear) - .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color.primary.opacity(on ? 0 : 0.3), lineWidth: 1.5)) - if on { Image(systemName: "checkmark").font(.system(size: 9, weight: .heavy)).foregroundStyle(Color(.systemBackground)) } - } else { - Circle() - .fill(on ? Color.primary : .clear) - .overlay(Circle().stroke(Color.primary.opacity(on ? 0 : 0.3), lineWidth: 1.5)) - Circle().fill(Color(.systemBackground)).frame(width: 6, height: 6).scaleEffect(on ? 1 : 0) + private func customToggleRow(for question: FormQuestion) -> some View { + let active = isCustomActive(in: question) + return Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + withAnimation(.spring(response: 0.25, dampingFraction: 0.86)) { + toggleCustom(in: question) } + } label: { + HStack(spacing: 10) { + optionIndicator(selected: active, multiSelect: question.multiSelect) + + HStack(spacing: 5) { + Image(systemName: "square.and.pencil") + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(active ? Color.accentColor : .secondary) + Text("自定义回答") + .font(.system(size: 13.5, weight: active ? .semibold : .regular)) + .foregroundStyle(.primary) + } + + Spacer(minLength: 0) + } + .padding(.horizontal, 11) + .padding(.vertical, 9) + .background( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(active ? Color.accentColor.opacity(0.10) : Color(.tertiarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .strokeBorder( + active ? Color.accentColor.opacity(0.55) : Color.primary.opacity(0.07), + lineWidth: active ? 1.1 : 0.6 + ) + ) + .contentShape(Rectangle()) } - .frame(width: 16, height: 16) - .animation(.easeOut(duration: 0.2), value: on) + .buttonStyle(.plain) + .disabled(busy) } - private var footer: some View { - HStack(spacing: 10) { - HStack(spacing: 4) { - navButton("chevron.up", enabled: index > 0) { go(index - 1) } - Text("\(index + 1) / \(questions.count)") - .font(.system(size: 12, weight: .medium)) - .monospacedDigit() - .foregroundStyle(.tertiary) - .contentTransition(.numericText()) - navButton("chevron.down", enabled: !isLast) { go(index + 1) } + private func customTextField(for question: FormQuestion) -> some View { + let binding = Binding( + get: { answers[question.id]?.customText ?? "" }, + set: { text in + var entry = answers[question.id] ?? QuestionAnswer(customActive: true) + entry.customActive = true + entry.customText = text + if !question.multiSelect, question.customFieldName == nil { + entry.selected = [] + } + answers[question.id] = entry } - Spacer() - Button("跳过") { advance() } - .font(.system(size: 13, weight: .medium)) - .foregroundStyle(.secondary) - .buttonStyle(.plain) - .padding(.horizontal, 8) - Button(action: advance) { - HStack(spacing: 6) { - Text(isLast ? "发送" : "继续") - Image(systemName: "return").font(.system(size: 10, weight: .semibold)) + ) + return TextField("请直接输入你的回答…", text: binding, axis: .vertical) + .font(.system(size: 13.5)) + .lineLimit(1...4) + .focused($customInputFocused) + .keyboardType(question.valueType == .number || question.valueType == .integer ? .decimalPad : .default) + .padding(.horizontal, 11) + .padding(.vertical, 9) + .background( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(Color(.systemBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .strokeBorder(Color.accentColor.opacity(0.45), lineWidth: 1) + ) + .disabled(busy) + } + + @ViewBuilder + private func optionIndicator(selected: Bool, multiSelect: Bool) -> some View { + if multiSelect { + RoundedRectangle(cornerRadius: 4.5, style: .continuous) + .strokeBorder(selected ? Color.accentColor : Color.secondary.opacity(0.45), lineWidth: 1.4) + .background( + RoundedRectangle(cornerRadius: 4.5, style: .continuous) + .fill(selected ? Color.accentColor : .clear) + ) + .overlay { + if selected { + Image(systemName: "checkmark") + .font(.system(size: 9.5, weight: .bold)) + .foregroundStyle(.white) + } } - .font(.system(size: 13, weight: .medium)) - .foregroundStyle(Color(.systemBackground)) - .padding(.horizontal, 14) - .padding(.vertical, 6) - .background(Color.primary.opacity(answer.isEmpty ? 0.25 : 1), in: Capsule()) + .frame(width: 16, height: 16) + } else { + Circle() + .strokeBorder(selected ? Color.accentColor : Color.secondary.opacity(0.45), lineWidth: 1.4) + .overlay { + if selected { + Circle() + .fill(Color.accentColor) + .frame(width: 8, height: 8) + } + } + .frame(width: 16, height: 16) + } + } + + private func footer(items: [FormQuestion], activeIndex: Int) -> some View { + let isLast = activeIndex >= items.count - 1 + let complete = items.allSatisfy { !(answers[$0.id]?.isEmpty ?? true) } + return HStack(spacing: 8) { + if items.count > 1 { + Button { + withAnimation(.easeInOut(duration: 0.18)) { + index = max(0, activeIndex - 1) + } + } label: { + Text("上一题") + .font(.system(size: 12.5, weight: .medium)) + .foregroundStyle(activeIndex == 0 ? .tertiary : .primary) + .padding(.horizontal, 11) + .frame(height: 30) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color(.tertiarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.6) + ) + } + .buttonStyle(.plain) + .disabled(busy || activeIndex == 0) + } + + Spacer(minLength: 4) + + Button { + respond(nil) + } label: { + Text("拒绝") + .font(.system(size: 12.5, weight: .medium)) + .foregroundStyle(.secondary) + .padding(.horizontal, 12) + .frame(height: 30) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color(.tertiarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.6) + ) } .buttonStyle(.plain) - .disabled(answer.isEmpty) + .disabled(busy) + + if isLast { + Button { + let payload = QuestionForm.content(for: request, questions: items, answers: answers) + respond(payload) + } label: { + HStack(spacing: 5) { + if busy { + ProgressView().controlSize(.mini).tint(.white) + } + Text("提交") + .font(.system(size: 12.5, weight: .semibold)) + } + .foregroundStyle(complete && !busy ? Color(.systemBackground) : .secondary) + .padding(.horizontal, 14) + .frame(height: 30) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(complete && !busy ? Color.primary : Color.primary.opacity(0.10)) + ) + } + .buttonStyle(.plain) + .disabled(busy || !complete) + } else { + Button { + withAnimation(.easeInOut(duration: 0.18)) { + index = min(items.count - 1, activeIndex + 1) + } + } label: { + Text("下一题") + .font(.system(size: 12.5, weight: .semibold)) + .foregroundStyle(Color(.systemBackground)) + .padding(.horizontal, 14) + .frame(height: 30) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color.primary) + ) + } + .buttonStyle(.plain) + .disabled(busy) + } } + .padding(.top, 2) } - private func navButton(_ symbol: String, enabled: Bool, action: @escaping () -> Void) -> some View { - Button(action: action) { - Image(systemName: symbol) - .font(.system(size: 11, weight: .semibold)) - .foregroundStyle(.secondary) - .frame(width: 22, height: 22) - } - .buttonStyle(.plain) - .disabled(!enabled) - .opacity(enabled ? 1 : 0.3) + private func isCustomActive(in question: FormQuestion) -> Bool { + if question.choices.isEmpty { return true } + return answers[question.id]?.customActive == true } - private var customText: Binding { - Binding( - get: { answer.customText }, - set: { text in - var next = answer - next.customText = text - if !question.multiSelect, !text.isEmpty { next.selected = [] } - answers[question.id] = next + private func toggle(_ value: JSONValue, in question: FormQuestion) { + var entry = answers[question.id] ?? QuestionAnswer() + if question.multiSelect { + if let existing = entry.selected.firstIndex(of: value) { + entry.selected.remove(at: existing) + } else { + entry.selected.append(value) } - ) + } else { + entry.selected = [value] + if question.customFieldName == nil { + entry.customActive = false + entry.customText = "" + } + } + answers[question.id] = entry } - private func toggle(_ choice: QuestionChoice) { - var next = answer + private func toggleCustom(in question: FormQuestion) { + var entry = answers[question.id] ?? QuestionAnswer() if question.multiSelect { - if let at = next.selected.firstIndex(of: choice.value) { - next.selected.remove(at: at) + entry.customActive.toggle() + if !entry.customActive { + entry.customText = "" } else { - next.selected.append(choice.value) + customInputFocused = true } } else { - next.selected = [choice.value] - next.customText = "" - } - answers[question.id] = next - pendingAdvance?.cancel() - guard !question.multiSelect else { return } - pendingAdvance = Task { - try? await Task.sleep(for: .milliseconds(480)) - guard !Task.isCancelled else { return } - await MainActor.run { advance() } + entry.customActive.toggle() + if entry.customActive { + if question.customFieldName == nil { + entry.selected = [] + } + customInputFocused = true + } else { + entry.customText = "" + } } + answers[question.id] = entry } +} - private func go(_ target: Int) { - pendingAdvance?.cancel() - index = min(max(target, 0), questions.count - 1) +/// Inline timeline card matching VibeX desktop's `AskQuestionToolCard.tsx`: +/// displays the question title, `查看详情` toggle, `问答确认` tag, and read-only question options. +struct AskQuestionToolCardView: View { + let tool: ToolStep + @State private var isExpanded = false + @State private var activeIndex = 0 + + private var questions: [FormQuestion] { tool.questions } + private var activeQuestion: FormQuestion? { + guard !questions.isEmpty else { return nil } + let idx = min(max(0, activeIndex), questions.count - 1) + return questions[idx] } - private func advance() { - pendingAdvance?.cancel() - if isLast { - withAnimation { sent = true } - let content = QuestionForm.content(for: request, questions: questions, answers: answers) - Task { await submit(content) } - } else { - index += 1 + private var cardTitle: String { + if let q = activeQuestion { + return q.text.isEmpty ? q.header : q.text } + return tool.preview ?? "需要确认的问题" + } + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Text(cardTitle) + .font(.system(size: 13.5, weight: .medium)) + .foregroundStyle(.primary) + .lineLimit(isExpanded ? 3 : 1) + + HStack(spacing: 8) { + if !questions.isEmpty { + Button { + withAnimation(.spring(response: 0.26, dampingFraction: 0.86)) { + isExpanded.toggle() + } + } label: { + HStack(spacing: 4) { + Image(systemName: "chevron.right") + .font(.system(size: 10, weight: .bold)) + .rotationEffect(.degrees(isExpanded ? 90 : 0)) + Text("查看详情") + .font(.system(size: 12, weight: .medium)) + } + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + } + + Spacer(minLength: 4) + + Text("问答确认") + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.secondary) + .padding(.horizontal, 7) + .padding(.vertical, 2) + .background(Color.primary.opacity(0.06), in: Capsule()) + } + + if isExpanded, let current = activeQuestion { + Divider().opacity(0.45) + + VStack(alignment: .leading, spacing: 8) { + if questions.count > 1 { + HStack(spacing: 6) { + Text("\(activeIndex + 1) / \(questions.count)") + .font(.system(size: 11, weight: .semibold, design: .monospaced)) + .foregroundStyle(.secondary) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Color.primary.opacity(0.06), in: Capsule()) + Text(current.header) + .font(.system(size: 12.5, weight: .semibold)) + .foregroundStyle(.primary) + Spacer() + HStack(spacing: 4) { + Button { + activeIndex = max(0, activeIndex - 1) + } label: { + Image(systemName: "chevron.left") + .font(.system(size: 11, weight: .semibold)) + .frame(width: 24, height: 24) + } + .disabled(activeIndex == 0) + Button { + activeIndex = min(questions.count - 1, activeIndex + 1) + } label: { + Image(systemName: "chevron.right") + .font(.system(size: 11, weight: .semibold)) + .frame(width: 24, height: 24) + } + .disabled(activeIndex >= questions.count - 1) + } + .buttonStyle(.plain) + } + } + + ForEach(current.choices) { choice in + HStack(alignment: .top, spacing: 8) { + Circle() + .strokeBorder(Color.secondary.opacity(0.4), lineWidth: 1.2) + .frame(width: 14, height: 14) + .padding(.top, 2) + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 5) { + Text(choice.label) + .font(.system(size: 13)) + .foregroundStyle(.primary) + if choice.recommended { + Text("推荐") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(Color.accentColor) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background(Color.accentColor.opacity(0.12), in: Capsule()) + } + } + if let desc = choice.description, !desc.isEmpty { + Text(desc) + .font(.system(size: 11.5)) + .foregroundStyle(.secondary) + } + } + Spacer(minLength: 0) + } + .padding(.horizontal, 10) + .padding(.vertical, 7) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color(.tertiarySystemGroupedBackground)) + ) + } + } + .padding(.top, 4) + } + } + .padding(.horizontal, 14) + .padding(.vertical, 11) + .background( + RoundedRectangle(cornerRadius: 11, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 11, style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.6) + ) } } diff --git a/mobile/ios/App/BoardView.swift b/mobile/ios/App/BoardView.swift new file mode 100644 index 000000000..9bb7714b1 --- /dev/null +++ b/mobile/ios/App/BoardView.swift @@ -0,0 +1,2080 @@ +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) + } +} + +struct BoardView: View { + let client: HostClient + + @State private var viewMode: KanbanViewMode = .columns + @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? + + // Columns board presentation + @State private var columnsLayout: ColumnsLayoutStyle = .horizontalBoard + @State private var focusedColumn: KanbanSessionStatus = .todo + + // Session Hub state + @State private var hubSubMode: SessionHubSubMode = .list + @State private var searchQuery = "" + @State private var sortField: KanbanSortField = .defaultOrder + @State private var selectedWorkspaceFilterIDs: Set = [] + @State private var selectedAgentFilters: Set = [] + @State private var isArchiveView = false + @State private var isBulkDeleteMode = false + @State private var selectedDeleteIDs: Set = [] + @State private var collapsedStatuses: Set = [] + + // Monitor & Canvas state + @State private var monitoredSessionIDs: Set = [] + @State private var monitorPreviews: [String: String] = [:] + @State private var showAddMonitorPicker = false + @State private var canvasGrouping: CanvasGroupingMode = .byProject + @State private var collapsedCanvasGroups: Set = [] + + // 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? + @State private var showBulkDeleteConfirm = false + + enum ColumnsLayoutStyle: String, CaseIterable, Identifiable { + case horizontalBoard = "四栏画板" + case statusTabs = "分栏列表" + var id: String { rawValue } + } + + enum SessionHubSubMode: String, CaseIterable, Identifiable { + case list = "会话列表" + case monitor = "会话监控区" + case canvas = "画布分组" + var id: String { rawValue } + + var icon: String { + switch self { + case .list: return "list.bullet" + case .monitor: return "rectangle.grid.2x2" + case .canvas: return "square.on.square.dashed" + } + } + } + + enum CanvasGroupingMode: String, CaseIterable, Identifiable { + case byProject = "按项目" + case byAgent = "按 Agent" + case byRecent = "最近时间" + var id: String { rawValue } + } + + var body: some View { + NavigationStack(path: $path) { + VStack(spacing: 0) { + topModeBar + Divider() + + if let noticeMessage { + noticeBanner(noticeMessage) + } + + switch viewMode { + case .columns: + columnsBoardContent + case .sessionHub: + sessionHubContent + case .usage: + KanbanUsageDashboardView( + client: client, + projects: projects, + initialProjectID: selectedProjectID + ) + } + } + .background(Color(.systemGroupedBackground)) + .navigationTitle("看板") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarLeading) { + projectSelectorMenu + } + ToolbarItem(placement: .topBarTrailing) { + Button { + createSheetInitialStatus = .todo + showCreateSheet = true + } label: { + Image(systemName: "plus.circle.fill") + .font(.title3) + } + .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) + } + } + } + .sheet(isPresented: $showAddMonitorPicker) { + addMonitorSessionSheet + } + .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 + } + } + .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)”吗?正在执行中的会话不会被删除。") + } + .alert( + "批量删除会话", + isPresented: $showBulkDeleteConfirm + ) { + Button("取消", role: .cancel) {} + Button("删除 (\(selectedDeleteIDs.count))", role: .destructive) { + performBulkDelete() + } + } message: { + Text("确定删除已选中的 \(selectedDeleteIDs.count) 个会话吗?正在执行中的会话不会被删除。") + } + } + .task { + while !Task.isCancelled { + await reload() + try? await Task.sleep(for: .seconds(errorMessage == nil ? 15 : 4)) + } + } + } + + // MARK: - Top Bars + + private var projectSelectorMenu: some View { + Menu { + Button { + selectedProjectID = nil + selectedWorkspaceFilterIDs.removeAll() + Task { await reload() } + } label: { + HStack { + Label("全部项目", systemImage: "square.stack.3d.up") + if selectedProjectID == nil { + Image(systemName: "checkmark") + } + } + } + + Divider() + + ForEach(projects) { project in + Button { + selectedProjectID = project.id + selectedWorkspaceFilterIDs.removeAll() + Task { await reload() } + } label: { + HStack { + Label( + project.displayName, + systemImage: project.isGit ? "arrow.triangle.branch" : "folder" + ) + if selectedProjectID?.lowercased() == project.id.lowercased() { + Image(systemName: "checkmark") + } + } + } + } + } label: { + HStack(spacing: 4) { + Image(systemName: selectedProject?.isGit == true ? "arrow.triangle.branch" : "folder.fill") + .font(.caption) + Text(selectedProject?.displayName ?? "全部项目") + .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 var topModeBar: some View { + HStack(spacing: 8) { + ForEach(KanbanViewMode.allCases) { mode in + let isSelected = viewMode == mode + Button { + withAnimation(.spring(response: 0.26, dampingFraction: 0.85)) { + viewMode = mode + } + } label: { + HStack(spacing: 5) { + Image(systemName: mode.icon) + .font(.caption) + Text(mode.title) + .font(.footnote.weight(isSelected ? .semibold : .medium)) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 8) + .foregroundStyle(isSelected ? Color.white : Color.primary) + .background( + isSelected ? Color.accentColor : Color(.secondarySystemGroupedBackground), + in: RoundedRectangle(cornerRadius: 10) + ) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + .background(Color(.systemGroupedBackground)) + } + + 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) + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + } + .padding(.horizontal, 14) + .padding(.vertical, 8) + .background(Color(.secondarySystemGroupedBackground)) + } + + // MARK: - 1. Four-Column Kanban Board (`builtin:columns`) + + @ViewBuilder + private var columnsBoardContent: some View { + if isLoading && sessions.isEmpty { + Spacer() + ProgressView("正在加载会话看板...") + Spacer() + } else if let errorMessage, sessions.isEmpty { + Spacer() + LoadFailureView(message: errorMessage) { + Task { await reload() } + } + Spacer() + } else { + VStack(spacing: 0) { + HStack(spacing: 10) { + Picker("看板布局", selection: $columnsLayout) { + ForEach(ColumnsLayoutStyle.allCases) { style in + Text(style.rawValue).tag(style) + } + } + .pickerStyle(.segmented) + .frame(width: 170) + + Spacer() + + Text("共 \(activeSessions.count) 个活跃会话") + .font(.caption) + .foregroundStyle(.secondary) + + Button { + Task { await reload() } + } label: { + Image(systemName: "arrow.clockwise") + .font(.footnote.weight(.medium)) + .frame(width: 28, height: 28) + .background(Color(.secondarySystemGroupedBackground), in: Circle()) + } + .buttonStyle(.plain) + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + + if columnsLayout == .horizontalBoard { + 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 - 58, 340) + ) + } + } + .scrollTargetLayout() + .padding(.bottom, 12) + } + .contentMargins(.horizontal, 16, for: .scrollContent) + .scrollTargetBehavior(.viewAligned) + } + } else { + VStack(spacing: 0) { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + ForEach(KanbanSessionStatus.activeColumns) { status in + let count = sessionsForStatus(status).count + let selected = focusedColumn == status + Button { + withAnimation(.easeInOut(duration: 0.18)) { + focusedColumn = status + } + } label: { + HStack(spacing: 6) { + Circle() + .fill(statusColor(status)) + .frame(width: 8, height: 8) + Text(status.title) + .font(.footnote.weight(selected ? .semibold : .medium)) + Text("\(count)") + .font(.caption2.monospacedDigit().weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + selected + ? Color.white.opacity(0.22) + : Color(.tertiarySystemFill), + in: Capsule() + ) + } + .padding(.horizontal, 12) + .padding(.vertical, 7) + .foregroundStyle(selected ? Color.white : Color.primary) + .background( + selected + ? statusColor(status) + : Color(.secondarySystemGroupedBackground), + in: Capsule() + ) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, 16) + .padding(.bottom, 8) + } + + let columnItems = sessionsForStatus(focusedColumn) + if columnItems.isEmpty { + Spacer() + VStack(spacing: 12) { + Image(systemName: "rectangle.stack.badge.plus") + .font(.system(size: 36)) + .foregroundStyle(.secondary) + Text("“\(focusedColumn.title)”暂无会话") + .font(.subheadline.weight(.medium)) + .foregroundStyle(.secondary) + Button { + createSheetInitialStatus = focusedColumn + showCreateSheet = true + } label: { + Label("新建\(focusedColumn.title)会话", systemImage: "plus") + .font(.footnote.weight(.semibold)) + .padding(.horizontal, 14) + .padding(.vertical, 8) + .background(Color.accentColor, in: Capsule()) + .foregroundStyle(.white) + } + .buttonStyle(.plain) + } + Spacer() + } else { + ScrollView { + LazyVStack(spacing: 10) { + ForEach(columnItems) { session in + sessionCard(session, showStatusPill: false) + } + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + } + .refreshable { + await reload() + } + } + } + } + } + } + } + + 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: - 2. Session Hub (`builtin:sessions`: List + Monitor + Canvas + Archive) + + @ViewBuilder + private var sessionHubContent: some View { + VStack(spacing: 0) { + // Sub-mode switcher: 会话列表 / 会话监控区 / 画布分组 + HStack(spacing: 8) { + ForEach(SessionHubSubMode.allCases) { mode in + let selected = hubSubMode == mode + Button { + withAnimation(.easeInOut(duration: 0.18)) { + hubSubMode = mode + } + } label: { + HStack(spacing: 5) { + Image(systemName: mode.icon) + .font(.caption2) + Text(mode.rawValue) + .font(.caption.weight(selected ? .semibold : .medium)) + if mode == .monitor && !effectiveMonitoredSessions.isEmpty { + Text("\(effectiveMonitoredSessions.count)") + .font(.caption2.monospacedDigit().weight(.bold)) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background( + selected ? Color.white.opacity(0.24) : Color.accentColor.opacity(0.15), + in: Capsule() + ) + } + } + .padding(.horizontal, 12) + .padding(.vertical, 6) + .foregroundStyle(selected ? Color.white : Color.primary) + .background( + selected ? Color.accentColor : Color(.secondarySystemGroupedBackground), + in: Capsule() + ) + } + .buttonStyle(.plain) + } + Spacer() + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + + switch hubSubMode { + case .list: + sessionHubListContent + case .monitor: + sessionHubMonitorContent + case .canvas: + sessionHubCanvasContent + } + } + } + + private var sessionHubListContent: some View { + VStack(spacing: 0) { + // Controls row: Sort, Filter, Archive Toggle, Bulk Delete + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + // Sort Menu + Menu { + ForEach(KanbanSortField.allCases) { field in + Button { + sortField = field + } label: { + HStack { + Text(field.label) + if sortField == field { Image(systemName: "checkmark") } + } + } + } + } label: { + HStack(spacing: 4) { + Image(systemName: "arrow.up.arrow.down") + .font(.caption2) + Text(sortField == .defaultOrder ? "排序" : "排序:\(sortField.label)") + .font(.caption.weight(.medium)) + } + .padding(.horizontal, 10) + .padding(.vertical, 6) + .background( + sortField == .defaultOrder + ? Color(.secondarySystemGroupedBackground) + : Color.accentColor.opacity(0.15), + in: Capsule() + ) + } + + // Agent Filter Menu + if !availableAgentKeys.isEmpty { + Menu { + Button("全部代理") { + selectedAgentFilters.removeAll() + } + Divider() + ForEach(availableAgentKeys, id: \.self) { agentKey in + Button { + if selectedAgentFilters.contains(agentKey) { + selectedAgentFilters.remove(agentKey) + } else { + selectedAgentFilters.insert(agentKey) + } + } label: { + if selectedAgentFilters.contains(agentKey) { + Label(KanbanSessionSummary.formatAgentDisplayName(agentKey), systemImage: "checkmark") + } else { + AgentMenuLabel( + agentID: agentKey, + hostName: KanbanSessionSummary.formatAgentDisplayName(agentKey) + ) + } + } + } + } label: { + HStack(spacing: 4) { + Image(systemName: "line.3.horizontal.decrease.circle") + .font(.caption2) + Text( + selectedAgentFilters.isEmpty + ? "代理筛选" + : "代理:\(selectedAgentFilters.count)" + ) + .font(.caption.weight(.medium)) + } + .padding(.horizontal, 10) + .padding(.vertical, 6) + .background( + selectedAgentFilters.isEmpty + ? Color(.secondarySystemGroupedBackground) + : Color.accentColor.opacity(0.15), + in: Capsule() + ) + } + } + + // Workspace Filter Menu + if availableWorkspaceLabels.count > 1 { + Menu { + Button("全部工作区") { + selectedWorkspaceFilterIDs.removeAll() + } + Divider() + ForEach(availableWorkspaceLabels, id: \.id) { ws in + Button { + if selectedWorkspaceFilterIDs.contains(ws.id) { + selectedWorkspaceFilterIDs.remove(ws.id) + } else { + selectedWorkspaceFilterIDs.insert(ws.id) + } + } label: { + HStack { + Text(ws.label) + if selectedWorkspaceFilterIDs.contains(ws.id) { + Image(systemName: "checkmark") + } + } + } + } + } label: { + HStack(spacing: 4) { + Image(systemName: "arrow.triangle.branch") + .font(.caption2) + Text( + selectedWorkspaceFilterIDs.isEmpty + ? "工作区" + : "工作区:\(selectedWorkspaceFilterIDs.count)" + ) + .font(.caption.weight(.medium)) + } + .padding(.horizontal, 10) + .padding(.vertical, 6) + .background( + selectedWorkspaceFilterIDs.isEmpty + ? Color(.secondarySystemGroupedBackground) + : Color.accentColor.opacity(0.15), + in: Capsule() + ) + } + } + + // Archive view toggle + Button { + withAnimation(.easeInOut(duration: 0.18)) { + isArchiveView.toggle() + isBulkDeleteMode = false + selectedDeleteIDs.removeAll() + } + } label: { + HStack(spacing: 4) { + Image(systemName: isArchiveView ? "tray.full.fill" : "archivebox") + .font(.caption2) + Text( + isArchiveView + ? "返回会话列表" + : "归档区 (\(archivedSessions.count))" + ) + .font(.caption.weight(.medium)) + } + .padding(.horizontal, 10) + .padding(.vertical, 6) + .foregroundStyle(isArchiveView ? Color.white : Color.primary) + .background( + isArchiveView ? Color.indigo : Color(.secondarySystemGroupedBackground), + in: Capsule() + ) + } + .buttonStyle(.plain) + + // Bulk delete toggle + Button { + withAnimation(.easeInOut(duration: 0.18)) { + isBulkDeleteMode.toggle() + selectedDeleteIDs.removeAll() + } + } label: { + HStack(spacing: 4) { + Image(systemName: isBulkDeleteMode ? "xmark.circle.fill" : "trash") + .font(.caption2) + Text(isBulkDeleteMode ? "退出删除模式" : "批量删除") + .font(.caption.weight(.medium)) + } + .padding(.horizontal, 10) + .padding(.vertical, 6) + .foregroundStyle(isBulkDeleteMode ? Color.white : Color.red) + .background( + isBulkDeleteMode ? Color.red : Color(.secondarySystemGroupedBackground), + in: Capsule() + ) + } + .buttonStyle(.plain) + + if hasActiveFilters { + Button { + sortField = .defaultOrder + selectedAgentFilters.removeAll() + selectedWorkspaceFilterIDs.removeAll() + searchQuery = "" + } label: { + Text("恢复默认") + .font(.caption) + .foregroundStyle(Color.accentColor) + .padding(.horizontal, 8) + .padding(.vertical, 6) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, 16) + .padding(.bottom, 6) + } + + if isBulkDeleteMode { + HStack(spacing: 12) { + let currentPool = isArchiveView ? filteredArchivedSessions : filteredActiveSessions + Button { + if selectedDeleteIDs.count == currentPool.count { + selectedDeleteIDs.removeAll() + } else { + selectedDeleteIDs = Set(currentPool.map(\.id)) + } + } label: { + Text(selectedDeleteIDs.count == currentPool.count && !currentPool.isEmpty ? "取消全选" : "全选") + .font(.caption.weight(.medium)) + } + + Text("已选择 \(selectedDeleteIDs.count) 项") + .font(.caption) + .foregroundStyle(.secondary) + + Spacer() + + Button(role: .destructive) { + showBulkDeleteConfirm = true + } label: { + Text("删除选中") + .font(.caption.weight(.semibold)) + .padding(.horizontal, 12) + .padding(.vertical, 5) + .background( + selectedDeleteIDs.isEmpty ? Color.gray.opacity(0.3) : Color.red, + in: Capsule() + ) + .foregroundStyle(.white) + } + .disabled(selectedDeleteIDs.isEmpty) + .buttonStyle(.plain) + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + .background(Color(.secondarySystemGroupedBackground)) + } + + List { + Section { + SearchListCard( + query: $searchQuery, + placeholder: "搜索名称或用户消息…", + results: hubSearchResults + ) + } + .listRowInsets(EdgeInsets(top: 4, leading: 0, bottom: 8, trailing: 0)) + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + + if isArchiveView { + if filteredArchivedSessions.isEmpty { + Section { + ContentUnavailableView("归档区暂无会话", systemImage: "archivebox") + .frame(maxWidth: .infinity) + .padding(.vertical, 24) + } + .listRowBackground(Color.clear) + } else { + Section("归档区 (\(filteredArchivedSessions.count))") { + ForEach(filteredArchivedSessions) { session in + hubListRow(session) + } + } + } + } else { + if filteredActiveSessions.isEmpty { + Section { + ContentUnavailableView( + hasActiveFilters ? "没有符合当前筛选或排序条件的会话" : "暂无会话,点击右上角“+”即可创建", + systemImage: "bubble.left.and.bubble.right" + ) + .frame(maxWidth: .infinity) + .padding(.vertical, 24) + } + .listRowBackground(Color.clear) + } else { + ForEach(KanbanSessionStatus.activeColumns) { status in + let groupItems = filteredActiveSessions.filter { $0.status == status } + if !groupItems.isEmpty { + Section { + if !collapsedStatuses.contains(status) { + ForEach(groupItems) { session in + hubListRow(session) + } + } + } header: { + Button { + withAnimation(.easeInOut(duration: 0.18)) { + if collapsedStatuses.contains(status) { + collapsedStatuses.remove(status) + } else { + collapsedStatuses.insert(status) + } + } + } label: { + HStack(spacing: 6) { + Image( + systemName: collapsedStatuses.contains(status) + ? "chevron.right" + : "chevron.down" + ) + .font(.caption2.weight(.bold)) + Circle() + .fill(statusColor(status)) + .frame(width: 8, height: 8) + Text(status.title) + .font(.footnote.weight(.semibold)) + .foregroundStyle(.primary) + Text("\(groupItems.count)") + .font(.caption2.monospacedDigit().weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 1) + .background(Color(.tertiarySystemFill), in: Capsule()) + Spacer() + } + } + .buttonStyle(.plain) + } + } + } + } + } + } + .listStyle(.insetGrouped) + .scrollDismissesKeyboard(.immediately) + .refreshable { + await reload() + } + } + } + + @ViewBuilder + private func hubListRow(_ session: KanbanSessionSummary) -> some View { + HStack(spacing: 10) { + if isBulkDeleteMode { + Button { + if selectedDeleteIDs.contains(session.id) { + selectedDeleteIDs.remove(session.id) + } else { + selectedDeleteIDs.insert(session.id) + } + } label: { + Image( + systemName: selectedDeleteIDs.contains(session.id) + ? "checkmark.circle.fill" + : "circle" + ) + .font(.title3) + .foregroundStyle( + selectedDeleteIDs.contains(session.id) ? Color.accentColor : Color.secondary + ) + } + .buttonStyle(.plain) + } + + Button { + if isBulkDeleteMode { + if selectedDeleteIDs.contains(session.id) { + selectedDeleteIDs.remove(session.id) + } else { + selectedDeleteIDs.insert(session.id) + } + } else { + openSession(session) + } + } label: { + VStack(alignment: .leading, spacing: 5) { + HStack(spacing: 6) { + if session.isPinned { + Image(systemName: "pin.fill") + .font(.caption2) + .foregroundStyle(.orange) + } + if session.isRunning { + ProgressView() + .controlSize(.mini) + Text("进行中") + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 1) + .background(Color.orange.opacity(0.16), in: Capsule()) + .foregroundStyle(.orange) + } else if session.status == .inreview { + Text("待检查") + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 1) + .background(Color.purple.opacity(0.16), in: Capsule()) + .foregroundStyle(.purple) + } + Text(session.resolvedTitle) + .font(.subheadline.weight(.medium)) + .foregroundStyle(.primary) + .lineLimit(1) + Spacer() + if let date = session.updatedDate { + Text(Self.shortRelative(date)) + .font(.caption2) + .foregroundStyle(.secondary) + } + } + + HStack(spacing: 8) { + if let collab = session.collaboration, let member = collab.memberName, !member.isEmpty { + Label(member, systemImage: "person.2.fill") + .font(.caption2) + .foregroundStyle(.indigo) + .lineLimit(1) + } + AgentModelLabel(agent: session.effectiveAgentKey, model: session.model ?? session.agentDisplayName, iconSize: 12) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + if !session.workspaceDisplayLabel.isEmpty { + Label(session.workspaceDisplayLabel, systemImage: "arrow.triangle.branch") + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Spacer() + if monitoredSessionIDs.contains(session.id) { + Image(systemName: "eye.fill") + .font(.caption2) + .foregroundStyle(Color.accentColor) + } + } + } + } + .buttonStyle(.plain) + } + .contextMenu { + sessionContextMenuItems(session) + } + .swipeActions(edge: .trailing, allowsFullSwipe: true) { + Button(role: .destructive) { + performDelete(session) + } label: { + Label("删除", systemImage: "trash") + } + if session.isArchived { + Button { + performStatusChange(session, to: .todo) + } label: { + Label("移至列表", systemImage: "tray.and.arrow.up") + } + .tint(.blue) + } else { + Button { + performStatusChange(session, to: .archived) + } label: { + Label("归档", systemImage: "archivebox") + } + .tint(.indigo) + } + } + .swipeActions(edge: .leading, allowsFullSwipe: false) { + Button { + performTogglePin(session) + } label: { + Label(session.isPinned ? "取消置顶" : "置顶", systemImage: session.isPinned ? "pin.slash" : "pin") + } + .tint(.orange) + + Button { + toggleMonitor(session) + } label: { + Label( + monitoredSessionIDs.contains(session.id) ? "取消监控" : "监控", + systemImage: monitoredSessionIDs.contains(session.id) ? "eye.slash" : "eye" + ) + } + .tint(.blue) + } + } + + // MARK: - Session Hub Monitor (`SessionHubMonitor`) + + private var sessionHubMonitorContent: some View { + let monitored = effectiveMonitoredSessions + return VStack(spacing: 0) { + HStack { + Text("会话监控区 (\(monitored.count))") + .font(.subheadline.weight(.semibold)) + Spacer() + Button { + showAddMonitorPicker = true + } label: { + Label("添加监控会话", systemImage: "plus.circle") + .font(.caption.weight(.semibold)) + } + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + + if monitored.isEmpty { + Spacer() + ContentUnavailableView { + Label("会话监控区为空", systemImage: "rectangle.grid.2x2") + } description: { + Text("在会话列表中右滑选择“监控”或点击上方“添加监控会话”,即可在此实时监控多个会话。") + } actions: { + Button("添加监控会话") { + showAddMonitorPicker = true + } + .buttonStyle(.borderedProminent) + } + Spacer() + } else { + ScrollView { + LazyVGrid(columns: [GridItem(.flexible())], spacing: 12) { + ForEach(Array(monitored.enumerated()), id: \.element.id) { index, session in + monitorCardView(session: session, slotIndex: index) + } + } + .padding(16) + } + .refreshable { + await reload() + await loadMonitorPreviews() + } + } + } + .task(id: monitored.map(\.id)) { + await loadMonitorPreviews() + } + } + + private func monitorCardView(session: KanbanSessionSummary, slotIndex: Int) -> some View { + let slotColors: [Color] = [.blue, .purple, .orange, .green, .pink, .teal] + let barColor = slotColors[slotIndex % slotColors.count] + let preview = monitorPreviews[session.id] ?? session.firstPrompt ?? "点击“在执行区打开”查看完整对话流" + + return VStack(alignment: .leading, spacing: 10) { + HStack(spacing: 8) { + RoundedRectangle(cornerRadius: 2) + .fill(barColor) + .frame(width: 4, height: 18) + + Text(session.resolvedTitle) + .font(.subheadline.weight(.semibold)) + .lineLimit(1) + + Spacer() + + if session.isRunning { + HStack(spacing: 4) { + ProgressView().controlSize(.mini) + Text("进行中") + .font(.caption2.weight(.semibold)) + } + .padding(.horizontal, 7) + .padding(.vertical, 3) + .background(Color.orange.opacity(0.16), in: Capsule()) + .foregroundStyle(.orange) + } else { + Text(session.status.title) + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 7) + .padding(.vertical, 3) + .background(statusColor(session.status).opacity(0.15), in: Capsule()) + .foregroundStyle(statusColor(session.status)) + } + } + + Text(preview) + .font(.footnote) + .foregroundStyle(.secondary) + .lineLimit(3) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(10) + .background(Color(.tertiarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 10)) + + HStack(spacing: 10) { + AgentModelLabel(agent: session.effectiveAgentKey, model: session.model ?? session.agentDisplayName, iconSize: 12) + .font(.caption2) + .foregroundStyle(.secondary) + if !session.workspaceDisplayLabel.isEmpty { + Label(session.workspaceDisplayLabel, systemImage: "arrow.triangle.branch") + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Spacer() + Button { + monitoredSessionIDs.remove(session.id) + } label: { + Text("取消监控") + .font(.caption.weight(.medium)) + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + + Button { + openSession(session) + } label: { + Label("在执行区打开", systemImage: "arrow.up.right.square") + .font(.caption.weight(.semibold)) + .padding(.horizontal, 10) + .padding(.vertical, 5) + .background(Color.accentColor, in: Capsule()) + .foregroundStyle(.white) + } + .buttonStyle(.plain) + } + } + .padding(14) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14)) + } + + // MARK: - Session Hub Canvas Grouping (`SessionCanvasView`) + + private var sessionHubCanvasContent: some View { + let groups = buildCanvasGroups() + return VStack(spacing: 0) { + HStack { + Picker("分组方式", selection: $canvasGrouping) { + ForEach(CanvasGroupingMode.allCases) { mode in + Text(mode.rawValue).tag(mode) + } + } + .pickerStyle(.segmented) + .frame(maxWidth: 260) + + Spacer() + + Button { + if collapsedCanvasGroups.count == groups.count { + collapsedCanvasGroups.removeAll() + } else { + collapsedCanvasGroups = Set(groups.map(\.id)) + } + } label: { + Text(collapsedCanvasGroups.count == groups.count ? "全部展开" : "全部收起") + .font(.caption.weight(.medium)) + } + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + + if groups.isEmpty { + Spacer() + ContentUnavailableView("画布是空的", systemImage: "square.on.square.dashed") + Spacer() + } else { + ScrollView { + LazyVStack(spacing: 14) { + ForEach(groups) { group in + let isCollapsed = collapsedCanvasGroups.contains(group.id) + VStack(alignment: .leading, spacing: 10) { + Button { + withAnimation(.easeInOut(duration: 0.18)) { + if isCollapsed { + collapsedCanvasGroups.remove(group.id) + } else { + collapsedCanvasGroups.insert(group.id) + } + } + } label: { + HStack(spacing: 8) { + Image(systemName: isCollapsed ? "chevron.right" : "chevron.down") + .font(.caption.weight(.bold)) + .foregroundStyle(.secondary) + Image(systemName: group.icon) + .font(.subheadline) + .foregroundStyle(Color.accentColor) + Text(group.title) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.primary) + Spacer() + Text("\(group.sessions.count) 个会话") + .font(.caption) + .foregroundStyle(.secondary) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background(Color(.tertiarySystemFill), in: Capsule()) + } + } + .buttonStyle(.plain) + + if !isCollapsed { + ForEach(group.sessions) { session in + sessionCard(session, showStatusPill: true) + } + } + } + .padding(14) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 16)) + } + } + .padding(16) + } + .refreshable { + await reload() + } + } + } + } + + // 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) + } + } + + private static let relativeFormatter: RelativeDateTimeFormatter = { + let f = RelativeDateTimeFormatter() + f.locale = Locale(identifier: "zh_Hans_CN") + f.unitsStyle = .short + f.dateTimeStyle = .named + return f + }() + + static func shortRelative(_ date: Date) -> String { + 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") + } + + Button { + toggleMonitor(session) + } label: { + Label( + monitoredSessionIDs.contains(session.id) ? "取消监控" : "加入监控区", + systemImage: monitoredSessionIDs.contains(session.id) ? "eye.slash" : "eye" + ) + } + + 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") + } + } + + private var addMonitorSessionSheet: some View { + NavigationStack { + List { + ForEach(activeSessions) { session in + let isMonitored = monitoredSessionIDs.contains(session.id) + Button { + toggleMonitor(session) + } label: { + HStack(spacing: 10) { + AgentIconView(agent: session.effectiveAgentKey, size: 20) + VStack(alignment: .leading, spacing: 3) { + Text(session.resolvedTitle) + .font(.subheadline.weight(.medium)) + .foregroundStyle(.primary) + .lineLimit(1) + Text("\(session.agentDisplayName) · \(session.status.title)") + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + Image(systemName: isMonitored ? "checkmark.circle.fill" : "plus.circle") + .foregroundStyle(isMonitored ? Color.accentColor : Color.secondary) + .font(.title3) + } + } + } + } + .navigationTitle("选择监控会话") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("完成") { + showAddMonitorPicker = false + } + } + } + } + .presentationDetents([.medium, .large]) + } + + // MARK: - Computed Properties & Filtering + + private var selectedProject: ProjectSummary? { + guard let selectedProjectID else { return nil } + return projects.first { $0.id.lowercased() == selectedProjectID.lowercased() } + } + + private var activeWorkspaceIDs: [String] { + if let selectedProject { + return selectedProject.workspaceIds + } + return projects.flatMap(\.workspaceIds) + } + + private var activeSessions: [KanbanSessionSummary] { + sessions.filter { !$0.isArchived } + } + + private var archivedSessions: [KanbanSessionSummary] { + sessions.filter(\.isArchived) + } + + private func sessionsForStatus(_ status: KanbanSessionStatus) -> [KanbanSessionSummary] { + sortSessionsList(activeSessions.filter { $0.status == status }, by: .defaultOrder) + } + + private var hasActiveFilters: Bool { + sortField != .defaultOrder + || !selectedAgentFilters.isEmpty + || !selectedWorkspaceFilterIDs.isEmpty + || !searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + private var availableAgentKeys: [String] { + let keys = Set(sessions.compactMap(\.effectiveAgentKey)) + return keys.sorted() + } + + private var availableWorkspaceLabels: [(id: String, label: String)] { + var map: [String: String] = [:] + for ws in workspaces { + map[ws.id] = ws.displayLabel + } + for s in sessions where map[s.workspaceId] == nil && !s.workspaceId.isEmpty { + map[s.workspaceId] = s.workspaceDisplayLabel.isEmpty ? "默认工作区" : s.workspaceDisplayLabel + } + return map.map { (id: $0.key, label: $0.value) }.sorted { $0.label < $1.label } + } + + private var filteredActiveSessions: [KanbanSessionSummary] { + applyHubFilters(to: activeSessions) + } + + private var filteredArchivedSessions: [KanbanSessionSummary] { + applyHubFilters(to: archivedSessions) + } + + private func applyHubFilters(to input: [KanbanSessionSummary]) -> [KanbanSessionSummary] { + let needle = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + let filtered = input.filter { session in + if !selectedWorkspaceFilterIDs.isEmpty && !selectedWorkspaceFilterIDs.contains(session.workspaceId) { + return false + } + if !selectedAgentFilters.isEmpty { + guard let key = session.effectiveAgentKey, selectedAgentFilters.contains(key) else { + return false + } + } + if !needle.isEmpty { + let matchTitle = session.resolvedTitle.lowercased().contains(needle) + let matchPrompt = session.firstPrompt?.lowercased().contains(needle) ?? false + let matchBranch = session.workspaceDisplayLabel.lowercased().contains(needle) + let matchAgent = session.agentDisplayName.lowercased().contains(needle) + if !(matchTitle || matchPrompt || matchBranch || matchAgent) { + return false + } + } + return true + } + return sortSessionsList(filtered, by: sortField) + } + + 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 var hubSearchResults: [SearchResultItem] { + let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !q.isEmpty else { return [] } + return sessions.filter { + $0.resolvedTitle.lowercased().contains(q) + || ($0.firstPrompt?.lowercased().contains(q) ?? false) + } + .prefix(6) + .map { session in + SearchResultItem( + id: session.id, + title: session.resolvedTitle, + subtitle: "\(session.status.title) · \(session.agentDisplayName)", + icon: "bubble.left.and.bubble.right", + action: { openSession(session) } + ) + } + } + + private var effectiveMonitoredSessions: [KanbanSessionSummary] { + let explicit = activeSessions.filter { monitoredSessionIDs.contains($0.id) } + if !explicit.isEmpty { return explicit } + let autoAttention = activeSessions.filter { $0.isRunning || $0.status == .inreview } + return Array(autoAttention.prefix(6)) + } + + private struct CanvasGroup: Identifiable { + let id: String + let title: String + let icon: String + let sessions: [KanbanSessionSummary] + } + + private func buildCanvasGroups() -> [CanvasGroup] { + switch canvasGrouping { + case .byProject: + var wsToProject: [String: ProjectSummary] = [:] + for proj in projects { + for ws in proj.workspaceIds { + wsToProject[ws.lowercased()] = proj + } + } + var buckets: [String: (title: String, icon: String, list: [KanbanSessionSummary])] = [:] + for s in activeSessions { + if let proj = wsToProject[s.workspaceId.lowercased()] { + var entry = buckets[proj.id] ?? (proj.displayName, proj.isGit ? "arrow.triangle.branch" : "folder.fill", []) + entry.list.append(s) + buckets[proj.id] = entry + } else { + var entry = buckets["other"] ?? ("其他工作区", "folder", []) + entry.list.append(s) + buckets["other"] = entry + } + } + return buckets.map { CanvasGroup(id: $0.key, title: $0.value.title, icon: $0.value.icon, sessions: $0.value.list) } + .sorted { $0.sessions.count > $1.sessions.count } + + case .byAgent: + var buckets: [String: [KanbanSessionSummary]] = [:] + for s in activeSessions { + let key = s.agentDisplayName + buckets[key, default: []].append(s) + } + return buckets.map { CanvasGroup(id: $0.key, title: $0.key, icon: "sparkles", sessions: $0.value) } + .sorted { $0.sessions.count > $1.sessions.count } + + case .byRecent: + let now = Date() + var today: [KanbanSessionSummary] = [] + var sevenDays: [KanbanSessionSummary] = [] + var older: [KanbanSessionSummary] = [] + for s in activeSessions { + let d = s.updatedDate ?? .distantPast + let hours = now.timeIntervalSince(d) / 3600.0 + if hours <= 24 { + today.append(s) + } else if hours <= 24 * 7 { + sevenDays.append(s) + } else { + older.append(s) + } + } + var groups: [CanvasGroup] = [] + if !today.isEmpty { groups.append(CanvasGroup(id: "1d", title: "最近 1 天", icon: "clock.fill", sessions: today)) } + if !sevenDays.isEmpty { groups.append(CanvasGroup(id: "7d", title: "最近 7 天", icon: "calendar", sessions: sevenDays)) } + if !older.isEmpty { groups.append(CanvasGroup(id: "older", title: "更早之前", icon: "archivebox", sessions: older)) } + return groups + } + } + + 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 loadMonitorPreviews() async { + for session in effectiveMonitoredSessions.prefix(6) { + var state = TranscriptState(conversationID: session.id) + if (try? await client.refresh(&state)) != nil { + if let last = state.items.last(where: { !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) { + monitorPreviews[session.id] = last.text + } + } + } + } + + 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 } + monitoredSessionIDs.remove(session.id) + selectedDeleteIDs.remove(session.id) + } + Task { + do { + try await client.deleteKanbanSession(sessionID: removed.id) + await reload() + } catch { + noticeMessage = describeHostFailure(error) + await reload() + } + } + } + + private func performBulkDelete() { + let ids = Array(selectedDeleteIDs) + guard !ids.isEmpty else { return } + withAnimation { + sessions.removeAll { ids.contains($0.id) } + selectedDeleteIDs.removeAll() + isBulkDeleteMode = false + } + Task { + for id in ids { + try? await client.deleteKanbanSession(sessionID: id) + } + noticeMessage = "已删除 \(ids.count) 个会话。" + 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 toggleMonitor(_ session: KanbanSessionSummary) { + if monitoredSessionIDs.contains(session.id) { + monitoredSessionIDs.remove(session.id) + } else { + monitoredSessionIDs.insert(session.id) + } + } + + 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/mobile/ios/App/CodeBlockView.swift b/mobile/ios/App/CodeBlockView.swift new file mode 100644 index 000000000..88ce2c3e6 --- /dev/null +++ b/mobile/ios/App/CodeBlockView.swift @@ -0,0 +1,676 @@ +import SwiftUI +import UIKit + +// MARK: - Language + +/// Languages the lightweight highlighter understands. Detection is by file +/// name; anything unknown renders as plain monospaced text. +enum CodeLanguage: String { + case javascript, typescript, json, swift, rust, python, go, java, kotlin + case c, cpp, csharp, css, html, xml, shell, yaml, toml, markdown, sql, ruby, php + case plain + + static func detect(path: String) -> CodeLanguage { + let name = (path as NSString).lastPathComponent.lowercased() + switch name { + case "dockerfile", "makefile", ".zshrc", ".bashrc", ".env", ".gitignore": return .shell + case "cargo.lock": return .toml + default: break + } + switch (name as NSString).pathExtension { + case "js", "jsx", "mjs", "cjs": return .javascript + case "ts", "tsx", "mts", "cts": return .typescript + case "json", "jsonc", "json5", "lock": return .json + case "swift": return .swift + case "rs": return .rust + case "py", "pyi": return .python + case "go": return .go + case "java": return .java + case "kt", "kts": return .kotlin + case "c", "h": return .c + case "cc", "cpp", "cxx", "hpp", "hh", "m", "mm": return .cpp + case "cs": return .csharp + case "css", "scss", "sass", "less": return .css + case "html", "htm", "vue", "svelte": return .html + case "xml", "plist", "svg", "xib", "storyboard": return .xml + case "sh", "bash", "zsh", "fish": return .shell + case "yml", "yaml": return .yaml + case "toml", "ini", "cfg", "conf": return .toml + case "md", "mdx", "markdown": return .markdown + case "sql": return .sql + case "rb": return .ruby + case "php": return .php + default: return .plain + } + } + + static func detectFromFence(_ raw: String) -> CodeLanguage { + let tag = raw.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !tag.isEmpty else { return .plain } + switch tag { + case "javascript", "js", "jsx", "mjs", "cjs", "node": return .javascript + case "typescript", "ts", "tsx": return .typescript + case "json", "jsonc", "json5": return .json + case "swift": return .swift + case "rust", "rs": return .rust + case "python", "py": return .python + case "go", "golang": return .go + case "java": return .java + case "kotlin", "kt": return .kotlin + case "c", "h": return .c + case "cpp", "c++", "cc", "cxx", "hpp", "objc", "objective-c": return .cpp + case "csharp", "c#", "cs": return .csharp + case "css", "scss", "sass", "less": return .css + case "html", "htm", "vue", "svelte": return .html + case "xml", "svg", "plist": return .xml + case "sh", "bash", "zsh", "fish", "shell", "console", "terminal": return .shell + case "yaml", "yml": return .yaml + case "toml", "ini": return .toml + case "markdown", "md", "mdx": return .markdown + case "sql", "postgres", "mysql", "sqlite": return .sql + case "ruby", "rb": return .ruby + case "php": return .php + default: + return detect(path: tag.contains(".") ? tag : "snippet.\(tag)") + } + } + + var displayName: String { + switch self { + case .javascript: return "JavaScript" + case .typescript: return "TypeScript" + case .json: return "JSON" + case .swift: return "Swift" + case .rust: return "Rust" + case .python: return "Python" + case .go: return "Go" + case .java: return "Java" + case .kotlin: return "Kotlin" + case .c: return "C" + case .cpp: return "C++" + case .csharp: return "C#" + case .css: return "CSS" + case .html: return "HTML" + case .xml: return "XML" + case .shell: return "Shell" + case .yaml: return "YAML" + case .toml: return "TOML" + case .markdown: return "Markdown" + case .sql: return "SQL" + case .ruby: return "Ruby" + case .php: return "PHP" + case .plain: return "Text" + } + } + + /// Brand-ish accent used for the header dot and file icons. + var accent: Color { + switch self { + case .javascript: return Color(red: 0.94, green: 0.76, blue: 0.13) + case .typescript: return Color(red: 0.19, green: 0.47, blue: 0.78) + case .json: return Color(red: 0.80, green: 0.55, blue: 0.10) + case .swift: return Color(red: 0.98, green: 0.42, blue: 0.24) + case .rust: return Color(red: 0.72, green: 0.38, blue: 0.22) + case .python: return Color(red: 0.22, green: 0.46, blue: 0.67) + case .go: return Color(red: 0.0, green: 0.68, blue: 0.85) + case .java, .kotlin: return Color(red: 0.69, green: 0.36, blue: 0.85) + case .c, .cpp, .csharp: return Color(red: 0.35, green: 0.45, blue: 0.80) + case .css: return Color(red: 0.34, green: 0.30, blue: 0.80) + case .html, .xml: return Color(red: 0.89, green: 0.30, blue: 0.15) + case .shell: return Color(red: 0.30, green: 0.68, blue: 0.35) + case .yaml, .toml: return Color(red: 0.80, green: 0.25, blue: 0.30) + case .markdown: return Color(red: 0.35, green: 0.40, blue: 0.48) + case .sql: return Color(red: 0.85, green: 0.50, blue: 0.10) + case .ruby: return Color(red: 0.80, green: 0.15, blue: 0.20) + case .php: return Color(red: 0.47, green: 0.48, blue: 0.70) + case .plain: return .secondary + } + } + + fileprivate var keywords: Set { + switch self { + case .javascript, .typescript: + return [ + "import", "export", "from", "default", "const", "let", "var", "function", "return", + "if", "else", "for", "while", "do", "switch", "case", "break", "continue", "new", + "class", "extends", "super", "this", "typeof", "instanceof", "in", "of", "async", + "await", "yield", "try", "catch", "finally", "throw", "delete", "void", "null", + "undefined", "true", "false", "interface", "type", "enum", "implements", "as", + "public", "private", "protected", "readonly", "static", "declare", "namespace", + "keyof", "satisfies", "abstract", + ] + case .json: return ["true", "false", "null"] + case .swift: + return [ + "import", "let", "var", "func", "return", "if", "else", "guard", "for", "in", + "while", "repeat", "switch", "case", "default", "break", "continue", "struct", + "class", "enum", "protocol", "extension", "init", "deinit", "self", "Self", "super", + "nil", "true", "false", "private", "fileprivate", "internal", "public", "open", + "static", "some", "any", "async", "await", "throws", "throw", "try", "catch", "do", + "where", "typealias", "inout", "mutating", "override", "final", "lazy", "weak", + "defer", "is", "as", "@State", "@Binding", "@Environment", "@MainActor", + ] + case .rust: + return [ + "fn", "let", "mut", "pub", "use", "mod", "crate", "self", "Self", "super", "struct", + "enum", "impl", "trait", "for", "in", "if", "else", "match", "loop", "while", + "return", "break", "continue", "as", "where", "async", "await", "move", "ref", + "static", "const", "type", "dyn", "unsafe", "true", "false", "Some", "None", "Ok", "Err", + ] + case .python: + return [ + "def", "class", "return", "if", "elif", "else", "for", "while", "in", "not", "and", + "or", "is", "import", "from", "as", "with", "try", "except", "finally", "raise", + "pass", "break", "continue", "lambda", "yield", "global", "nonlocal", "None", "True", + "False", "async", "await", "self", + ] + case .go: + return [ + "package", "import", "func", "return", "var", "const", "type", "struct", "interface", + "map", "chan", "go", "defer", "if", "else", "for", "range", "switch", "case", + "default", "break", "continue", "select", "nil", "true", "false", + ] + case .java, .kotlin, .csharp, .c, .cpp, .php: + return [ + "import", "package", "class", "interface", "enum", "struct", "public", "private", + "protected", "static", "final", "void", "int", "long", "float", "double", "bool", + "boolean", "char", "return", "if", "else", "for", "while", "do", "switch", "case", + "default", "break", "continue", "new", "this", "null", "true", "false", "try", + "catch", "finally", "throw", "throws", "extends", "implements", "fun", "val", "var", + "const", "using", "namespace", "include", "define", "typedef", "auto", "function", + "echo", "override", "object", "when", "is", "in", + ] + case .shell: + return [ + "if", "then", "else", "elif", "fi", "for", "in", "do", "done", "while", "case", + "esac", "function", "return", "export", "local", "echo", "cd", "set", "unset", + "source", "exit", "FROM", "RUN", "COPY", "CMD", "ENV", "WORKDIR", "ARG", "EXPOSE", + ] + case .sql: + let base = [ + "select", "from", "where", "insert", "into", "values", "update", "set", "delete", + "create", "table", "drop", "alter", "index", "join", "left", "right", "inner", + "outer", "on", "and", "or", "not", "null", "as", "order", "by", "group", "having", + "limit", "primary", "key", "foreign", "references", "default", "distinct", + ] + return Set(base + base.map { $0.uppercased() }) + case .ruby: + return [ + "def", "end", "class", "module", "if", "elsif", "else", "unless", "while", "do", + "return", "require", "self", "nil", "true", "false", "yield", "begin", "rescue", + ] + case .yaml, .toml: return ["true", "false", "null", "yes", "no", "on", "off"] + case .css, .html, .xml, .markdown, .plain: return [] + } + } + + fileprivate var lineComment: [String] { + switch self { + case .python, .shell, .yaml, .toml, .ruby: return ["#"] + case .sql: return ["--"] + case .json: return ["//"] + case .css, .html, .xml, .markdown, .plain: return [] + case .php: return ["//", "#"] + default: return ["//"] + } + } + + fileprivate var blockComment: (String, String)? { + switch self { + case .html, .xml, .markdown: return ("") + case .python, .shell, .yaml, .toml, .ruby, .plain: return nil + default: return ("/*", "*/") + } + } + + fileprivate var hasMarkup: Bool { + switch self { + case .html, .xml, .javascript, .typescript: return true + default: return false + } + } +} + +// MARK: - Highlighter + +private enum TokenKind { + case keyword, string, comment, number, type, function, property, tag, attribute, punctuation +} + +private struct CodeTheme { + static func color(_ kind: TokenKind) -> UIColor { + switch kind { + case .keyword: return dynamic(0xCF222E, 0xFF7B72) + case .string: return dynamic(0x0A3069, 0xA5D6FF) + case .comment: return dynamic(0x6E7781, 0x8B949E) + case .number: return dynamic(0x0550AE, 0x79C0FF) + case .type: return dynamic(0x953800, 0xFFA657) + case .function: return dynamic(0x8250DF, 0xD2A8FF) + case .property: return dynamic(0x0550AE, 0x7EE787) + case .tag: return dynamic(0x116329, 0x7EE787) + case .attribute: return dynamic(0x0550AE, 0x79C0FF) + case .punctuation: return dynamic(0x57606A, 0x8B949E) + } + } + + private static func dynamic(_ light: UInt32, _ dark: UInt32) -> UIColor { + UIColor { $0.userInterfaceStyle == .dark ? hex(dark) : hex(light) } + } + + private static func hex(_ v: UInt32) -> UIColor { + UIColor( + red: CGFloat((v >> 16) & 0xFF) / 255, + green: CGFloat((v >> 8) & 0xFF) / 255, + blue: CGFloat(v & 0xFF) / 255, + alpha: 1 + ) + } +} + +/// Single-pass scanner over UTF-16 units. Not a parser — it recognises +/// comments, strings, numbers, identifiers and markup tags well enough for a +/// readable phone preview, and degrades to plain text for anything else. +enum CodeHighlighter { + static func highlight(_ source: String, language: CodeLanguage) -> [AttributedString] { + let ns = source as NSString + let length = ns.length + var units = [unichar](repeating: 0, count: length) + ns.getCharacters(&units, range: NSRange(location: 0, length: length)) + + var tokens: [(NSRange, TokenKind)] = [] + if language != .plain { + tokens = scan(units, language: language) + } + + // Split into lines and colour each line's slice of the token stream. + var lines: [AttributedString] = [] + var tokenIndex = 0 + var lineStart = 0 + var i = 0 + while i <= length { + if i == length || units[i] == 10 { + var end = i + if end > lineStart, units[end - 1] == 13 { end -= 1 } + let text = ns.substring(with: NSRange(location: lineStart, length: end - lineStart)) + var line = AttributedString(text) + while tokenIndex < tokens.count, NSMaxRange(tokens[tokenIndex].0) <= lineStart { + tokenIndex += 1 + } + var t = tokenIndex + while t < tokens.count, tokens[t].0.location < end { + let (range, kind) = tokens[t] + let lo = max(range.location, lineStart) - lineStart + let hi = min(NSMaxRange(range), end) - lineStart + if hi > lo { + let sLo = String.Index(utf16Offset: lo, in: text) + let sHi = String.Index(utf16Offset: hi, in: text) + if let r = Range(sLo.. Bool { + (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 95 || c == 36 || c == 64 || c > 127 + } + + private static func isIdent(_ c: unichar) -> Bool { + isIdentStart(c) || (c >= 48 && c <= 57) + } + + private static func isDigit(_ c: unichar) -> Bool { c >= 48 && c <= 57 } + + private static func matches(_ units: [unichar], _ at: Int, _ word: String) -> Bool { + let w = Array(word.utf16) + guard at + w.count <= units.count else { return false } + for k in 0.. [(NSRange, TokenKind)] { + var out: [(NSRange, TokenKind)] = [] + let n = u.count + let keywords = language.keywords + let lineComments = language.lineComment + let block = language.blockComment + var i = 0 + var lineHasContent = false + + func add(_ start: Int, _ end: Int, _ kind: TokenKind) { + if end > start { out.append((NSRange(location: start, length: end - start), kind)) } + } + + while i < n { + let c = u[i] + if c == 10 { lineHasContent = false; i += 1; continue } + + // Block comment + if let (open, close) = block, matches(u, i, open) { + let start = i + i += open.utf16.count + while i < n, !matches(u, i, close) { i += 1 } + i = min(n, i + close.utf16.count) + add(start, i, .comment) + continue + } + + // Line comment (shell '#' only at token boundary) + if let lc = lineComments.first(where: { matches(u, i, $0) }) { + let boundary = i == 0 || u[i - 1] == 32 || u[i - 1] == 9 || u[i - 1] == 10 + if lc != "#" || boundary || language == .python || language == .yaml || language == .toml { + let start = i + while i < n, u[i] != 10 { i += 1 } + add(start, i, .comment) + continue + } + } + + // Markup tags: / + if language.hasMarkup, c == 60, i + 1 < n, isIdentStart(u[i + 1]) || u[i + 1] == 47 { + var j = i + 1 + if u[j] == 47 { j += 1 } + let nameStart = j + while j < n, isIdent(u[j]) || u[j] == 46 || u[j] == 45 || u[j] == 58 { j += 1 } + if j > nameStart, language == .html || language == .xml || u[nameStart] >= 65 && u[nameStart] <= 90 || j < n && (u[j] == 32 || u[j] == 62 || u[j] == 10 || u[j] == 47) { + add(i, nameStart, .punctuation) + add(nameStart, j, (u[nameStart] >= 65 && u[nameStart] <= 90) ? .type : .tag) + i = j + // attributes until '>' on the same tag (html/xml only; JSX attrs fall through) + if language == .html || language == .xml { + while i < n, u[i] != 62 { + if u[i] == 34 || u[i] == 39 { + let q = u[i]; let s = i; i += 1 + while i < n, u[i] != q { i += 1 } + i = min(n, i + 1) + add(s, i, .string) + } else if isIdentStart(u[i]) { + let s = i + while i < n, isIdent(u[i]) || u[i] == 45 || u[i] == 58 { i += 1 } + add(s, i, .attribute) + } else { i += 1 } + } + if i < n { add(i, i + 1, .punctuation); i += 1 } + } + lineHasContent = true + continue + } + } + + // Strings + if c == 34 || c == 39 || (c == 96 && language != .markdown) { + if c == 39, language == .markdown || language == .plain { i += 1; continue } + let start = i + let quote = c + i += 1 + while i < n { + if u[i] == 92 { i += 2; continue } + if u[i] == quote { i += 1; break } + if u[i] == 10, quote != 96 { break } + i += 1 + } + i = min(i, n) + // JSON / YAML keys: string followed by ':' + var k = i + while k < n, u[k] == 32 || u[k] == 9 { k += 1 } + let isKey = k < n && u[k] == 58 && (language == .json || language == .yaml || language == .javascript || language == .typescript || language == .python) + add(start, i, isKey ? .property : .string) + lineHasContent = true + continue + } + + // Numbers + if isDigit(c), i == 0 || !isIdent(u[i - 1]) { + let start = i + while i < n, isIdent(u[i]) || u[i] == 46 { i += 1 } + add(start, i, .number) + lineHasContent = true + continue + } + + // Identifiers + if isIdentStart(c) { + let start = i + i += 1 + while i < n, isIdent(u[i]) || (language == .css && u[i] == 45) { i += 1 } + let word = String(utf16CodeUnits: Array(u[start..= 65, first <= 90 { + add(start, i, .type) + } else if start > 0, u[start - 1] == 46 { + add(start, i, .property) + } + lineHasContent = true + continue + } + + // Markdown headings / list markers + if language == .markdown, !lineHasContent, c == 35 || c == 62 || c == 45 || c == 42 { + let start = i + while i < n, u[i] != 10 { i += 1 } + add(start, i, c == 35 ? .keyword : .punctuation) + continue + } + + if c != 32, c != 9 { lineHasContent = true } + i += 1 + } + return out + } +} + +// MARK: - File icons + +enum FileGlyph { + static func symbol(for path: String) -> String { + let name = (path as NSString).lastPathComponent.lowercased() + let ext = (name as NSString).pathExtension + if name.hasPrefix("readme") { return "book.closed" } + if name == "license" || name.hasPrefix("license.") { return "checkmark.seal" } + if name.hasPrefix(".git") { return "arrow.triangle.branch" } + if name == "dockerfile" { return "shippingbox" } + switch ext { + case "png", "jpg", "jpeg", "gif", "webp", "heic", "ico", "icns": return "photo" + case "svg": return "scribble.variable" + case "mp4", "mov", "webm": return "film" + case "mp3", "wav", "m4a": return "waveform" + case "zip", "gz", "tar", "tgz", "rar", "7z": return "doc.zipper" + case "pdf": return "doc.richtext" + case "md", "mdx", "txt", "rtf": return "doc.plaintext" + case "json", "jsonc", "lock": return "curlybraces" + case "yml", "yaml", "toml", "ini", "cfg", "conf", "env", "plist": return "gearshape" + case "swift": return "swift" + case "sh", "bash", "zsh", "fish": return "terminal" + case "html", "htm", "xml", "vue", "svelte": return "chevron.left.forwardslash.chevron.right" + case "css", "scss", "sass", "less": return "paintbrush" + case "sql", "db", "sqlite": return "cylinder.split.1x2" + case "ttf", "otf", "woff", "woff2": return "textformat" + case "js", "jsx", "mjs", "cjs", "ts", "tsx", "rs", "py", "go", "java", "kt", "c", "h", + "cpp", "hpp", "cs", "rb", "php", "m", "mm": + return "chevron.left.forwardslash.chevron.right" + default: return "doc.text" + } + } +} + +// MARK: - Code block + +/// Code viewer modelled on the desktop `CodeBlock`: titled header with the +/// language, copy and wrap actions, a line-number gutter and syntax colours. +struct CodeBlockView: View { + let code: String + let title: String + var language: CodeLanguage = .plain + var hasLineNumbers = true + var note: String? + + @State private var lines: [AttributedString]? + @State private var wraps = false + @State private var copied = false + @AppStorage("vibex.code.fontSize") private var fontSize: Double = 12 + + private var lineCount: Int { lines?.count ?? 0 } + private var gutterWidth: CGFloat { + CGFloat(max(2, String(lineCount).count)) * fontSize * 0.62 + 6 + } + + var body: some View { + VStack(spacing: 0) { + header + Divider().opacity(0.6) + if let lines { + codeBody(lines) + } else { + ProgressView() + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + .background(Color(.secondarySystemGroupedBackground)) + .task(id: code) { + let source = code + let lang = language + lines = await Task.detached(priority: .userInitiated) { + CodeHighlighter.highlight(source, language: lang) + }.value + } + } + + private var header: some View { + HStack(spacing: 8) { + Image(systemName: FileGlyph.symbol(for: title)) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(language.accent) + .frame(width: 22, height: 22) + .background(language.accent.opacity(0.14), in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + VStack(alignment: .leading, spacing: 0) { + Text(title) + .font(.system(size: 13, weight: .semibold, design: .monospaced)) + .lineLimit(1) + .truncationMode(.middle) + Text("\(language.displayName) · \(lineCount) 行") + .font(.system(size: 10.5)) + .foregroundStyle(.secondary) + } + Spacer(minLength: 6) + headerButton(wraps ? "text.alignleft" : "arrow.left.and.right.text.vertical", label: wraps ? "取消换行" : "自动换行", on: wraps) { + withAnimation(.easeInOut(duration: 0.18)) { wraps.toggle() } + } + Menu { + Button("缩小字号", systemImage: "textformat.size.smaller") { fontSize = max(9, fontSize - 1) } + Button("放大字号", systemImage: "textformat.size.larger") { fontSize = min(18, fontSize + 1) } + Button("恢复默认", systemImage: "arrow.counterclockwise") { fontSize = 12 } + } label: { + Image(systemName: "textformat.size") + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(.secondary) + .frame(width: 28, height: 28) + .background(Color(.tertiarySystemFill), in: Circle()) + } + headerButton(copied ? "checkmark" : "doc.on.doc", label: "复制代码", on: copied) { + UIPasteboard.general.string = code + UIImpactFeedbackGenerator(style: .light).impactOccurred() + withAnimation { copied = true } + Task { + try? await Task.sleep(for: .seconds(1.4)) + withAnimation { copied = false } + } + } + } + .padding(.horizontal, 12) + .padding(.vertical, 8) + } + + private func headerButton(_ icon: String, label: String, on: Bool, action: @escaping () -> Void) -> some View { + Button(action: action) { + Image(systemName: icon) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(on ? Color.accentColor : .secondary) + .frame(width: 28, height: 28) + .background(on ? Color.accentColor.opacity(0.14) : Color(.tertiarySystemFill), in: Circle()) + .contentTransition(.symbolEffect(.replace)) + } + .buttonStyle(.plain) + .accessibilityLabel(label) + } + + @ViewBuilder + private func codeBody(_ lines: [AttributedString]) -> some View { + let font = Font.system(size: fontSize, design: .monospaced) + let rows = LazyVStack(alignment: .leading, spacing: 0) { + ForEach(Array(lines.enumerated()), id: \.offset) { index, line in + HStack(alignment: .firstTextBaseline, spacing: 10) { + if hasLineNumbers { + Text("\(index + 1)") + .foregroundStyle(.tertiary) + .frame(width: gutterWidth, alignment: .trailing) + } + Text(line.characters.isEmpty ? AttributedString(" ") : line) + .foregroundStyle(.primary) + .fixedSize(horizontal: !wraps, vertical: true) + .frame(maxWidth: wraps ? .infinity : nil, alignment: .leading) + } + .font(font) + .lineSpacing(2) + .padding(.vertical, 1) + } + if let note { + Label(note, systemImage: "scissors") + .font(.footnote) + .foregroundStyle(.secondary) + .padding(.top, 12) + } + } + .textSelection(.enabled) + .padding(.vertical, 10) + .padding(.horizontal, 12) + + if wraps { + ScrollView(.vertical) { rows } + } else { + ScrollView([.vertical, .horizontal]) { rows } + } + } +} + +#Preview { + CodeBlockView( + code: """ + 'use client'; + + import {CodeBlock} from '@astryxdesign/core/CodeBlock'; + + const code = `{ + "name": "@astryxdesign/core", + "version": "0.0.5" + }`; + + export default function CodeBlockJSONConfig() { + return ( + + ); + } + """, + title: "CodeBlockJSONConfig.tsx", + language: .typescript + ) +} diff --git a/mobile/ios/App/CollaborationChatView.swift b/mobile/ios/App/CollaborationChatView.swift new file mode 100644 index 000000000..5ac8f42c6 --- /dev/null +++ b/mobile/ios/App/CollaborationChatView.swift @@ -0,0 +1,870 @@ +import CompanionCore +import SwiftUI + +struct CollaborationChatView: View { + let client: HostClient + let workspaceID: String + let item: CollabSidebarItem + let allSidebarItems: [CollabSidebarItem] + let contactGroups: [CollabContactGroup] + let onChanged: () async -> Void + + @State private var messages: [CollabSpaceMessage] = [] + @State private var scheduled: [CollabScheduledMessage] = [] + @State private var cards: [CollabCard] = [] + @State private var members: [CollabSpaceMember] = [] + @State private var loading = true + @State private var errorMessage: String? + + // Composer state + @State private var draftText = "" + @State private var selectedMentions: [String] = [] + @State private var replyingTo: CollabSpaceMessage? + @State private var delaySeconds: Int = 0 + @State private var sending = false + + // Sheets & navigation + @State private var showingDetails = false + @State private var openedConversation: ConversationListItem? + @State private var cardAnswerDraft: [String: String] = [:] + @State private var headerReactionTrigger: Int = 0 + + private static let quickEmojis = ["👍", "❤️", "🎉", "🚀", "👀", "💡"] + private static let delayOptions: [(label: String, seconds: Int)] = [ + ("立即发送", 0), + ("30 秒后", 30), + ("1 分钟后", 60), + ("5 分钟后", 300), + ("15 分钟后", 900), + ] + + private var spaceID: String { item.targetSpaceId } + + private var agentMembers: [CollabSpaceMember] { + members.filter(\.isAgent) + } + + private var isChatActive: Bool { + sending + || messages.contains(where: \.streaming) + || messages.contains { $0.receipts.contains(where: \.isProcessing) } + } + + var body: some View { + VStack(spacing: 0) { + if !scheduled.isEmpty { + scheduledBanner + } + + messageStream + + if !cards.filter(\.isPending).isEmpty { + pendingCardsStack + } + + composerBar + } + .navigationTitle(item.displayName) + .navigationBarTitleDisplayMode(.inline) + .toolbar(.hidden, for: .tabBar) + .toolbar { + ToolbarItem(placement: .principal) { + Button { + headerReactionTrigger += 1 + } label: { + HStack(spacing: 8) { + if item.isGroup { + let groupAvatars = (agentMembers.isEmpty ? item.membersPreview.map(\.botAvatar) : agentMembers.map(\.botAvatar)) + CollabGroupAvatarView( + avatars: groupAvatars.isEmpty + ? [CollabBotAvatarConfig.derive(seed: item.displayName)] + : groupAvatars, + tagColorHex: item.tagColor, + size: 28, + sessionActive: isChatActive + ) + } else { + let dmAvatar = item.member?.botAvatar + ?? CollabBotAvatarConfig.derive(seed: item.displayName) + MemberBotAvatarView( + config: dmAvatar, + size: 28, + animated: true, + sessionActive: isChatActive, + isSupervisor: item.member?.isSupervisor == true, + reactionTrigger: headerReactionTrigger + ) + } + + Text(item.displayName) + .font(.system(size: 16, weight: .semibold)) + .foregroundStyle(.primary) + .lineLimit(1) + + if item.isGroup, item.memberCount > 0 { + Text("(\(item.memberCount))") + .font(.system(size: 12)) + .foregroundStyle(.secondary) + } + } + .padding(.vertical, 2) + } + .buttonStyle(.plain) + } + ToolbarItem(placement: .primaryAction) { + HStack(spacing: 12) { + if item.isDirect, let member = item.member { + Button { + openMemberSession(memberID: member.resolvedIdentityId, fallbackConvID: member.conversationId, title: item.displayName) + } label: { + Image(systemName: "terminal") + } + .accessibilityLabel("打开助手会话") + } + Button { + showingDetails = true + } label: { + Image(systemName: item.isGroup ? "person.3" : "slider.horizontal.3") + } + .accessibilityLabel(item.isGroup ? "群组详情" : "助手详情") + } + } + } + .sheet(isPresented: $showingDetails) { + CollaborationDetailSheet( + client: client, + workspaceID: workspaceID, + item: item, + members: members, + allSidebarItems: allSidebarItems, + contactGroups: contactGroups, + onOpenConversation: { conv in + showingDetails = false + openedConversation = conv + }, + onChanged: { + await reload() + await onChanged() + } + ) + } + .navigationDestination(item: $openedConversation) { conv in + ConversationDetailView(client: client, conversation: conv) + } + .onDisappear { + dismissKeyboard() + } + .task { + try? await client.collabMarkRead(threadID: item.threadId) + while !Task.isCancelled { + await reload() + try? await Task.sleep(for: .seconds(2.5)) + } + } + } + + // MARK: - Message Stream + + @ViewBuilder + private var messageStream: some View { + if loading && messages.isEmpty && errorMessage == nil { + Spacer() + ProgressView() + Spacer() + } else if let errorMessage, messages.isEmpty { + Spacer() + LoadFailureView(message: errorMessage) { Task { await reload() } } + Spacer() + } else if messages.isEmpty { + Spacer() + ContentUnavailableView { + Label(item.isGroup ? "群里还没有消息" : "还没有私聊消息", systemImage: "bubble.left.and.bubble.right") + } description: { + Text(item.isGroup ? "用下方输入框发送消息,可 @ 指定助手协同处理" : "在下方输入内容即可与 \(item.displayName) 对话") + } + Spacer() + } else { + ScrollViewReader { proxy in + ScrollView { + LazyVStack(alignment: .leading, spacing: 14) { + ForEach(messages) { message in + CollabMessageRow( + message: message, + allMessages: messages, + isGroup: item.isGroup, + senderAvatar: resolveSenderAvatar(for: message), + quickEmojis: Self.quickEmojis, + onTapSender: { + openSenderSession(for: message) + }, + onReply: { + withAnimation { replyingTo = message } + }, + onReact: { emoji in + react(to: message, emoji: emoji) + }, + onCollect: { + collectMessage(message) + }, + onDistill: { + distillMessage(message) + }, + onCancelReceiptTurn: { receipt in + cancelTurn(for: receipt) + } + ) + .id(message.id) + } + } + .padding(.horizontal, 14) + .padding(.vertical, 12) + } + .scrollDismissesKeyboard(.interactively) + .onChange(of: messages.last?.id) { _, lastID in + if let lastID { + withAnimation(.easeOut(duration: 0.2)) { + proxy.scrollTo(lastID, anchor: .bottom) + } + } + } + } + } + } + + // MARK: - Scheduled Messages Banner + + private var scheduledBanner: some View { + VStack(alignment: .leading, spacing: 6) { + ForEach(scheduled) { item in + HStack(spacing: 8) { + Image(systemName: "clock.fill") + .font(.system(size: 12)) + .foregroundStyle(.orange) + VStack(alignment: .leading, spacing: 2) { + Text(item.content) + .font(.system(size: 12, weight: .medium)) + .lineLimit(1) + Text("定时投递:\(item.deliverAt)") + .font(.system(size: 10)) + .foregroundStyle(.secondary) + } + Spacer() + Button("取消") { + cancelScheduled(item) + } + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(.red) + } + .padding(.horizontal, 12) + .padding(.vertical, 6) + .background(Color.orange.opacity(0.1)) + } + } + } + + // MARK: - Pending Approval & Ask Cards + + private var pendingCardsStack: some View { + VStack(spacing: 8) { + ForEach(cards.filter(\.isPending)) { card in + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 6) { + Image(systemName: card.kind == "approval" ? "checkmark.shield.fill" : "questionmark.circle.fill") + .foregroundStyle(card.kind == "approval" ? .orange : .blue) + Text(card.kind == "approval" ? "待审批请求" : "助手提问") + .font(.system(size: 13, weight: .semibold)) + Spacer() + } + if let text = card.question ?? card.reason ?? card.action ?? card.command { + Text(text) + .font(.system(size: 13)) + .foregroundStyle(.primary) + } + if card.kind == "approval" { + HStack(spacing: 8) { + Button { + resolveCard(card, decision: "approved", answer: nil, declined: false) + } label: { + Text("批准") + .font(.system(size: 13, weight: .medium)) + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + + Button(role: .destructive) { + resolveCard(card, decision: "rejected", answer: nil, declined: true) + } label: { + Text("拒绝") + .font(.system(size: 13, weight: .medium)) + .frame(maxWidth: .infinity) + } + .buttonStyle(.bordered) + } + } else { + if !card.options.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 6) { + ForEach(card.options, id: \.self) { opt in + Button(opt) { + resolveCard(card, decision: nil, answer: opt, declined: false) + } + .font(.system(size: 12, weight: .medium)) + .padding(.horizontal, 10) + .padding(.vertical, 5) + .background(Capsule().fill(Color.blue.opacity(0.12))) + } + } + } + } + HStack(spacing: 8) { + TextField( + "输入回答…", + text: Binding( + get: { cardAnswerDraft[card.id] ?? "" }, + set: { cardAnswerDraft[card.id] = $0 } + ) + ) + .textFieldStyle(.roundedBorder) + .font(.system(size: 13)) + + Button("发送") { + let ans = (cardAnswerDraft[card.id] ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + guard !ans.isEmpty else { return } + resolveCard(card, decision: nil, answer: ans, declined: false) + } + .buttonStyle(.borderedProminent) + .controlSize(.small) + + Button("跳过") { + resolveCard(card, decision: nil, answer: nil, declined: true) + } + .buttonStyle(.bordered) + .controlSize(.small) + } + } + } + .padding(12) + .background( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + .shadow(color: .black.opacity(0.06), radius: 6, y: 2) + ) + } + } + .padding(.horizontal, 12) + .padding(.vertical, 6) + } + + // MARK: - Composer Bar + + private var composerBar: some View { + VStack(spacing: 6) { + Divider() + + if let reply = replyingTo { + HStack(spacing: 8) { + Image(systemName: "arrowshape.turn.up.left.fill") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + Text("回复 \(reply.envelope.displaySender):\(reply.envelope.content)") + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .lineLimit(1) + Spacer() + Button { + withAnimation { replyingTo = nil } + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(.secondary) + } + } + .padding(.horizontal, 14) + .padding(.top, 4) + } + + if item.isGroup && !agentMembers.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 6) { + mentionChip(name: "全体成员", label: "@全体成员", avatar: nil) + ForEach(agentMembers) { member in + mentionChip( + name: member.nickname, + label: "@\(member.nickname)", + avatar: member.botAvatar + ) + } + } + .padding(.horizontal, 14) + } + } + + if let errorMessage, !messages.isEmpty { + Text(errorMessage) + .font(.system(size: 11)) + .foregroundStyle(.red) + .padding(.horizontal, 14) + } + + HStack(alignment: .bottom, spacing: 8) { + if item.isGroup { + Menu { + ForEach(Self.delayOptions, id: \.seconds) { option in + Button { + delaySeconds = option.seconds + } label: { + HStack { + Text(option.label) + if delaySeconds == option.seconds { + Image(systemName: "checkmark") + } + } + } + } + } label: { + 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) + } + .accessibilityLabel("定时发送") + } + + TextField( + item.isGroup ? "发送群消息(可点上方 @ 提及助手)…" : "给 \(item.displayName) 发消息…", + text: $draftText, + axis: .vertical + ) + .lineLimit(1...5) + .font(.system(size: 14)) + .padding(.horizontal, 12) + .padding(.vertical, 8) + .background( + RoundedRectangle(cornerRadius: 18, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + + Button { + sendMessage() + } label: { + Image(systemName: "arrow.up.circle.fill") + .font(.system(size: 30)) + .foregroundStyle(canSend ? Color.blue : Color.secondary.opacity(0.4)) + } + .disabled(!canSend) + .accessibilityLabel("发送") + } + .padding(.horizontal, 12) + .padding(.bottom, 8) + } + .background(Color(.systemBackground)) + } + + private func mentionChip(name: String, label: String, avatar: CollabBotAvatarConfig?) -> some View { + let isSelected = selectedMentions.contains(name) + return Button { + if isSelected { + selectedMentions.removeAll { $0 == name } + } else { + selectedMentions.append(name) + if !draftText.contains("@\(name)") { + draftText = (draftText.isEmpty ? "" : draftText + " ") + "@\(name) " + } + } + } label: { + HStack(spacing: 5) { + if let avatar { + MemberBotAvatarView(config: avatar, size: 17) + } + Text(label) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(isSelected ? .white : .primary) + } + .padding(.horizontal, 9) + .padding(.vertical, 4) + .background( + Capsule() + .fill(isSelected ? Color.blue : Color.primary.opacity(0.07)) + ) + } + .buttonStyle(.plain) + } + + private func resolveSenderAvatar(for message: CollabSpaceMessage) -> CollabBotAvatarConfig { + if item.isDirect, let dmMember = item.member { + return dmMember.botAvatar + } + if let matched = agentMembers.first(where: { + $0.nickname == message.envelope.sender || $0.conversationId == message.envelope.conversationId + }) { + return matched.botAvatar + } + if let preview = item.membersPreview.first(where: { + $0.name == message.envelope.sender || $0.conversationId == message.envelope.conversationId + }) { + return preview.botAvatar + } + return CollabBotAvatarConfig.derive(seed: message.envelope.displaySender) + } + + private var canSend: Bool { + !sending && !draftText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + // MARK: - Network Operations + + private func reload() async { + do { + async let pageTask = client.collabMessages(spaceID: spaceID) + async let membersTask = item.isGroup ? client.collabSpaceMembers(spaceID: spaceID) : [] + let page = try await pageTask + let loadedMembers = (try? await membersTask) ?? [] + messages = page.messages + scheduled = page.scheduled + cards = page.cards + members = loadedMembers + errorMessage = nil + } catch { + errorMessage = describeHostFailure(error) + } + loading = false + } + + private func sendMessage() { + let text = draftText.trimmingCharacters(in: .whitespacesAndNewlines) + guard !text.isEmpty, !sending else { return } + sending = true + let recipients = selectedMentions + let replyID = replyingTo?.id + let delay = delaySeconds > 0 ? delaySeconds : nil + + draftText = "" + selectedMentions = [] + replyingTo = nil + delaySeconds = 0 + + Task { + do { + try await client.collabPostMessage( + spaceID: spaceID, + content: text, + to: recipients, + inReplyTo: replyID, + delaySeconds: delay + ) + errorMessage = nil + await reload() + await onChanged() + } catch { + errorMessage = describeHostFailure(error) + } + sending = false + } + } + + private func react(to message: CollabSpaceMessage, emoji: String) { + Task { + try? await client.collabReact(spaceID: spaceID, messageID: message.id, emoji: emoji) + await reload() + } + } + + private func collectMessage(_ message: CollabSpaceMessage) { + Task { + try? await client.collaborationCommand("space.addCollectionItem", input: [ + "spaceId": spaceID, + "kind": "text", + "name": "\(message.envelope.displaySender) 的消息", + "content": message.envelope.content, + "creatorNickname": "User", + ]) + } + } + + private func distillMessage(_ message: CollabSpaceMessage) { + Task { + try? await client.collaborationCommand("space.memory.distillMessage", input: [ + "spaceId": spaceID, + "messageId": message.id, + "content": message.envelope.content, + ]) + } + } + + private func cancelTurn(for receipt: CollabDeliveryReceipt) { + guard let matched = agentMembers.first(where: { + $0.conversationId == receipt.conversationId || $0.nickname == receipt.nickname + }) else { return } + Task { + try? await client.collabCancelSpaceTurn(spaceID: spaceID, memberID: matched.memberId) + await reload() + } + } + + private func cancelScheduled(_ scheduledItem: CollabScheduledMessage) { + Task { + try? await client.collaborationCommand("space.cancelScheduledMessage", input: [ + "spaceId": spaceID, + "id": scheduledItem.id, + ]) + await reload() + } + } + + private func resolveCard(_ card: CollabCard, decision: String?, answer: String?, declined: Bool) { + Task { + try? await client.collabResolveCard( + cardID: card.id, + decision: decision, + answer: answer, + declined: declined + ) + cardAnswerDraft[card.id] = nil + await reload() + } + } + + private func openSenderSession(for message: CollabSpaceMessage) { + guard !message.isFromUser, !message.envelope.isSystem else { return } + if let convID = message.envelope.conversationId, !convID.isEmpty { + openConversation(id: convID, title: message.envelope.displaySender) + return + } + if let matched = agentMembers.first(where: { $0.nickname == message.envelope.sender }) { + openMemberSession( + memberID: matched.resolvedIdentityId, + fallbackConvID: matched.conversationId, + title: matched.nickname + ) + } + } + + private func openMemberSession(memberID: String, fallbackConvID: String?, title: String) { + Task { + let resolved = (try? await client.collabResolveSession(memberID: memberID, threadID: item.threadId)) ?? fallbackConvID + guard let convID = resolved, !convID.isEmpty else { return } + openConversation(id: convID, title: title) + } + } + + private func openConversation(id: String, title: String) { + guard let data = try? JSONSerialization.data(withJSONObject: [ + "id": id, + "workspace_id": workspaceID, + "title": title, + "message_count": 0, + "updated_at": ISO8601DateFormatter().string(from: Date()), + ]), + let item = try? JSONDecoder().decode(ConversationListItem.self, from: data) + else { return } + openedConversation = item + } +} + +// MARK: - Single Message Row + +private struct CollabMessageRow: View { + let message: CollabSpaceMessage + let allMessages: [CollabSpaceMessage] + let isGroup: Bool + let senderAvatar: CollabBotAvatarConfig + let quickEmojis: [String] + let onTapSender: () -> Void + let onReply: () -> Void + let onReact: (String) -> Void + let onCollect: () -> Void + let onDistill: () -> Void + let onCancelReceiptTurn: (CollabDeliveryReceipt) -> Void + + private var repliedMessage: CollabSpaceMessage? { + guard let replyID = message.inReplyTo, !replyID.isEmpty else { return nil } + let clean = replyID.replacingOccurrences(of: "vibex://space-message/", with: "") + return allMessages.first { $0.id == clean } + } + + private var senderColor: Color { + Color(collabHex: senderAvatar.color) ?? CollabTagPalette.hashColor(message.envelope.displaySender) + } + + var body: some View { + HStack(alignment: .top, spacing: 10) { + if message.isFromUser { + Spacer(minLength: 36) + } else { + Button(action: onTapSender) { + MemberBotAvatarView( + config: senderAvatar, + size: 32, + animated: true, + sessionActive: message.streaming + ) + } + .buttonStyle(.plain) + } + + VStack(alignment: message.isFromUser ? .trailing : .leading, spacing: 5) { + HStack(spacing: 6) { + Button(action: onTapSender) { + Text(message.envelope.displaySender) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(message.isFromUser ? .secondary : senderColor) + } + .buttonStyle(.plain) + + ForEach(message.envelope.recipientLabels, id: \.self) { target in + Text("@\(target)") + .font(.system(size: 10, weight: .medium)) + .foregroundStyle(.blue) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background(Capsule().fill(Color.blue.opacity(0.12))) + } + + if message.streaming { + ProgressView() + .controlSize(.mini) + } + } + + if let replied = repliedMessage { + HStack(spacing: 5) { + Rectangle() + .fill(Color.secondary.opacity(0.4)) + .frame(width: 2, height: 14) + Text("\(replied.envelope.displaySender):\(replied.envelope.content)") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background( + RoundedRectangle(cornerRadius: 6, style: .continuous) + .fill(Color.primary.opacity(0.05)) + ) + } + + Text(message.envelope.content) + .font(.system(size: 14)) + .foregroundStyle(message.isFromUser ? .white : .primary) + .padding(.horizontal, 12) + .padding(.vertical, 9) + .background( + RoundedRectangle(cornerRadius: 14, style: .continuous) + .fill(message.isFromUser ? Color.blue : Color(.secondarySystemGroupedBackground)) + ) + .textSelection(.enabled) + .contextMenu { + ForEach(quickEmojis, id: \.self) { emoji in + Button("\(emoji) 表情回应") { onReact(emoji) } + } + Divider() + Button { + onReply() + } label: { + Label("回复", systemImage: "arrowshape.turn.up.left") + } + Button { + UIPasteboard.general.string = message.envelope.content + } label: { + Label("复制内容", systemImage: "doc.on.doc") + } + Button { + onCollect() + } label: { + Label("加入空间收藏", systemImage: "bookmark") + } + Button { + onDistill() + } label: { + Label("提炼到空间记忆", systemImage: "brain") + } + if !message.isFromUser && !message.envelope.isSystem { + Divider() + Button { + onTapSender() + } label: { + Label("打开该助手会话", systemImage: "terminal") + } + } + } + + // Reactions bar + let reactions = message.groupedReactions + if !reactions.isEmpty { + HStack(spacing: 4) { + ForEach(reactions, id: \.emoji) { r in + Button { + onReact(r.emoji) + } label: { + HStack(spacing: 3) { + Text(r.emoji) + .font(.system(size: 12)) + Text("\(r.count)") + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(r.byUser ? .blue : .secondary) + } + .padding(.horizontal, 7) + .padding(.vertical, 3) + .background( + Capsule() + .fill(r.byUser ? Color.blue.opacity(0.15) : Color.primary.opacity(0.06)) + ) + } + .buttonStyle(.plain) + } + } + } + + // Delivery Receipts (for user messages in group/direct chats) + if message.isFromUser && !message.receipts.isEmpty { + HStack(spacing: 6) { + ForEach(message.receipts) { receipt in + HStack(spacing: 4) { + Circle() + .fill(receiptColor(receipt.effectiveState)) + .frame(width: 6, height: 6) + if let nick = receipt.nickname, !nick.isEmpty { + Text(nick) + .font(.system(size: 10, weight: .medium)) + } + Text(receipt.stateLabel) + .font(.system(size: 10)) + .foregroundStyle(.secondary) + if isGroup && receipt.isProcessing { + Button { + onCancelReceiptTurn(receipt) + } label: { + Image(systemName: "stop.circle.fill") + .font(.system(size: 11)) + .foregroundStyle(.red) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + Capsule() + .fill(Color.primary.opacity(0.05)) + ) + } + } + } + } + + if !message.isFromUser { + Spacer(minLength: 36) + } + } + } + + private func receiptColor(_ state: String) -> Color { + switch state { + case "replied": return .green + case "processing": return .blue + case "queued", "dispatched": return .orange + case "failed", "timed_out": return .red + default: return .secondary + } + } +} diff --git a/mobile/ios/App/CollaborationDetailSheet.swift b/mobile/ios/App/CollaborationDetailSheet.swift new file mode 100644 index 000000000..805218aad --- /dev/null +++ b/mobile/ios/App/CollaborationDetailSheet.swift @@ -0,0 +1,1048 @@ +import CompanionCore +import SwiftUI + +struct CollaborationDetailSheet: View { + @Environment(\.dismiss) private var dismiss + let client: HostClient + let workspaceID: String + let item: CollabSidebarItem + let members: [CollabSpaceMember] + let allSidebarItems: [CollabSidebarItem] + let contactGroups: [CollabContactGroup] + let onOpenConversation: (ConversationListItem) -> Void + let onChanged: () async -> Void + + enum Tab: String { + case primary + case memoryAndCollection + case settings + } + + @State private var selectedTab: Tab = .primary + @State private var liveMembers: [CollabSpaceMember] = [] + @State private var leadMemberID: String = "" + @State private var showingCreateForGroup = false + + // Memory & Collection state + @State private var assetKind: AssetKind = .facts + @State private var facts: [CollabMemoryFact] = [] + @State private var topics: [CollabMemoryTopic] = [] + @State private var collectionItems: [CollabCollectionItem] = [] + @State private var newFactContent = "" + @State private var newFactScope = "thread" + @State private var newTopicSlug = "" + @State private var newTopicTitle = "" + @State private var newTopicContent = "" + @State private var newCollectionName = "" + @State private var newCollectionText = "" + @State private var newCollectionNote = "" + + // Settings / Customize state + @State private var nameDraft = "" + @State private var personaDraft = "" + @State private var agentID = "" + @State private var modeID = "" + @State private var writeAccess = "write_isolated" + @State private var isSupervisor = false + @State private var selectedColor = "" + @State private var avatarDraft: CollabBotAvatarConfig = .defaultMaster + @State private var errorMessage: String? + + enum AssetKind: String, CaseIterable, Identifiable { + case facts = "记忆" + case topics = "主题" + case collection = "收藏" + var id: String { rawValue } + } + + private var spaceID: String { item.targetSpaceId } + private var memberIdentityID: String? { item.member?.resolvedIdentityId } + + var body: some View { + NavigationStack { + VStack(spacing: 0) { + Picker("详情", selection: $selectedTab) { + Text(item.isGroup ? "成员" : "定制").tag(Tab.primary) + Text("记忆与收藏").tag(Tab.memoryAndCollection) + Text(item.isGroup ? "设置" : "会话").tag(Tab.settings) + } + .pickerStyle(.segmented) + .padding(.horizontal, 16) + .padding(.vertical, 10) + + switch selectedTab { + case .primary: + if item.isGroup { + groupMembersView + } else { + assistantCustomizeView + } + case .memoryAndCollection: + memoryAndCollectionView + case .settings: + if item.isGroup { + groupSettingsView + } else { + assistantSessionView + } + } + } + .navigationTitle(item.isGroup ? "群组详情" : "助手详情") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("完成") { dismiss() } + } + } + } + .sheet(isPresented: $showingCreateForGroup) { + CreateAssistantSheet( + client: client, + workspaceID: workspaceID, + targetSpaceID: spaceID, + onCreated: { + await loadDetails() + await onChanged() + } + ) + } + .task { + nameDraft = item.displayName + isSupervisor = item.member?.isSupervisor ?? false + selectedColor = (item.isGroup ? item.tagColor : item.member?.color) ?? "" + avatarDraft = item.member?.botAvatar ?? CollabBotAvatarConfig.derive(seed: item.displayName) + newFactScope = item.isGroup ? "thread" : "private" + liveMembers = members.filter(\.isAgent) + await loadDetails() + } + } + + // MARK: - Group Members Tab + + private var candidateAssistants: [CollabSidebarItem] { + let existingConvIDs = Set(liveMembers.compactMap(\.conversationId)) + let existingNames = Set(liveMembers.map { $0.nickname.lowercased() }) + return allSidebarItems.filter { candidate in + guard candidate.isDirect, let m = candidate.member, let convID = m.conversationId, !convID.isEmpty else { + return false + } + return !existingConvIDs.contains(convID) && !existingNames.contains(m.name.lowercased()) + } + } + + private var groupMembersView: some View { + List { + Section { + Button { + showingCreateForGroup = true + } label: { + Label("新建助手并拉入本群", systemImage: "person.badge.plus") + } + + if !candidateAssistants.isEmpty { + Menu { + ForEach(candidateAssistants) { candidate in + Button(candidate.displayName) { + addExistingAssistant(candidate) + } + } + } label: { + Label("添加已有工作区助手入群", systemImage: "plus.circle") + } + } + } + + Section("群内助手 (\(liveMembers.count))") { + if liveMembers.isEmpty { + Text("本群还没有助手成员") + .foregroundStyle(.secondary) + } else { + ForEach(liveMembers) { member in + let isLead = !leadMemberID.isEmpty + && (member.memberId == leadMemberID || member.identityMemberId == leadMemberID) + HStack(spacing: 10) { + MemberBotAvatarView( + config: member.botAvatar, + size: 34, + isLead: isLead, + isSupervisor: member.isSupervisor + ) + + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 6) { + Text(member.nickname) + .font(.system(size: 14, weight: .medium)) + if isLead { + Text("群负责人") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.blue) + .padding(.horizontal, 6) + .padding(.vertical, 1.5) + .background(Capsule().fill(Color.blue.opacity(0.14))) + } + } + } + Spacer() + Menu { + Button { + openMemberConversation(member) + } label: { + Label("查看本群会话", systemImage: "terminal") + } + Button { + setGroupLead(member) + } label: { + Label("设为群负责人", systemImage: "star") + } + Divider() + Button(role: .destructive) { + removeMemberFromGroup(member) + } label: { + Label("移出本群", systemImage: "person.badge.minus") + } + } label: { + Image(systemName: "ellipsis.circle") + .foregroundStyle(.secondary) + } + } + } + } + } + } + } + + // MARK: - Assistant Customize Tab + + private var assistantCustomizeView: some View { + Form { + Section("基本信息") { + TextField("助手名称", text: $nameDraft) + MemberBotAvatarPicker(value: $avatarDraft) + .padding(.vertical, 4) + Toggle("设为主管(置顶)", isOn: $isSupervisor) + } + + Section("会话与人设配置") { + if !agentID.isEmpty { + LabeledContent("Agent", value: agentID) + } + Picker("工作区写入策略", selection: $writeAccess) { + Text("独立工作区隔离 (write_isolated)").tag("write_isolated") + Text("串行写入主工作区 (write_serialized)").tag("write_serialized") + } + VStack(alignment: .leading, spacing: 6) { + Text("人设提示词 (Persona Prompt)") + .font(.caption) + .foregroundStyle(.secondary) + TextEditor(text: $personaDraft) + .frame(minHeight: 90) + } + } + + if let errorMessage { + Section { + Text(errorMessage).foregroundStyle(.red).font(.footnote) + } + } + + Section { + Button("保存配置") { + saveAssistantCustomization() + } + .frame(maxWidth: .infinity) + } + } + } + + // MARK: - Memory, Topics & Collection Tab + + private var memoryAndCollectionView: some View { + List { + Section { + Picker("资产类别", selection: $assetKind) { + ForEach(AssetKind.allCases) { kind in + Text(kind.rawValue).tag(kind) + } + } + .pickerStyle(.segmented) + } + .listRowBackground(Color.clear) + .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 4, trailing: 0)) + + switch assetKind { + case .facts: + Section("新增记忆") { + TextField("输入长期事实或偏好…", text: $newFactContent, axis: .vertical) + .lineLimit(1...3) + Picker("作用域", selection: $newFactScope) { + if item.isGroup { + Text("本群").tag("thread") + } else { + Text("私聊").tag("private") + } + Text("全局").tag("global") + } + Button("添加记忆") { addFact() } + .disabled(newFactContent.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + + Section("已存记忆 (\(facts.count))") { + if facts.isEmpty { + Text("暂无记忆条目").foregroundStyle(.secondary) + } else { + ForEach(facts) { fact in + HStack(alignment: .top, spacing: 8) { + Text(fact.scopeLabel) + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.blue) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Capsule().fill(Color.blue.opacity(0.12))) + Text(fact.content) + .font(.system(size: 13)) + Spacer() + } + .swipeActions { + Button(role: .destructive) { + deleteFact(fact) + } label: { + Label("删除", systemImage: "trash") + } + } + } + } + } + + case .topics: + Section("新增/更新知识主题") { + TextField("主题标识 (如 arch-notes)", text: $newTopicSlug) + .textInputAutocapitalization(.never) + TextField("标题", text: $newTopicTitle) + TextField("正文内容…", text: $newTopicContent, axis: .vertical) + .lineLimit(2...5) + Button("保存主题") { writeTopic() } + .disabled( + newTopicSlug.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + || newTopicContent.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ) + } + + Section("主题列表 (\(topics.count))") { + if topics.isEmpty { + Text("暂无主题文档").foregroundStyle(.secondary) + } else { + ForEach(topics) { topic in + VStack(alignment: .leading, spacing: 4) { + Text(topic.title) + .font(.system(size: 14, weight: .medium)) + Text(topic.topic) + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(.secondary) + if let preview = topic.preview ?? topic.content, !preview.isEmpty { + Text(preview) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .lineLimit(3) + } + } + .swipeActions { + Button(role: .destructive) { + deleteTopic(topic) + } label: { + Label("删除", systemImage: "trash") + } + } + } + } + } + + case .collection: + Section("新增文本收藏") { + TextField("标题(可选)", text: $newCollectionName) + TextField("收藏内容…", text: $newCollectionText, axis: .vertical) + .lineLimit(2...5) + TextField("备注(可选)", text: $newCollectionNote) + Button("加入收藏") { addCollectionItem() } + .disabled(newCollectionText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + + Section("空间收藏 (\(collectionItems.count))") { + if collectionItems.isEmpty { + Text("暂无收藏条目").foregroundStyle(.secondary) + } else { + ForEach(collectionItems) { entry in + VStack(alignment: .leading, spacing: 4) { + HStack { + Text(entry.name) + .font(.system(size: 14, weight: .medium)) + Spacer() + Text(entry.creatorNickname) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + } + if let text = entry.textContent, !text.isEmpty { + Text(text) + .font(.system(size: 12)) + .foregroundStyle(.primary) + .lineLimit(4) + } + if !entry.note.isEmpty { + Text("备注:\(entry.note)") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + } + } + .swipeActions { + Button(role: .destructive) { + deleteCollectionItem(entry) + } label: { + Label("删除", systemImage: "trash") + } + } + } + } + } + } + } + } + + // MARK: - Group Settings & Assistant Session Tabs + + private var groupSettingsView: some View { + Form { + Section("群组名称与标签") { + TextField("群组名称", text: $nameDraft) + Picker("群标签颜色", selection: $selectedColor) { + Text("无").tag("") + ForEach(CollabTagPalette.presets, id: \.id) { preset in + Text(preset.label).tag(preset.id) + } + } + Button("保存修改") { + saveGroupSettings() + } + } + + Section { + Button("删除此群组", role: .destructive) { + deleteGroup() + } + } + } + } + + private var assistantSessionView: some View { + Form { + Section("底层 Agent 会话") { + Text("每个助手在当前聊天中对应一条持久化的底层 Agent 会话,包含完整的工具调用轨迹、文件变更差异与权限控制。") + .font(.footnote) + .foregroundStyle(.secondary) + + Button { + openDirectAssistantSession() + } label: { + Label("打开底层对话详情", systemImage: "terminal") + } + } + } + } + + // MARK: - Data & Mutation Helpers + + private func loadDetails() async { + if item.isGroup { + if let loaded = try? await client.collabSpaceMembers(spaceID: spaceID) { + liveMembers = loaded.filter(\.isAgent) + } + if let spaces = try? await client.collabSpaces(workspaceID: workspaceID), + let match = spaces.first(where: { $0.spaceId == spaceID }) + { + leadMemberID = match.leadMemberId ?? "" + } + } else if let mid = memberIdentityID { + struct ConfigResponse: Decodable { let config: CollabMemberConfig? } + if let resp = try? await client.collaborationCall( + "member.config.get", + input: ["memberId": mid], + as: ConfigResponse.self + ), + let cfg = resp.config { + agentID = cfg.agentId ?? item.member?.agent ?? "" + modeID = cfg.modeId ?? "" + personaDraft = cfg.personaPrompt ?? "" + } + } + + if let mem = try? await client.collabMemoryView(spaceID: spaceID, memberID: memberIdentityID) { + facts = mem.facts + topics = mem.topics + } + if let col = try? await client.collabCollectionItems(spaceID: spaceID) { + collectionItems = col + } + } + + private func addExistingAssistant(_ candidate: CollabSidebarItem) { + guard let m = candidate.member, let convID = m.conversationId else { return } + Task { + try? await client.collabAddMemberToSpace( + spaceID: spaceID, + conversationID: convID, + nickname: candidate.displayName + ) + await loadDetails() + await onChanged() + } + } + + private func setGroupLead(_ member: CollabSpaceMember) { + Task { + try? await client.collaborationCommand("space.rename", input: [ + "spaceId": spaceID, + "leadMemberId": member.memberId, + ]) + leadMemberID = member.memberId + await loadDetails() + await onChanged() + } + } + + private func removeMemberFromGroup(_ member: CollabSpaceMember) { + guard let convID = member.conversationId else { return } + Task { + try? await client.collaborationCommand("space.batchDelete", input: [ + "workspaceId": workspaceID, + "operationId": UUID().uuidString.lowercased(), + "spaceIds": [], + "memberTargets": [[ + "spaceId": spaceID, + "conversationId": convID, + ]], + ]) + await loadDetails() + await onChanged() + } + } + + private func openMemberConversation(_ member: CollabSpaceMember) { + Task { + let resolved = (try? await client.collabResolveSession( + memberID: member.resolvedIdentityId, + threadID: spaceID + )) ?? member.conversationId + guard let convID = resolved, !convID.isEmpty else { return } + emitConversation(id: convID, title: member.nickname) + } + } + + private func openDirectAssistantSession() { + guard let mid = memberIdentityID else { return } + Task { + let resolved = (try? await client.collabResolveSession( + memberID: mid, + threadID: item.threadId + )) ?? item.member?.conversationId + guard let convID = resolved, !convID.isEmpty else { return } + emitConversation(id: convID, title: item.displayName) + } + } + + private func emitConversation(id: String, title: String) { + guard let data = try? JSONSerialization.data(withJSONObject: [ + "id": id, + "workspace_id": workspaceID, + "title": title, + "message_count": 0, + "updated_at": ISO8601DateFormatter().string(from: Date()), + ]), + let conv = try? JSONDecoder().decode(ConversationListItem.self, from: data) + else { return } + onOpenConversation(conv) + } + + private func saveAssistantCustomization() { + guard let mid = memberIdentityID else { return } + let trimmed = nameDraft.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + Task { + do { + try await client.collaborationCommand("member.update", input: [ + "memberId": mid, + "name": trimmed, + "avatar": avatarDraft.jsonString, + "color": avatarDraft.color, + ]) + try await client.collaborationCommand("member.config.update", input: [ + "memberId": mid, + "modeId": modeID, + "personaPrompt": personaDraft, + ]) + try await client.collaborationCommand("member.setWriteAccess", input: [ + "memberId": mid, + "writeAccess": writeAccess, + ]) + let supValue: Any = isSupervisor ? mid : NSNull() + try await client.collaborationCommand("member.setSupervisor", input: [ + "workspaceId": workspaceID, + "memberId": supValue, + ]) + errorMessage = nil + await onChanged() + dismiss() + } catch { + errorMessage = describeHostFailure(error) + } + } + } + + private func saveGroupSettings() { + let trimmed = nameDraft.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + Task { + try? await client.collaborationCommand("space.rename", input: [ + "spaceId": spaceID, + "name": trimmed, + ]) + try? await client.collaborationCommand("thread.update", input: [ + "spaceId": spaceID, + "tagColor": selectedColor, + ]) + await onChanged() + dismiss() + } + } + + private func deleteGroup() { + Task { + try? await client.collaborationCommand("space.batchDelete", input: [ + "workspaceId": workspaceID, + "operationId": UUID().uuidString.lowercased(), + "spaceIds": [spaceID], + "memberTargets": [], + ]) + await onChanged() + dismiss() + } + } + + private func addFact() { + let trimmed = newFactContent.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + newFactContent = "" + Task { + var input: [String: Any] = [ + "spaceId": spaceID, + "content": trimmed, + "scope": newFactScope, + ] + if let mid = memberIdentityID { input["memberId"] = mid } + try? await client.collaborationCommand("space.memory.add", input: input) + await loadDetails() + } + } + + private func deleteFact(_ fact: CollabMemoryFact) { + Task { + var input: [String: Any] = [ + "spaceId": spaceID, + "factId": fact.id, + ] + if let mid = memberIdentityID { input["memberId"] = mid } + try? await client.collaborationCommand("space.memory.delete", input: input) + await loadDetails() + } + } + + private func writeTopic() { + let slug = newTopicSlug.trimmingCharacters(in: .whitespacesAndNewlines) + let body = newTopicContent.trimmingCharacters(in: .whitespacesAndNewlines) + guard !slug.isEmpty, !body.isEmpty else { return } + let title = newTopicTitle.trimmingCharacters(in: .whitespacesAndNewlines) + newTopicSlug = "" + newTopicTitle = "" + newTopicContent = "" + Task { + var input: [String: Any] = [ + "spaceId": spaceID, + "topic": slug, + "content": body, + ] + if !title.isEmpty { input["title"] = title } + if let mid = memberIdentityID { input["memberId"] = mid } + try? await client.collaborationCommand("space.memory.writeTopic", input: input) + await loadDetails() + } + } + + private func deleteTopic(_ topic: CollabMemoryTopic) { + Task { + var input: [String: Any] = [ + "spaceId": spaceID, + "topic": topic.topic, + ] + if let mid = memberIdentityID { input["memberId"] = mid } + try? await client.collaborationCommand("space.memory.deleteTopic", input: input) + await loadDetails() + } + } + + private func addCollectionItem() { + let body = newCollectionText.trimmingCharacters(in: .whitespacesAndNewlines) + guard !body.isEmpty else { return } + let name = newCollectionName.trimmingCharacters(in: .whitespacesAndNewlines) + let note = newCollectionNote.trimmingCharacters(in: .whitespacesAndNewlines) + newCollectionName = "" + newCollectionText = "" + newCollectionNote = "" + Task { + var input: [String: Any] = [ + "spaceId": spaceID, + "kind": "text", + "content": body, + "creatorNickname": "User", + ] + if !name.isEmpty { input["name"] = name } + if !note.isEmpty { input["note"] = note } + try? await client.collaborationCommand("space.addCollectionItem", input: input) + await loadDetails() + } + } + + private func deleteCollectionItem(_ entry: CollabCollectionItem) { + Task { + try? await client.collaborationCommand("space.removeCollectionItem", input: [ + "spaceId": spaceID, + "itemId": entry.id, + ]) + await loadDetails() + } + } +} + +// MARK: - Create Assistant Sheet + +struct CreateAssistantSheet: View { + @Environment(\.dismiss) private var dismiss + let client: HostClient + let workspaceID: String + let targetSpaceID: String? + let onCreated: () async -> Void + + @State private var name = "" + @State private var roles: [CollabRole] = [] + @State private var agents: [CatalogAgent] = [] + @State private var selectedRoleID = "" + @State private var selectedAgentID = "" + @State private var personaPrompt = "" + @State private var avatar: CollabBotAvatarConfig = .random() + @State private var isSupervisor = false + @State private var submitting = false + @State private var errorMessage: String? + + var body: some View { + NavigationStack { + Form { + Section("助手信息") { + TextField("助手昵称(如 前端专家、架构师)", text: $name) + MemberBotAvatarPicker(value: $avatar) + .padding(.vertical, 4) + if targetSpaceID == nil { + Toggle("设为主管(置顶)", isOn: $isSupervisor) + } + } + + if !roles.isEmpty { + Section("角色模板(可选)") { + Picker("基于角色创建", selection: $selectedRoleID) { + Text("不使用模板").tag("") + ForEach(roles) { role in + Text(role.name).tag(role.id) + } + } + .onChange(of: selectedRoleID) { _, rid in + if let matched = roles.first(where: { $0.id == rid }) { + if name.isEmpty { name = matched.name } + selectedAgentID = matched.agentId + personaPrompt = matched.personaPrompt + } + } + } + } + + Section("Agent 与人设") { + if !agents.isEmpty { + Picker("Agent", selection: $selectedAgentID) { + ForEach(agents.filter(\.usable)) { agent in + AgentMenuLabel(agentID: agent.id, hostName: agent.displayName).tag(agent.id) + } + } + } + VStack(alignment: .leading, spacing: 6) { + Text("人设提示词(可选)") + .font(.caption) + .foregroundStyle(.secondary) + TextEditor(text: $personaPrompt) + .frame(minHeight: 80) + } + } + + if let errorMessage { + Section { + Text(errorMessage).foregroundStyle(.red).font(.footnote) + } + } + } + .navigationTitle(targetSpaceID == nil ? "新建助手" : "新建并拉入本群") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("取消") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button("创建") { create() } + .disabled(submitting || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + } + .task { + roles = (try? await client.collabRoles()) ?? [] + let catalog = (try? await client.agentCatalog()) ?? [] + agents = catalog + if selectedAgentID.isEmpty { + selectedAgentID = catalog.first(where: \.usable)?.id ?? "" + } + } + } + } + + private func create() { + let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, !submitting else { return } + submitting = true + Task { + do { + let created = try await client.collabCreateMember( + workspaceID: workspaceID, + name: trimmed, + agentID: selectedAgentID.isEmpty ? nil : selectedAgentID, + roleID: selectedRoleID.isEmpty ? nil : selectedRoleID, + personaPrompt: personaPrompt.trimmingCharacters(in: .whitespacesAndNewlines), + avatar: avatar, + color: avatar.color, + isSupervisor: isSupervisor + ) + if let targetSpaceID, + case .object(let dict) = created, + case .string(let convID)? = dict["conversation_id"], + !convID.isEmpty + { + try await client.collabAddMemberToSpace( + spaceID: targetSpaceID, + conversationID: convID, + nickname: trimmed + ) + } + await onCreated() + dismiss() + } catch { + errorMessage = describeHostFailure(error) + submitting = false + } + } + } +} + +// MARK: - Roles & Teams Management Sheet + +struct RolesAndTeamsSheet: View { + @Environment(\.dismiss) private var dismiss + let client: HostClient + + enum SectionKind: String, CaseIterable, Identifiable { + case roles = "角色模板" + case teams = "团队" + var id: String { rawValue } + } + + @State private var section: SectionKind = .roles + @State private var roles: [CollabRole] = [] + @State private var teams: [CollabTeam] = [] + @State private var agents: [CatalogAgent] = [] + + // New Role + @State private var roleName = "" + @State private var roleSummary = "" + @State private var roleAgentID = "" + @State private var roleTeamID = "" + @State private var rolePersona = "" + + // New Team + @State private var teamName = "" + @State private var teamSummary = "" + + var body: some View { + NavigationStack { + List { + Section { + Picker("类别", selection: $section) { + ForEach(SectionKind.allCases) { item in + Text(item.rawValue).tag(item) + } + } + .pickerStyle(.segmented) + } + .listRowBackground(Color.clear) + .listRowInsets(EdgeInsets()) + + switch section { + case .roles: + Section("新建角色模板") { + TextField("角色名称", text: $roleName) + TextField("一句话简介", text: $roleSummary) + if !agents.isEmpty { + Picker("默认 Agent", selection: $roleAgentID) { + ForEach(agents.filter(\.usable)) { agent in + AgentMenuLabel(agentID: agent.id, hostName: agent.displayName).tag(agent.id) + } + } + } + if !teams.isEmpty { + Picker("所属团队", selection: $roleTeamID) { + Text("无团队").tag("") + ForEach(teams) { team in + Text(team.name).tag(team.id) + } + } + } + TextField("人设提示词…", text: $rolePersona, axis: .vertical) + .lineLimit(2...4) + Button("创建角色") { createRole() } + .disabled(roleName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + + Section("已有角色 (\(roles.count))") { + if roles.isEmpty { + Text("暂无角色模板").foregroundStyle(.secondary) + } else { + ForEach(roles) { role in + VStack(alignment: .leading, spacing: 4) { + HStack { + Text(role.name).font(.system(size: 14, weight: .medium)) + Spacer() + AgentModelLabel(agent: role.agentId, model: AgentBrand.displayName(role.agentId), iconSize: 12) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + } + if !role.summary.isEmpty { + Text(role.summary).font(.system(size: 12)).foregroundStyle(.secondary) + } + } + .swipeActions { + Button(role: .destructive) { + deleteRole(role) + } label: { + Label("删除", systemImage: "trash") + } + } + } + } + } + + case .teams: + Section("新建团队") { + TextField("团队名称", text: $teamName) + TextField("团队简介(可选)", text: $teamSummary) + Button("创建团队") { createTeam() } + .disabled(teamName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + + Section("已有团队 (\(teams.count))") { + if teams.isEmpty { + Text("暂无团队").foregroundStyle(.secondary) + } else { + ForEach(teams) { team in + VStack(alignment: .leading, spacing: 2) { + Text(team.name).font(.system(size: 14, weight: .medium)) + if let sum = team.summary, !sum.isEmpty { + Text(sum).font(.system(size: 12)).foregroundStyle(.secondary) + } + } + .swipeActions { + Button(role: .destructive) { + deleteTeam(team) + } label: { + Label("删除", systemImage: "trash") + } + } + } + } + } + } + } + .navigationTitle("角色与团队") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("完成") { dismiss() } + } + } + .task { await reload() } + } + } + + private func reload() async { + roles = (try? await client.collabRoles()) ?? [] + teams = (try? await client.collabTeams()) ?? [] + let catalog = (try? await client.agentCatalog()) ?? [] + agents = catalog + if roleAgentID.isEmpty { + roleAgentID = catalog.first(where: \.usable)?.id ?? "codex" + } + } + + private func createRole() { + let name = roleName.trimmingCharacters(in: .whitespacesAndNewlines) + guard !name.isEmpty else { return } + Task { + var input: [String: Any] = [ + "name": name, + "summary": roleSummary.trimmingCharacters(in: .whitespacesAndNewlines), + "personaPrompt": rolePersona.trimmingCharacters(in: .whitespacesAndNewlines), + "agentId": roleAgentID.isEmpty ? "codex" : roleAgentID, + ] + if !roleTeamID.isEmpty { input["teamId"] = roleTeamID } + try? await client.collaborationCommand("role.create", input: input) + roleName = "" + roleSummary = "" + rolePersona = "" + await reload() + } + } + + private func deleteRole(_ role: CollabRole) { + Task { + try? await client.collaborationCommand("role.delete", input: ["roleId": role.id]) + await reload() + } + } + + private func createTeam() { + let name = teamName.trimmingCharacters(in: .whitespacesAndNewlines) + guard !name.isEmpty else { return } + Task { + try? await client.collaborationCommand("team.create", input: [ + "name": name, + "summary": teamSummary.trimmingCharacters(in: .whitespacesAndNewlines), + ]) + teamName = "" + teamSummary = "" + await reload() + } + } + + private func deleteTeam(_ team: CollabTeam) { + Task { + try? await client.collaborationCommand("team.delete", input: ["teamId": team.id]) + await reload() + } + } +} diff --git a/mobile/ios/App/CollaborationSpaceView.swift b/mobile/ios/App/CollaborationSpaceView.swift new file mode 100644 index 000000000..ee7c90274 --- /dev/null +++ b/mobile/ios/App/CollaborationSpaceView.swift @@ -0,0 +1,723 @@ +import CompanionCore +import SwiftUI + +struct CollaborationSpaceView: View { + let client: HostClient + + @State private var projects: [ProjectSummary] = [] + @State private var selectedProjectID: String = "" + @State private var sidebarItems: [CollabSidebarItem] = [] + @State private var contactGroups: [CollabContactGroup] = [] + @State private var spaces: [CollabSpaceSummary] = [] + @State private var loading = true + @State private var errorMessage: String? + @State private var searchQuery = "" + @State private var filterKind: FilterKind = .all + @State private var collapsedGroupIDs: Set = [] + @State private var path = NavigationPath() + + // Modals & Alerts + @State private var showingCreateAssistant = false + @State private var showingCreateGroup = false + @State private var showingCreateContactGroup = false + @State private var showingRolesAndTeams = false + @State private var newGroupName = "" + @State private var newContactGroupName = "" + @State private var renamingGroup: CollabContactGroup? + @State private var renameGroupDraft = "" + + enum FilterKind: String, CaseIterable, Identifiable { + case all = "全部" + case group = "群组" + case assistant = "助手" + var id: String { rawValue } + } + + private var orderedProjects: [ProjectGroup] { + ProjectGroup.make(conversations: [], projects: projects) + } + + private var activeProject: ProjectGroup? { + orderedProjects.first { $0.id == selectedProjectID } ?? orderedProjects.first + } + + private var activeWorkspaceID: String? { + activeProject?.workspaceIds.first + } + + var body: some View { + NavigationStack(path: $path) { + content + .navigationTitle("协作空间") + .toolbar { + ToolbarItem(placement: .topBarLeading) { + if !orderedProjects.isEmpty { + Menu { + ForEach(orderedProjects) { project in + Button { + selectedProjectID = project.id + Task { await reload() } + } label: { + HStack { + Text(String(repeating: " ", count: project.depth) + project.name) + if project.id == activeProject?.id { + Image(systemName: "checkmark") + } + } + } + } + } label: { + HStack(spacing: 4) { + Image(systemName: activeProject?.isGit == true ? "arrow.triangle.branch" : "folder") + .font(.system(size: 12, weight: .medium)) + Text(activeProject?.name ?? "选择项目") + .font(.system(size: 13, weight: .medium)) + Image(systemName: "chevron.down") + .font(.system(size: 10, weight: .semibold)) + } + } + } + } + + ToolbarItem(placement: .primaryAction) { + Menu { + Button { + showingCreateAssistant = true + } label: { + Label("新建助手", systemImage: "person.badge.plus") + } + Button { + newGroupName = "" + showingCreateGroup = true + } label: { + Label("新建群组", systemImage: "person.3") + } + Button { + newContactGroupName = "" + showingCreateContactGroup = true + } label: { + Label("新建联系人分组", systemImage: "folder.badge.plus") + } + Divider() + Button { + showingRolesAndTeams = true + } label: { + Label("角色与团队管理", systemImage: "person.text.rectangle") + } + } label: { + Image(systemName: "plus") + } + .accessibilityLabel("新建") + .disabled(activeWorkspaceID == nil) + } + } + .navigationDestination(for: CollabSidebarItem.self) { item in + if let workspaceID = activeWorkspaceID { + CollaborationChatView( + client: client, + workspaceID: workspaceID, + item: item, + allSidebarItems: sidebarItems, + contactGroups: contactGroups, + onChanged: { await reload() } + ) + } + } + .navigationDestination(for: ConversationListItem.self) { conv in + ConversationDetailView(client: client, conversation: conv) + } + } + .sheet(isPresented: $showingCreateAssistant) { + if let workspaceID = activeWorkspaceID { + CreateAssistantSheet( + client: client, + workspaceID: workspaceID, + targetSpaceID: nil, + onCreated: { await reload() } + ) + } + } + .sheet(isPresented: $showingRolesAndTeams) { + RolesAndTeamsSheet(client: client) + } + .alert("新建群组", isPresented: $showingCreateGroup) { + TextField("群组名称", text: $newGroupName) + Button("取消", role: .cancel) {} + Button("创建") { createGroup() } + } + .alert("新建联系人分组", isPresented: $showingCreateContactGroup) { + TextField("分组名称", text: $newContactGroupName) + Button("取消", role: .cancel) {} + Button("创建") { createContactGroup() } + } + .alert( + "重命名分组", + isPresented: Binding( + get: { renamingGroup != nil }, + set: { if !$0 { renamingGroup = nil } } + ) + ) { + TextField("分组名称", text: $renameGroupDraft) + Button("取消", role: .cancel) { renamingGroup = nil } + Button("保存") { + if let group = renamingGroup { + renameContactGroup(group, to: renameGroupDraft) + } + renamingGroup = nil + } + } + .task { + while !Task.isCancelled { + await reload() + try? await Task.sleep(for: .seconds(errorMessage == nil ? 8 : 4)) + } + } + } + + // MARK: - Filtering & Grouping + + private var filteredItems: [CollabSidebarItem] { + sidebarItems.filter { item in + switch filterKind { + case .all: return true + case .group: return item.isGroup + case .assistant: return item.isDirect + } + } + } + + private var supervisorItem: CollabSidebarItem? { + let directs = filteredItems.filter(\.isDirect) + if let explicit = directs.first(where: { $0.member?.isSupervisor == true }) { + return explicit + } + return nil + } + + private var nonSupervisorItems: [CollabSidebarItem] { + guard let sup = supervisorItem else { return filteredItems } + 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: { path.append(item) } + ) + } + } + + @ViewBuilder + private var content: some View { + if loading && sidebarItems.isEmpty && errorMessage == nil { + ProgressView() + } else if let errorMessage, sidebarItems.isEmpty { + LoadFailureView(message: errorMessage) { Task { await reload() } } + } else { + List { + Section { + VStack(spacing: 10) { + SearchListCard( + query: $searchQuery, + placeholder: "搜索群组或助手…", + results: searchResults + ) + Picker("筛选", selection: $filterKind) { + ForEach(FilterKind.allCases) { kind in + Text(kind.rawValue).tag(kind) + } + } + .pickerStyle(.segmented) + } + } + .listRowInsets(EdgeInsets(top: 4, leading: 0, bottom: 8, trailing: 0)) + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + + if let supervisor = supervisorItem { + Section("主管") { + NavigationLink(value: supervisor) { + CollabContactRow(item: supervisor, isSupervisorSlot: true) + } + .modifier(rowActions(for: supervisor)) + } + } + + if nonSupervisorItems.isEmpty && supervisorItem == nil { + Section { + ContentUnavailableView { + Label("还没有群组或助手", systemImage: "person.2") + } description: { + Text("点击右上角 + 创建助手或群组,开启多智能体协作") + } + .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: item) { + CollabContactRow(item: item, isSupervisorSlot: false) + } + .modifier(rowActions(for: item)) + } + } + } header: { + HStack { + Button { + withAnimation { + if isCollapsed { + collapsedGroupIDs.remove(group.groupId) + } else { + collapsedGroupIDs.insert(group.groupId) + } + } + } 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 { + Button { + renameGroupDraft = group.name + renamingGroup = group + } label: { + Label("重命名分组", systemImage: "pencil") + } + Button(role: .destructive) { + deleteContactGroup(group) + } label: { + Label("删除分组", systemImage: "trash") + } + } label: { + Image(systemName: "ellipsis") + .font(.system(size: 12)) + .foregroundStyle(.secondary) + } + } + } + } + + let knownGroupIDs = Set(contactGroups.map(\.groupId)) + let ungrouped = nonSupervisorItems.filter { item in + guard let gid = item.groupId, !gid.isEmpty else { return true } + return !knownGroupIDs.contains(gid) + } + if !ungrouped.isEmpty { + Section("未分组 (\(ungrouped.count))") { + ForEach(ungrouped) { item in + NavigationLink(value: item) { + CollabContactRow(item: item, isSupervisorSlot: false) + } + .modifier(rowActions(for: item)) + } + } + } + } else { + let groupItems = nonSupervisorItems.filter(\.isGroup) + let directItems = nonSupervisorItems.filter(\.isDirect) + + if !groupItems.isEmpty { + Section("群组 (\(groupItems.count))") { + ForEach(groupItems) { item in + NavigationLink(value: item) { + CollabContactRow(item: item, isSupervisorSlot: false) + } + .modifier(rowActions(for: item)) + } + } + } + + if !directItems.isEmpty { + Section("助手 (\(directItems.count))") { + ForEach(directItems) { item in + NavigationLink(value: item) { + CollabContactRow(item: item, isSupervisorSlot: false) + } + .modifier(rowActions(for: item)) + } + } + } + } + } + .listSectionSpacing(10) + .scrollDismissesKeyboard(.immediately) + .refreshable { await reload() } + } + } + + private func rowActions(for item: CollabSidebarItem) -> CollabRowActionsModifier { + CollabRowActionsModifier( + item: item, + contactGroups: contactGroups, + onToggleRead: { toggleRead(item) }, + onMoveToGroup: { setThreadGroup(item, groupID: $0) }, + onSetTagColor: { setTagColor(item, color: $0) }, + onToggleSupervisor: { toggleSupervisor(item) }, + onDelete: { deleteItem(item) } + ) + } + + // MARK: - Actions & Loading + + private func reload() async { + do { + let loadedProjects = try await client.projects() + projects = loadedProjects + if selectedProjectID.isEmpty || !loadedProjects.contains(where: { $0.id == selectedProjectID }) { + selectedProjectID = ProjectGroup.make(conversations: [], projects: loadedProjects).first?.id ?? "" + } + guard let workspaceID = activeWorkspaceID else { + loading = false + return + } + async let sidebarTask = client.collabSidebar(workspaceID: workspaceID) + async let groupsTask = client.collabContactGroups(workspaceID: workspaceID) + async let spacesTask = client.collabSpaces(workspaceID: workspaceID) + sidebarItems = try await sidebarTask + contactGroups = (try? await groupsTask) ?? [] + spaces = (try? await spacesTask) ?? [] + errorMessage = nil + } catch { + errorMessage = describeHostFailure(error) + } + loading = false + } + + private func createGroup() { + let trimmed = newGroupName.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, let workspaceID = activeWorkspaceID else { return } + Task { + _ = try? await client.collabCreateSpace(workspaceID: workspaceID, name: trimmed) + await reload() + } + } + + private func createContactGroup() { + let trimmed = newContactGroupName.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, let workspaceID = activeWorkspaceID else { return } + Task { + try? await client.collaborationCommand("contactGroup.create", input: [ + "workspaceId": workspaceID, + "name": trimmed, + ]) + await reload() + } + } + + private func renameContactGroup(_ group: CollabContactGroup, to name: String) { + let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + Task { + try? await client.collaborationCommand("contactGroup.rename", input: [ + "groupId": group.groupId, + "name": trimmed, + ]) + await reload() + } + } + + private func deleteContactGroup(_ group: CollabContactGroup) { + Task { + try? await client.collaborationCommand("contactGroup.delete", input: [ + "groupId": group.groupId, + ]) + await reload() + } + } + + private func toggleRead(_ item: CollabSidebarItem) { + Task { + if item.unreadCount > 0 { + try? await client.collabMarkRead(threadID: item.threadId, seq: item.lastMessage?.seq) + } else { + try? await client.collabMarkUnread(threadID: item.threadId) + } + await reload() + } + } + + private func setThreadGroup(_ item: CollabSidebarItem, groupID: String?) { + Task { + var input: [String: Any] = ["threadId": item.threadId] + input["groupId"] = groupID ?? NSNull() + try? await client.collaborationCommand("thread.setGroup", input: input) + await reload() + } + } + + private func setTagColor(_ item: CollabSidebarItem, color: String) { + Task { + var input: [String: Any] = item.isDirect + ? ["threadId": item.threadId] + : ["spaceId": item.targetSpaceId] + input["tagColor"] = color + try? await client.collaborationCommand("thread.update", input: input) + await reload() + } + } + + private func toggleSupervisor(_ item: CollabSidebarItem) { + guard let workspaceID = activeWorkspaceID, let member = item.member else { return } + let nextMemberID: Any = member.isSupervisor ? NSNull() : member.resolvedIdentityId + Task { + try? await client.collaborationCommand("member.setSupervisor", input: [ + "workspaceId": workspaceID, + "memberId": nextMemberID, + ]) + await reload() + } + } + + private func deleteItem(_ item: CollabSidebarItem) { + guard let workspaceID = activeWorkspaceID else { return } + withAnimation { + sidebarItems.removeAll { $0.id == item.id } + } + Task { + var input: [String: Any] = [ + "workspaceId": workspaceID, + "operationId": UUID().uuidString.lowercased(), + ] + if item.isGroup { + input["spaceIds"] = [item.targetSpaceId] + input["memberTargets"] = [] + } else if let convID = item.member?.conversationId { + input["spaceIds"] = [] + input["memberTargets"] = [[ + "spaceId": "unassigned:\(workspaceID)", + "conversationId": convID, + ]] + } + try? await client.collaborationCommand("space.batchDelete", input: input) + await reload() + } + } +} + +// MARK: - Contact Row & Swipe/Menu Modifier + +private struct CollabRowActionsModifier: ViewModifier { + let item: CollabSidebarItem + let contactGroups: [CollabContactGroup] + let onToggleRead: () -> Void + let onMoveToGroup: (String?) -> Void + let onSetTagColor: (String) -> Void + let onToggleSupervisor: () -> Void + let onDelete: () -> Void + + func body(content: Content) -> some View { + content + .swipeActions(edge: .trailing, allowsFullSwipe: true) { + Button(role: .destructive, action: onDelete) { + Label("删除", systemImage: "trash") + } + Button(action: onToggleRead) { + Label( + item.unreadCount > 0 ? "标为已读" : "标为未读", + systemImage: item.unreadCount > 0 ? "envelope.open" : "envelope.badge" + ) + } + .tint(.indigo) + } + .contextMenu { + Button(action: onToggleRead) { + Label( + item.unreadCount > 0 ? "标为已读" : "标为未读", + systemImage: item.unreadCount > 0 ? "envelope.open" : "envelope.badge" + ) + } + + if item.isDirect, let member = item.member { + Button(action: onToggleSupervisor) { + Label( + member.isSupervisor ? "取消主管身份" : "设为主管", + systemImage: member.isSupervisor ? "crown" : "crown.fill" + ) + } + } + + if item.isGroup { + Menu("群标签颜色") { + ForEach(CollabTagPalette.presets, id: \.id) { preset in + Button(preset.label) { onSetTagColor(preset.id) } + } + Divider() + Button("清除颜色") { onSetTagColor("") } + } + } + + if !contactGroups.isEmpty { + Menu("移至分组") { + ForEach(contactGroups) { group in + Button { + onMoveToGroup(group.groupId) + } label: { + HStack { + Text(group.name) + if item.groupId == group.groupId { + Image(systemName: "checkmark") + } + } + } + } + Divider() + Button("未分组") { onMoveToGroup(nil) } + } + } + + Divider() + Button(role: .destructive, action: onDelete) { + Label(item.isGroup ? "删除群组" : "删除助手", systemImage: "trash") + } + } + } +} + +struct CollabContactRow: View { + let item: CollabSidebarItem + let isSupervisorSlot: Bool + + var body: some View { + HStack(spacing: 12) { + CollabAvatarView(item: item, size: 40) + + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 6) { + Text(item.displayName) + .font(.system(size: 15, weight: .medium)) + .foregroundStyle(.primary) + .lineLimit(1) + + if isSupervisorSlot || item.member?.isSupervisor == true { + Text("主管") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.orange) + .padding(.horizontal, 6) + .padding(.vertical, 1.5) + .background(Capsule().fill(Color.orange.opacity(0.14))) + } else if item.isGroup, item.memberCount > 0 { + Text("(\(item.memberCount))") + .font(.system(size: 12)) + .foregroundStyle(.secondary) + } else if let agent = item.member?.agent, !agent.isEmpty { + HStack(spacing: 3) { + AgentIconView(agent: agent, size: 11) + Text(AgentBrand.displayName(agent)) + } + .font(.system(size: 10, weight: .medium)) + .foregroundStyle(.secondary) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background(Capsule().fill(Color.primary.opacity(0.06))) + } + + Spacer(minLength: 4) + + if let date = item.activityDate { + Text(date, format: .relative(presentation: .named)) + .font(.system(size: 11)) + .foregroundStyle(.tertiary) + } + } + + HStack(spacing: 8) { + Text(item.lastMessage?.preview ?? (item.isGroup ? "点击进入群聊" : "点击发起私聊")) + .font(.system(size: 13)) + .foregroundStyle(.secondary) + .lineLimit(1) + + Spacer(minLength: 4) + + if item.unreadCount > 0 { + Text("\(min(item.unreadCount, 99))") + .font(.system(size: 11, weight: .bold)) + .foregroundStyle(.white) + .padding(.horizontal, 6) + .frame(minWidth: 18, minHeight: 18) + .background(Capsule().fill(Color.blue)) + } + } + } + } + .padding(.vertical, 3) + } +} + +struct CollabAvatarView: View { + let item: CollabSidebarItem + let size: CGFloat + + var body: some View { + if item.isGroup { + let memberAvatars = item.membersPreview.map(\.botAvatar) + CollabGroupAvatarView( + avatars: memberAvatars.isEmpty + ? [CollabBotAvatarConfig.derive(seed: item.displayName)] + : memberAvatars, + tagColorHex: item.tagColor, + size: size + ) + } else { + let avatar = item.member?.botAvatar + ?? CollabBotAvatarConfig.derive(seed: item.displayName) + MemberBotAvatarView( + config: avatar, + size: size, + isSupervisor: item.member?.isSupervisor == true + ) + } + } +} + +enum CollabTagPalette { + static let presets: [(id: String, label: String, color: Color)] = [ + ("amber", "琥珀", .orange), + ("violet", "紫罗兰", .purple), + ("rose", "玫瑰", .pink), + ("cyan", "青色", .cyan), + ] + + static func color(for raw: String?) -> Color? { + guard let raw = raw?.trimmingCharacters(in: .whitespacesAndNewlines), !raw.isEmpty else { return nil } + if let preset = presets.first(where: { $0.id == raw }) { + return preset.color + } + if raw.hasPrefix("#") { + let hex = String(raw.dropFirst()) + if hex.count == 6, let val = Int(hex, radix: 16) { + return Color( + red: Double((val >> 16) & 0xFF) / 255.0, + green: Double((val >> 8) & 0xFF) / 255.0, + blue: Double(val & 0xFF) / 255.0 + ) + } + } + return nil + } + + static func hashColor(_ name: String) -> Color { + let palette: [Color] = [.blue, .indigo, .teal, .orange, .pink, .mint, .purple] + let hash = abs(name.unicodeScalars.reduce(0) { ($0 &* 31) &+ Int($1.value) }) + return palette[hash % palette.count] + } +} diff --git a/mobile/ios/App/CompanionAttentionCenter.swift b/mobile/ios/App/CompanionAttentionCenter.swift new file mode 100644 index 000000000..9066deba7 --- /dev/null +++ b/mobile/ios/App/CompanionAttentionCenter.swift @@ -0,0 +1,834 @@ +import AudioToolbox +import CompanionCore +import Foundation +import Observation +import SwiftUI +import UIKit +import UserNotifications + +enum AttentionToastKind: Equatable { + case permission(PermissionPrompt) + case question(PendingQuestion) + case completed + case failed(String) + + var accentColor: Color { + switch self { + case .permission, .question, .failed: + return Color(red: 0.96, green: 0.20, blue: 0.20) + case .completed: + return Color(red: 0.35, green: 0.72, blue: 0.06) + } + } + + var badgeIcon: String { + switch self { + case .permission, .question, .failed: + return "exclamationmark" + case .completed: + return "checkmark" + } + } + + var durationSeconds: TimeInterval { + switch self { + case .permission, .question: + return 30 + case .completed, .failed: + return 14 + } + } +} + +struct CompanionAttentionToast: Identifiable, Equatable { + let id: String + let conversation: ConversationListItem + let projectName: String + let title: String + let subtitle: String + let kind: AttentionToastKind + let createdAt: Date +} + +@MainActor +@Observable +final class CompanionAttentionCenter { + var activeToast: CompanionAttentionToast? + var pendingNavigationConversation: ConversationListItem? + var actionBusy = false + var actionError: String? + + @ObservationIgnored private var eventsByConversation: [String: [RemoteEvent]] = [:] + @ObservationIgnored private var lastSequenceByConversation: [String: Int64] = [:] + @ObservationIgnored private var sessionsByConversation: [String: SessionState] = [:] + @ObservationIgnored private var wasRunningByConversation: [String: Bool] = [:] + @ObservationIgnored private var initializedConversations: Set = [] + @ObservationIgnored private var handledEventIDs: Set = [] + @ObservationIgnored private var didRequestNotificationPermission = false + + func requestNotificationPermissionIfNeeded() { + guard !didRequestNotificationPermission else { return } + didRequestNotificationPermission = true + UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { _, _ in } + } + + func poll(client: HostClient) async { + requestNotificationPermissionIfNeeded() + + async let conversationsTask = try? client.call( + "conversation_list_recent", + args: ["sinceDays": 30, "limit": 20], + as: [ConversationListItem].self + ) + async let projectsTask = try? client.projects() + let (conversationsOpt, projectsOpt) = await (conversationsTask, projectsTask) + guard let conversations = conversationsOpt else { return } + let projects = projectsOpt ?? [] + let groups = ProjectGroup.make(conversations: conversations, projects: projects) + + func resolveProjectName(for conv: ConversationListItem) -> String { + if let group = groups.first(where: { g in g.conversations.contains(where: { $0.id == conv.id }) }), + group.id != "other", + !group.name.isEmpty { + return group.name + } + return "VibeX" + } + + let candidates = Array(conversations.prefix(6)) + for conv in candidates { + let isFirstSnapshot = !initializedConversations.contains(conv.id) + let previouslyRunning = wasRunningByConversation[conv.id] ?? false + let seq = lastSequenceByConversation[conv.id] ?? 0 + + guard let cache = try? await client.offlineConversation(id: conv.id, afterSequence: seq) else { + continue + } + + let fresh = cache.events ?? [] + var allEvents = eventsByConversation[conv.id] ?? [] + if !fresh.isEmpty { + allEvents.append(contentsOf: fresh) + eventsByConversation[conv.id] = allEvents + } + let confirmedSeq = max(seq, cache.confirmed_through) + lastSequenceByConversation[conv.id] = confirmedSeq + + let state = SessionStateBuilder.build(from: allEvents) + sessionsByConversation[conv.id] = state + initializedConversations.insert(conv.id) + wasRunningByConversation[conv.id] = state.isTurnRunning + + let project = resolveProjectName(for: conv) + let sessionTitle = (conv.title?.trimmingCharacters(in: .whitespacesAndNewlines)).flatMap { + $0.isEmpty ? nil : $0 + } ?? "未命名对话" + + // Auto-clear active toast if its permission/question was resolved on desktop or detail view + if let current = activeToast, current.conversation.id == conv.id { + switch current.kind { + case let .permission(prompt): + if !state.pendingPermissions.contains(where: { $0.id == prompt.id }) { + withAnimation(.spring(response: 0.3, dampingFraction: 0.84)) { + activeToast = nil + } + } + case let .question(question): + if !state.pendingQuestions.contains(where: { $0.id == question.id }) { + withAnimation(.spring(response: 0.3, dampingFraction: 0.84)) { + activeToast = nil + } + } + case .completed, .failed: + break + } + } + + // 1. Check pending permission prompts + if let prompt = state.pendingPermissions.first { + let eventKey = "perm:\(conv.id):\(prompt.id)" + if !handledEventIDs.contains(eventKey) { + handledEventIDs.insert(eventKey) + presentToast( + CompanionAttentionToast( + id: eventKey, + conversation: conv, + projectName: project, + title: "\(project):需要权限批准", + subtitle: prompt.title, + kind: .permission(prompt), + createdAt: Date() + ) + ) + } + } + + // 2. Check pending question / plan implementation confirmation + if let question = state.pendingQuestions.first { + let eventKey = "question:\(conv.id):\(question.id)" + if !handledEventIDs.contains(eventKey) { + handledEventIDs.insert(eventKey) + let subtitle = Self.questionSummary(question, fallback: sessionTitle) + presentToast( + CompanionAttentionToast( + id: eventKey, + conversation: conv, + projectName: project, + title: "\(project):需要权限批准", + subtitle: subtitle, + kind: .question(question), + createdAt: Date() + ) + ) + } + } + + // 3. Check turn completion or failure (after initial snapshot) + if !isFirstSnapshot { + let terminalEvents = fresh.filter { + $0.kind == "turn_completed" || $0.kind == "turn_failed" + } + if let lastTerminal = terminalEvents.last { + let eventKey = "terminal:\(conv.id):\(lastTerminal.sequence)" + if !handledEventIDs.contains(eventKey) { + handledEventIDs.insert(eventKey) + if lastTerminal.kind == "turn_failed" { + let err = Self.extractFailureMessage(from: lastTerminal.payload) + presentToast( + CompanionAttentionToast( + id: eventKey, + conversation: conv, + projectName: project, + title: "\(project):会话执行出错", + subtitle: err, + kind: .failed(err), + createdAt: Date() + ) + ) + } else { + presentToast( + CompanionAttentionToast( + id: eventKey, + conversation: conv, + projectName: project, + title: "\(project):会话已完成", + subtitle: "\(sessionTitle) · \(project)", + kind: .completed, + createdAt: Date() + ) + ) + } + } + } else if previouslyRunning && !state.isTurnRunning { + let eventKey = "done:\(conv.id):\(confirmedSeq)" + if !handledEventIDs.contains(eventKey) { + handledEventIDs.insert(eventKey) + presentToast( + CompanionAttentionToast( + id: eventKey, + conversation: conv, + projectName: project, + title: "\(project):会话已完成", + subtitle: "\(sessionTitle) · \(project)", + kind: .completed, + createdAt: Date() + ) + ) + } + } + } + } + } + + private static func extractFailureMessage(from payload: JSONValue) -> String { + if case let .object(dict) = payload { + if case let .string(err)? = dict["error"], !err.isEmpty { return err } + if case let .string(msg)? = dict["message"], !msg.isEmpty { return msg } + if case let .object(data)? = dict["data"] { + if case let .string(err)? = data["error"], !err.isEmpty { return err } + if case let .string(msg)? = data["message"], !msg.isEmpty { return msg } + } + } + return "任务执行异常中断" + } + + private static func questionSummary(_ request: PendingQuestion, fallback: String) -> String { + let forms = QuestionForm.questions(for: request) + if let first = forms.first?.text.trimmingCharacters(in: .whitespacesAndNewlines), !first.isEmpty { + return first + } + let prompt = request.prompt.trimmingCharacters(in: .whitespacesAndNewlines) + return prompt.isEmpty ? fallback : prompt + } + + func presentToast(_ toast: CompanionAttentionToast) { + actionError = nil + withAnimation(.spring(response: 0.34, dampingFraction: 0.82)) { + activeToast = toast + } + triggerFeedback(for: toast.kind) + scheduleSystemNotification(for: toast) + } + + func dismiss() { + actionError = nil + withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { + activeToast = nil + } + } + + func openConversation(_ conversation: ConversationListItem) { + dismiss() + pendingNavigationConversation = conversation + } + + func respondPermission( + client: HostClient, + conversationID: String, + prompt: PermissionPrompt, + option: PermissionOption? + ) async { + actionBusy = true + actionError = nil + defer { actionBusy = false } + do { + try await client.respondPermission( + conversationID: conversationID, + permissionID: prompt.id, + optionID: option?.id + ) + wasRunningByConversation[conversationID] = true + UINotificationFeedbackGenerator().notificationOccurred(.success) + dismiss() + } catch { + actionError = describeHostFailure(error) + } + } + + func respondQuestion( + client: HostClient, + conversationID: String, + question: PendingQuestion, + choice: QuestionChoice?, + fallbackText: String? = nil + ) async { + actionBusy = true + actionError = nil + defer { actionBusy = false } + do { + let payload: JSONValue? + if let choice { + let forms = QuestionForm.questions(for: question) + var answers: [String: QuestionAnswer] = [:] + if let first = forms.first { + answers[first.id] = QuestionAnswer(selected: [choice.value], customText: "") + } + payload = QuestionForm.content(for: question, questions: forms, answers: answers) + } else if let fallbackText { + let forms = QuestionForm.questions(for: question) + var answers: [String: QuestionAnswer] = [:] + if let first = forms.first { + answers[first.id] = QuestionAnswer(selected: [], customText: fallbackText) + } + payload = QuestionForm.content(for: question, questions: forms, answers: answers) + } else { + payload = nil + } + try await client.respondQuestion( + conversationID: conversationID, + questionID: question.id, + content: payload + ) + wasRunningByConversation[conversationID] = true + UINotificationFeedbackGenerator().notificationOccurred(.success) + dismiss() + } catch { + actionError = describeHostFailure(error) + } + } + + func sendQuickReply( + client: HostClient, + toast: CompanionAttentionToast, + text: String + ) async -> Bool { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return false } + actionBusy = true + actionError = nil + defer { actionBusy = false } + do { + let conv = toast.conversation + if case let .question(question) = toast.kind { + let forms = QuestionForm.questions(for: question) + var answers: [String: QuestionAnswer] = [:] + if let first = forms.first { + answers[first.id] = QuestionAnswer(selected: [], customText: trimmed) + } + let payload = QuestionForm.content(for: question, questions: forms, answers: answers) + try await client.respondQuestion( + conversationID: conv.id, + questionID: question.id, + content: payload + ) + } else { + if case let .permission(prompt) = toast.kind { + let allowOption = prompt.options.first { $0.kind.hasPrefix("allow") } ?? prompt.options.first + try? await client.respondPermission( + conversationID: conv.id, + permissionID: prompt.id, + optionID: allowOption?.id + ) + } + guard let agentID = conv.agent_id else { + actionError = "此对话未绑定 Agent" + return false + } + try await client.sendMessage( + conversationID: conv.id, + workspaceID: conv.workspace_id, + agentID: agentID, + text: trimmed + ) + } + wasRunningByConversation[conv.id] = true + UINotificationFeedbackGenerator().notificationOccurred(.success) + dismiss() + return true + } catch { + actionError = describeHostFailure(error) + return false + } + } + + private func triggerFeedback(for kind: AttentionToastKind) { + let generator = UINotificationFeedbackGenerator() + switch kind { + case .permission, .question: + generator.notificationOccurred(.warning) + AudioServicesPlaySystemSound(1007) + case .completed: + generator.notificationOccurred(.success) + AudioServicesPlaySystemSound(1001) + case .failed: + generator.notificationOccurred(.error) + AudioServicesPlaySystemSound(1005) + } + } + + private func scheduleSystemNotification(for toast: CompanionAttentionToast) { + let content = UNMutableNotificationContent() + content.title = toast.title + content.body = toast.subtitle + content.sound = .default + content.userInfo = ["conversationId": toast.conversation.id] + + let request = UNNotificationRequest( + identifier: "vibex.attention.\(toast.id)", + content: content, + trigger: nil + ) + UNUserNotificationCenter.current().add(request) + } +} + +struct CompanionToastOverlay: View { + let client: HostClient + @Bindable var center: CompanionAttentionCenter + let onOpenConversation: (ConversationListItem) -> Void + + @State private var isReplying = false + @State private var replyText = "" + @State private var remainingFraction: CGFloat = 1.0 + @FocusState private var replyFocused: Bool + + var body: some View { + if let toast = center.activeToast { + VStack(spacing: 0) { + toastCard(toast) + .padding(.horizontal, 12) + .padding(.top, 6) + .transition(.move(edge: .top).combined(with: .opacity)) + Spacer(minLength: 0) + } + .onChange(of: toast.id) { _, _ in + isReplying = false + replyText = "" + remainingFraction = 1.0 + } + .task(id: "\(toast.id)-\(isReplying)") { + guard !isReplying else { return } + let total = toast.kind.durationSeconds + let interval = 0.1 + let steps = max(1, Int(total / interval)) + for step in 0...steps { + if Task.isCancelled || isReplying { return } + remainingFraction = max(0, 1.0 - CGFloat(step) / CGFloat(steps)) + try? await Task.sleep(for: .milliseconds(100)) + } + if !Task.isCancelled && !isReplying && center.activeToast?.id == toast.id { + center.dismiss() + } + } + } + } + + @ViewBuilder + private func toastCard(_ toast: CompanionAttentionToast) -> some View { + VStack(alignment: .leading, spacing: 11) { + // Header row matching DesktopToastWindow.tsx + HStack(alignment: .top, spacing: 12) { + ZStack(alignment: .bottomTrailing) { + Circle() + .fill(Color(.tertiarySystemFill)) + .frame(width: 40, height: 40) + .overlay { + Image("vibex_logo_lite") + .resizable() + .interpolation(.high) + .scaledToFit() + .frame(width: 24, height: 24) + } + + Circle() + .fill(toast.kind.accentColor) + .frame(width: 17, height: 17) + .overlay { + Image(systemName: toast.kind.badgeIcon) + .font(.system(size: 9, weight: .black)) + .foregroundStyle(.white) + } + .overlay { + Circle().stroke(Color(.secondarySystemGroupedBackground), lineWidth: 2) + } + .offset(x: 2, y: 2) + } + + VStack(alignment: .leading, spacing: 3) { + Text(toast.title) + .font(.system(size: 14.5, weight: .semibold)) + .foregroundStyle(.primary) + .lineLimit(1) + + Text(toast.subtitle) + .font(.system(size: 12.5)) + .foregroundStyle(.secondary) + .lineLimit(2) + } + .frame(maxWidth: .infinity, alignment: .leading) + + Button { + center.dismiss() + } label: { + ZStack { + Circle() + .stroke(toast.kind.accentColor.opacity(0.18), lineWidth: 2) + .frame(width: 26, height: 26) + Circle() + .trim(from: 0, to: remainingFraction) + .stroke( + toast.kind.accentColor, + style: StrokeStyle(lineWidth: 2, lineCap: .round) + ) + .rotationEffect(.degrees(-90)) + .frame(width: 26, height: 26) + Image(systemName: "xmark") + .font(.system(size: 10, weight: .bold)) + .foregroundStyle(.secondary) + } + } + .buttonStyle(.plain) + .accessibilityLabel("关闭提醒") + } + + // Direct one-tap approval buttons for Permission or Question + switch toast.kind { + case let .permission(prompt): + permissionActionsRow(toast: toast, prompt: prompt) + case let .question(question): + questionActionsRow(toast: toast, question: question) + case .completed, .failed: + EmptyView() + } + + if let err = center.actionError { + Text(err) + .font(.system(size: 11.5)) + .foregroundStyle(.red) + .lineLimit(2) + } + + // Expandable inline quick reply or bottom action bar + if isReplying { + HStack(spacing: 8) { + TextField("输入回复内容并发送…", text: $replyText) + .font(.system(size: 13.5)) + .textFieldStyle(.plain) + .focused($replyFocused) + .padding(.horizontal, 12) + .padding(.vertical, 8) + .background( + Capsule(style: .continuous) + .fill(Color(.tertiarySystemFill)) + ) + .onSubmit { + submitReply(toast) + } + + Button { + isReplying = false + replyFocused = false + } label: { + Text("取消") + .font(.system(size: 12.5, weight: .medium)) + .foregroundStyle(.secondary) + .padding(.horizontal, 8) + .padding(.vertical, 7) + } + .buttonStyle(.plain) + + Button { + submitReply(toast) + } label: { + Text("发送") + .font(.system(size: 12.5, weight: .semibold)) + .foregroundStyle(.white) + .padding(.horizontal, 13) + .padding(.vertical, 7) + .background(Capsule(style: .continuous).fill(Color.primary)) + } + .buttonStyle(.plain) + .disabled(replyText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || center.actionBusy) + } + } else { + HStack(spacing: 8) { + Spacer(minLength: 0) + + if case .completed = toast.kind { + Button { + UINotificationFeedbackGenerator().notificationOccurred(.success) + center.dismiss() + } label: { + HStack(spacing: 5) { + Image(systemName: "checkmark.circle.fill") + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(toast.kind.accentColor) + Text("确认完成") + .font(.system(size: 12.5, weight: .semibold)) + } + .padding(.horizontal, 12) + .padding(.vertical, 7) + .background( + Capsule(style: .continuous) + .fill(toast.kind.accentColor.opacity(0.14)) + ) + .foregroundStyle(.primary) + } + .buttonStyle(.plain) + } + + Button { + withAnimation(.smooth(duration: 0.18)) { + isReplying = true + } + replyFocused = true + } label: { + HStack(spacing: 5) { + Image(systemName: "bubble.left") + .font(.system(size: 11.5, weight: .semibold)) + Text("快捷回复") + .font(.system(size: 12.5, weight: .medium)) + } + .padding(.horizontal, 12) + .padding(.vertical, 7) + .background( + Capsule(style: .continuous) + .fill(Color(.tertiarySystemFill)) + ) + .overlay( + Capsule(style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.5) + ) + .foregroundStyle(.primary) + } + .buttonStyle(.plain) + + Button { + onOpenConversation(toast.conversation) + } label: { + Text("打开会话") + .font(.system(size: 12.5, weight: .semibold)) + .foregroundStyle(Color(.systemBackground)) + .padding(.horizontal, 14) + .padding(.vertical, 7) + .background( + Capsule(style: .continuous) + .fill(Color.primary) + ) + } + .buttonStyle(.plain) + } + } + } + .padding(14) + .background( + RoundedRectangle(cornerRadius: 20, style: .continuous) + .fill(.regularMaterial) + .background( + RoundedRectangle(cornerRadius: 20, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground).opacity(0.92)) + ) + ) + .overlay( + RoundedRectangle(cornerRadius: 20, style: .continuous) + .strokeBorder(toast.kind.accentColor.opacity(0.28), lineWidth: 1) + ) + .shadow(color: .black.opacity(0.14), radius: 18, x: 0, y: 8) + } + + @ViewBuilder + private func permissionActionsRow(toast: CompanionAttentionToast, prompt: PermissionPrompt) -> some View { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 7) { + 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 + ) + } + } label: { + HStack(spacing: 4) { + Image(systemName: allow ? "checkmark.shield.fill" : "xmark.circle") + .font(.system(size: 11.5, weight: .semibold)) + Text(option.label) + .font(.system(size: 12.5, weight: .semibold)) + } + .padding(.horizontal, 12) + .padding(.vertical, 6.5) + .background( + Capsule(style: .continuous) + .fill(allow ? Color.accentColor : Color(.tertiarySystemFill)) + ) + .foregroundStyle(allow ? Color.white : Color.primary) + } + .buttonStyle(.plain) + .disabled(center.actionBusy) + } + } + } + } + + @ViewBuilder + private func questionActionsRow(toast: CompanionAttentionToast, question: PendingQuestion) -> some View { + let choices = Self.extractQuestionChoices(question) + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 7) { + if choices.isEmpty { + Button { + Task { + await center.respondQuestion( + client: client, + conversationID: toast.conversation.id, + question: question, + choice: nil, + fallbackText: "Yes" + ) + } + } label: { + HStack(spacing: 4) { + Image(systemName: "checkmark.circle.fill") + .font(.system(size: 11.5, weight: .semibold)) + Text("批准执行") + .font(.system(size: 12.5, weight: .semibold)) + .lineLimit(1) + } + .padding(.horizontal, 12) + .padding(.vertical, 6.5) + .background(Capsule(style: .continuous).fill(Color.accentColor)) + .foregroundStyle(Color.white) + } + .buttonStyle(.plain) + .disabled(center.actionBusy) + } else { + ForEach(choices.indices, id: \.self) { index in + let choice = choices[index] + let isPrimary = index == 0 + Button { + Task { + await center.respondQuestion( + client: client, + conversationID: toast.conversation.id, + question: question, + choice: choice + ) + } + } label: { + HStack(spacing: 4) { + Image(systemName: isPrimary ? "checkmark.circle.fill" : "circle") + .font(.system(size: 11.5, weight: .semibold)) + Text(choice.label) + .font(.system(size: 12.5, weight: .semibold)) + .lineLimit(1) + } + .padding(.horizontal, 12) + .padding(.vertical, 6.5) + .background( + Capsule(style: .continuous) + .fill(isPrimary ? Color.accentColor : Color(.tertiarySystemFill)) + ) + .foregroundStyle(isPrimary ? Color.white : Color.primary) + } + .buttonStyle(.plain) + .disabled(center.actionBusy) + } + } + + Button { + Task { + await center.respondQuestion( + client: client, + conversationID: toast.conversation.id, + question: question, + choice: nil + ) + } + } label: { + Text("拒绝") + .font(.system(size: 12.5, weight: .medium)) + .padding(.horizontal, 11) + .padding(.vertical, 6.5) + .background( + Capsule(style: .continuous) + .fill(Color.red.opacity(0.12)) + ) + .foregroundStyle(.red) + } + .buttonStyle(.plain) + .disabled(center.actionBusy) + } + } + } + + private static func extractQuestionChoices(_ request: PendingQuestion) -> [QuestionChoice] { + let forms = QuestionForm.questions(for: request) + if let first = forms.first, !first.choices.isEmpty { + return Array(first.choices.prefix(3)) + } + return [] + } + + private func submitReply(_ toast: CompanionAttentionToast) { + let text = replyText + Task { + if await center.sendQuickReply(client: client, toast: toast, text: text) { + replyText = "" + isReplying = false + } + } + } +} diff --git a/mobile/ios/App/ConversationDetailView.swift b/mobile/ios/App/ConversationDetailView.swift index 982606ba3..9496c73c2 100644 --- a/mobile/ios/App/ConversationDetailView.swift +++ b/mobile/ios/App/ConversationDetailView.swift @@ -9,12 +9,25 @@ struct ConversationDetailView: View { @State private var created: ConversationListItem? @State private var diffChange: FileChangeItem? - init(client: HostClient, conversation: ConversationListItem) { + var onToggleSidebar: (() -> Void)? + var onReturnToLanding: (() -> Void)? + + init( + client: HostClient, + conversation: ConversationListItem, + onToggleSidebar: (() -> Void)? = nil, + onReturnToLanding: (() -> Void)? = nil + ) { _model = State(initialValue: ConversationModel(client: client, conversation: conversation)) + self.onToggleSidebar = onToggleSidebar + self.onReturnToLanding = onReturnToLanding } var body: some View { VStack(spacing: 0) { + if onToggleSidebar != nil { + embeddedHeaderBar + } messages .overlay { if menu != nil { @@ -27,16 +40,16 @@ struct ConversationDetailView: View { .padding(.bottom, 8) } if let question = model.session.pendingQuestions.first { - ApprovalCard(request: question) { content in - await model.respond(to: question, content: content) + ApprovalCard(request: question, busy: model.busy) { content in + Task { await model.respond(to: question, content: content) } } .id(question.id) .padding(.horizontal, 12) .padding(.bottom, 8) } if let prompt = model.session.pendingPermissions.first { - PermissionBanner(prompt: prompt) { option in - Task { await model.respond(to: prompt, option: option) } + PermissionBanner(prompt: prompt, busy: model.busy) { option, persist in + Task { await model.respond(to: prompt, option: option, persist: persist) } } } if let message = model.actionError { @@ -51,14 +64,17 @@ struct ConversationDetailView: View { } .navigationTitle(model.conversation.title ?? "未命名对话") .navigationBarTitleDisplayMode(.inline) - .toolbar(.hidden, for: .tabBar) + .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(agent.displayName) { + Button { Task { created = await model.createConversation(agentID: agent.id) } + } label: { + AgentMenuLabel(agentID: agent.id, hostName: agent.displayName) } } } @@ -91,20 +107,122 @@ struct ConversationDetailView: View { FileDiffSheet(client: model.client, workspaceID: model.conversation.workspace_id, path: change.path) } } - .onDisappear { model.stopActivity() } + .onDisappear { + dismissKeyboard() + model.stopActivity() + } .navigationDestination(item: $created) { ConversationDetailView(client: model.client, conversation: $0) } .background { Color(.systemGroupedBackground).ignoresSafeArea() } .task { while !Task.isCancelled { await model.reload() - try? await Task.sleep(for: .seconds(model.session.isTurnRunning ? 0.6 : 4)) + if model.isActivelyStreaming { + try? await Task.sleep(for: .milliseconds(140)) + } else { + for _ in 0..<6 { + if Task.isCancelled || model.isActivelyStreaming { break } + try? await Task.sleep(for: .milliseconds(200)) + } + } } } .onChange(of: menu) { _, kind in - if kind == .model { Task { await model.refreshCatalog() } } + if kind == .model || kind == .plusModel { Task { await model.refreshCatalog() } } } } + 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 { + Circle() + .fill(Color.orange) + .frame(width: 6.5, height: 6.5) + } + Text(model.conversation.title ?? "未命名对话") + .font(.system(size: 15.5, weight: .semibold)) + .foregroundStyle(.primary) + .lineLimit(1) + } + + HStack(spacing: 4) { + AgentIconView(agent: model.conversation.agent_id, size: 11) + Text(model.currentModelLabel ?? AgentBrand.displayName(model.conversation.agent_id)) + .font(.system(size: 11, 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("新建对话") + } + + 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("更多操作") + } + } + .padding(.horizontal, 12) + .padding(.vertical, 7) + .background( + Color(.systemGroupedBackground) + .overlay(alignment: .bottom) { + Divider().opacity(0.45) + } + ) + } + // MARK: Prompt bar private var promptBar: some View { @@ -115,6 +233,7 @@ struct ConversationDetailView: View { busy: model.busy, hasAlert: !model.session.pendingPermissions.isEmpty, modelName: model.currentModelLabel, + agentID: model.conversation.agent_id, modelChoices: modelChoices, otherModelGroups: otherModelGroups, otherAgentNote: otherModelGroups.isEmpty @@ -133,6 +252,7 @@ struct ConversationDetailView: View { PromptChoice(id: "option:" + $0.key, title: $0.label, tag: $0.currentLabel, icon: "slider.horizontal.3") }, effort: effort, + openFiles: { panel = .files }, send: { let text = draft Task { if await model.send(text) { draft = "" } } @@ -170,6 +290,7 @@ struct ConversationDetailView: View { id: option.key + "|" + $0.id, title: $0.label, tag: $0.description, + agentID: model.conversation.agent_id, selected: $0.value == model.value(of: option) ) } @@ -179,9 +300,10 @@ struct ConversationDetailView: View { private var otherModelGroups: [PromptGroup] { model.otherAgentsWithModels.map { agent in PromptGroup( - title: agent.displayName, + 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, enabled: false) + PromptChoice(id: agent.id + "|" + $0.id, title: $0.label, agentID: agent.id, enabled: false) } ) } @@ -220,10 +342,12 @@ struct ConversationDetailView: View { } else { ScrollViewReader { proxy in ScrollView { - LazyVStack(alignment: .leading, spacing: 18) { + LazyVStack(alignment: .leading, spacing: 16) { ForEach(model.items) { item in MessageRow( item: item, + agentID: model.conversation.agent_id, + modelName: model.currentModelLabel, isLast: item.id == model.items.last?.id, running: model.session.isTurnRunning, openDiff: { diffChange = $0 } @@ -233,12 +357,30 @@ struct ConversationDetailView: View { if model.session.isTurnRunning && model.items.last?.role != .assistant { LoadingState(label: "正在思考").id("loading") } + Color.clear + .frame(height: 1) + .id("conversation-bottom") } - .padding() + .padding(.horizontal, 14) + .padding(.vertical, 12) } .scrollDismissesKeyboard(.interactively) - .onChange(of: model.items.last) { _, last in - if let last { withAnimation { proxy.scrollTo(last.id, anchor: .bottom) } } + .onChange(of: model.items.count) { _, _ in + withAnimation(.smooth(duration: 0.22)) { + proxy.scrollTo("conversation-bottom", anchor: .bottom) + } + } + .onChange(of: model.items.last?.text.count) { _, _ in + if model.isActivelyStreaming { + proxy.scrollTo("conversation-bottom", anchor: .bottom) + } + } + .onChange(of: model.items.last?.segments.count) { _, _ in + if model.isActivelyStreaming { + withAnimation(.smooth(duration: 0.18)) { + proxy.scrollTo("conversation-bottom", anchor: .bottom) + } + } } } } @@ -261,67 +403,420 @@ enum DetailPanel: String, Identifiable { private struct MessageRow: View { let item: TimelineItem + let agentID: String? + let modelName: String? let isLast: Bool let running: Bool let openDiff: (FileChangeItem) -> Void + private var lastTextSegmentID: String? { + item.segments.last { segment in + if case .text = segment { return true } + return false + }?.id + } + var body: some View { switch item.role { case .user: + let extracted = AttachmentImageStore.shared.extractUserAttachments(from: item.text) HStack { - Spacer(minLength: 40) - Text(item.text) - .textSelection(.enabled) - .padding(12) - .background(Color.accentColor.opacity(0.15), in: RoundedRectangle(cornerRadius: 14)) + Spacer(minLength: 48) + VStack(alignment: .trailing, spacing: 6) { + if !extracted.items.isEmpty { + HStack(spacing: 6) { + ForEach(extracted.items) { imgItem in + MarkdownImageFrameView( + src: imgItem.urlString ?? imgItem.id, + alt: imgItem.title, + fixedImage: imgItem.image + ) + } + } + } + if !extracted.cleanText.isEmpty { + Text(extracted.cleanText) + .font(.system(size: 15)) + .lineSpacing(3) + .textSelection(.enabled) + .padding(.horizontal, 14) + .padding(.vertical, 10) + .background( + UnevenRoundedRectangle( + topLeadingRadius: 16, + bottomLeadingRadius: 16, + bottomTrailingRadius: 5, + topTrailingRadius: 16 + ) + .fill(Color.accentColor.opacity(0.16)) + ) + } + } } case .assistant: let streaming = running && isLast - VStack(alignment: .leading, spacing: 10) { - if !item.thinking.isEmpty { - ThinkingView(item: item, working: streaming && item.text.isEmpty) - } - if !item.tools.isEmpty || !item.changes.isEmpty { - ToolChipsView(item: item, working: streaming, openDiff: openDiff) + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 6) { + AgentIconView(agent: agentID, size: 15) + .frame(width: 22, height: 22) + .background( + RoundedRectangle(cornerRadius: 6, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + Text(AgentBrand.displayName(agentID)) + .font(.system(size: 12.5, weight: .semibold)) + .foregroundStyle(.primary) + if let modelName, !modelName.isEmpty, modelName != AgentBrand.displayName(agentID) { + Text(modelName) + .font(.system(size: 11.5)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + if streaming { + Circle() + .fill(Color.orange) + .frame(width: 6, height: 6) + } + Spacer() } - if !item.text.isEmpty { - StreamingMessageText(text: item.text, streaming: streaming) + + if item.segments.isEmpty { + if !item.thinking.isEmpty { + ThinkingView(item: item, working: streaming && item.text.isEmpty) + } + if !item.tools.isEmpty || !item.changes.isEmpty { + ToolChipsView(item: item, working: streaming, openDiff: openDiff) + } + if !item.text.isEmpty { + StreamingMessageText(text: item.text, streaming: streaming) + .padding(.top, 2) + } + } else { + ForEach(item.segments) { segment in + segmentView(segment, streaming: streaming) + } + if !item.changes.isEmpty { + ToolChipsView( + tools: [], + changes: item.changes, + working: false, + openDiff: openDiff + ) + } } } .frame(maxWidth: .infinity, alignment: .leading) } } + + @ViewBuilder + private func segmentView(_ segment: TimelineSegment, streaming: Bool) -> some View { + let isLastSegment = segment.id == item.segments.last?.id + switch segment { + case let .thinking(_, text): + ThinkingView( + text: text, + durationMs: item.durationMs, + working: streaming && isLastSegment + ) + case let .tools(_, tools): + ToolChipsView( + tools: tools, + changes: [], + working: streaming && isLastSegment, + openDiff: openDiff + ) + case let .text(id, text): + let isLastText = id == lastTextSegmentID + StreamingMessageText( + text: text, + streaming: streaming && isLastSegment, + showCopyButton: isLastText, + copyPayload: item.text + ) + .padding(.top, 2) + } + } } +/// SwiftUI port of VibeX desktop's `PermissionRequestCard.tsx`: +/// displays the permission category badge, resolved heading & subtitle, structured tool-call preview +/// (expandable diffs, shell command, file paths), and progressive scope actions (`拒绝` + `[ 允许 | ▾ ]`). private struct PermissionBanner: View { let prompt: PermissionPrompt - let respond: (PermissionOption?) -> Void + let busy: Bool + let respond: (PermissionOption?, Bool) -> Void + + @State private var expandedDiffIDs: Set = [] var body: some View { - VStack(alignment: .leading, spacing: 8) { - Label(prompt.title, systemImage: "exclamationmark.shield") - .font(.subheadline.weight(.semibold)) - .foregroundStyle(.orange) - ForEach(prompt.options) { option in - let allow = option.kind.hasPrefix("allow") - Button { respond(option) } label: { - Text(option.label) - .font(.subheadline) - .multilineTextAlignment(.leading) + let primaryAllow = prompt.resolveAllowOption(for: .once) + let rejectOption = prompt.rejectOption + + VStack(alignment: .leading, spacing: 10) { + // 1. Category type row (`permissionTypeFor`) + HStack(spacing: 6) { + Image(systemName: prompt.category.systemImage) + .font(.system(size: 12, weight: .semibold)) + Text(prompt.category.label) + .font(.system(size: 12, weight: .medium)) + } + .foregroundStyle(.secondary) + + // 2. Heading (`detail.heading ?? t('permissionRequestCard.title')`) + Text(prompt.displayHeading) + .font(.system(size: 14, weight: .semibold)) + .foregroundStyle(.primary) + + // 3. Preview block (`permission-request-preview`) + if prompt.displaySubtitle != nil + || !prompt.diffs.isEmpty + || !prompt.textBlocks.isEmpty + || prompt.command != nil + || !prompt.locations.isEmpty + { + VStack(alignment: .leading, spacing: 6) { + if let subtitle = prompt.displaySubtitle { + Text(subtitle) + .font(.system(size: 13.5)) + .foregroundStyle(.primary) + .fixedSize(horizontal: false, vertical: true) + } + + ForEach(prompt.diffs) { diff in + diffPreviewRow(diff) + } + + ForEach(Array(prompt.textBlocks.enumerated()), id: \.offset) { _, blockText in + ScrollView(.horizontal, showsIndicators: false) { + Text(blockText) + .font(.system(size: 12, design: .monospaced)) + .foregroundStyle(.primary) + } + .padding(.horizontal, 10) + .padding(.vertical, 7) + .frame(maxWidth: .infinity, alignment: .leading) + .background( + RoundedRectangle(cornerRadius: 7, style: .continuous) + .fill(Color(.tertiarySystemGroupedBackground)) + ) + } + + if let command = prompt.command, !command.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + Text(command) + .font(.system(size: 12, design: .monospaced)) + .foregroundStyle(.primary) + } + .padding(.horizontal, 10) + .padding(.vertical, 7) .frame(maxWidth: .infinity, alignment: .leading) - .padding(.horizontal, 14) - .padding(.vertical, 10) .background( - (allow ? Color.accentColor : Color.secondary).opacity(0.14), - in: RoundedRectangle(cornerRadius: 12, style: .continuous) + RoundedRectangle(cornerRadius: 7, style: .continuous) + .fill(Color(.tertiarySystemGroupedBackground)) + ) + } + + if !prompt.locations.isEmpty { + VStack(alignment: .leading, spacing: 3) { + ForEach(prompt.locations, id: \.self) { path in + Text(path) + .font(.system(size: 11.5, design: .monospaced)) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + } + .padding(.top, 2) + } + } + } + + // 4. Progressive Action Footer (`拒绝` + split `[ 允许 | ▾ ]`) + HStack(spacing: 8) { + Spacer(minLength: 0) + + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + respond(rejectOption, false) + } label: { + Text("拒绝") + .font(.system(size: 12.5, weight: .medium)) + .foregroundStyle(.primary) + .padding(.horizontal, 13) + .frame(height: 30) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color(.tertiarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(Color.primary.opacity(0.10), lineWidth: 0.7) ) } .buttonStyle(.plain) - .foregroundStyle(allow ? Color.accentColor : Color.secondary) + .disabled(busy) + + if let primaryAllow { + HStack(spacing: 0) { + Button { + UIImpactFeedbackGenerator(style: .medium).impactOccurred() + respond(primaryAllow, false) + } label: { + HStack(spacing: 5) { + if busy { + ProgressView().controlSize(.mini).tint(Color(.systemBackground)) + } + Text("允许") + .font(.system(size: 12.5, weight: .semibold)) + } + .foregroundStyle(Color(.systemBackground)) + .padding(.leading, 13) + .padding(.trailing, 10) + .frame(height: 30) + } + .buttonStyle(.plain) + .disabled(busy) + + Rectangle() + .fill(Color(.systemBackground).opacity(0.22)) + .frame(width: 0.8, height: 18) + + Menu { + ForEach(PermissionAllowScope.allCases, id: \.rawValue) { scope in + if let opt = prompt.resolveAllowOption(for: scope) { + Button { + UIImpactFeedbackGenerator(style: .medium).impactOccurred() + respond(opt, scope != .once) + } label: { + Text(scope.label) + } + } + } + } label: { + Image(systemName: "chevron.down") + .font(.system(size: 10.5, weight: .bold)) + .foregroundStyle(Color(.systemBackground)) + .frame(width: 28, height: 30) + .contentShape(Rectangle()) + } + .disabled(busy) + } + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color.primary) + ) + } else { + ForEach(prompt.options) { option in + Button { + respond(option, false) + } label: { + Text(option.label) + .font(.system(size: 12.5, weight: .semibold)) + .foregroundStyle(Color(.systemBackground)) + .padding(.horizontal, 12) + .frame(height: 30) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color.primary) + ) + } + .buttonStyle(.plain) + .disabled(busy) + } + } } + .padding(.top, 2) } - .padding() + .padding(.horizontal, 14) + .padding(.vertical, 12) .frame(maxWidth: .infinity, alignment: .leading) - .background(Color.orange.opacity(0.1)) + .background( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .strokeBorder(Color.primary.opacity(0.10), lineWidth: 0.75) + ) + .shadow(color: .black.opacity(0.05), radius: 8, y: 2) + .padding(.horizontal, 12) + .padding(.bottom, 8) + } + + private func diffPreviewRow(_ diff: PermissionDiffPreview) -> some View { + let isOpen = expandedDiffIDs.contains(diff.id) + return VStack(alignment: .leading, spacing: 0) { + Button { + withAnimation(.spring(response: 0.25, dampingFraction: 0.86)) { + if isOpen { + expandedDiffIDs.remove(diff.id) + } else { + expandedDiffIDs.insert(diff.id) + } + } + } label: { + HStack(spacing: 6) { + Image(systemName: "chevron.right") + .font(.system(size: 10, weight: .bold)) + .foregroundStyle(.secondary) + .rotationEffect(.degrees(isOpen ? 90 : 0)) + Text(diff.path) + .font(.system(size: 12, design: .monospaced)) + .foregroundStyle(.primary) + .lineLimit(1) + .truncationMode(.middle) + Spacer(minLength: 6) + Text(diff.isNewFile ? "新文件" : "已修改") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + } + .padding(.horizontal, 10) + .padding(.vertical, 7) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + if isOpen { + VStack(alignment: .leading, spacing: 6) { + if !diff.isNewFile { + diffPane(label: "修改前", text: diff.oldText, isAddition: false) + } + diffPane(label: diff.isNewFile ? "文件内容" : "修改后", text: diff.newText, isAddition: true) + } + .padding(.horizontal, 10) + .padding(.bottom, 8) + } + } + .background( + RoundedRectangle(cornerRadius: 7, style: .continuous) + .fill(Color(.tertiarySystemGroupedBackground)) + ) + } + + private func diffPane(label: String, text: String, isAddition: Bool) -> some View { + let tint: Color = isAddition ? .green : .red + return VStack(alignment: .leading, spacing: 2) { + Text(label) + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.secondary) + ScrollView([.horizontal, .vertical], showsIndicators: false) { + Text(text) + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(.primary) + .padding(.horizontal, 8) + .padding(.vertical, 5) + } + .frame(maxHeight: 140, alignment: .leading) + .frame(maxWidth: .infinity, alignment: .leading) + .background( + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(tint.opacity(0.10)) + ) + .overlay( + RoundedRectangle(cornerRadius: 5, style: .continuous) + .strokeBorder(tint.opacity(0.28), lineWidth: 0.6) + ) + } } } diff --git a/mobile/ios/App/ConversationModel.swift b/mobile/ios/App/ConversationModel.swift index 85631d4d0..d9a138260 100644 --- a/mobile/ios/App/ConversationModel.swift +++ b/mobile/ios/App/ConversationModel.swift @@ -23,8 +23,13 @@ final class ConversationModel { private(set) var hasLoaded = false private(set) var loadError: String? private(set) var busy = false + private(set) var boostPollingUntil: Date = .distantPast var actionError: String? + var isActivelyStreaming: Bool { + session.isTurnRunning || Date() < boostPollingUntil + } + init(client: HostClient, conversation: ConversationListItem) { self.client = client self.conversation = conversation @@ -32,21 +37,44 @@ final class ConversationModel { } func reload() async { - do { - var state = transcript - try await client.refresh(&state) + let initialTranscript = transcript + let currentClient = client + let convID = conversation.id + let seq = lastSequence + + async let refreshedTranscriptResult: Result = { + var state = initialTranscript + do { + try await currentClient.refresh(&state) + return .success(state) + } catch { + return .failure(error) + } + }() + + async let offlineCacheResult: OfflineConversationCache? = try? currentClient.offlineConversation( + id: convID, + afterSequence: seq + ) + + let transcriptResult = await refreshedTranscriptResult + let cache = await offlineCacheResult + + switch transcriptResult { + case .success(let state): transcript = state items = state.items hasLoaded = true loadError = nil - } catch is CancellationError { + case .failure(let error) where error is CancellationError: return - } catch { + case .failure(let error): loadError = describeHostFailure(error) return } + // Mode, model, permission and question state come from the control-plane events; a failure keeps the last state. - if let cache = try? await client.offlineConversation(id: conversation.id, afterSequence: lastSequence) { + if let cache { let fresh = cache.events ?? [] events += fresh lastSequence = max(lastSequence, cache.confirmed_through) @@ -150,6 +178,8 @@ final class ConversationModel { actionError = "此对话没有绑定 Agent,无法发送" return false } + boostPollingUntil = Date().addingTimeInterval(25) + session.isTurnRunning = true return await perform { try await client.sendMessage( conversationID: conversation.id, @@ -186,18 +216,23 @@ final class ConversationModel { _ = await perform { try await client.cancelTurn(conversationID: conversation.id) } } - func respond(to prompt: PermissionPrompt, option: PermissionOption?) async { + func respond(to prompt: PermissionPrompt, option: PermissionOption?, persist: Bool = false) async { + boostPollingUntil = Date().addingTimeInterval(25) + session.isTurnRunning = true _ = await perform { try await client.respondPermission( conversationID: conversation.id, permissionID: prompt.id, - optionID: option?.id + optionID: option?.id, + persist: persist ) } } /// `content` nil declines the question. func respond(to question: PendingQuestion, content: JSONValue?) async { + boostPollingUntil = Date().addingTimeInterval(25) + session.isTurnRunning = true _ = await perform { try await client.respondQuestion( conversationID: conversation.id, diff --git a/mobile/ios/App/ConversationTools.swift b/mobile/ios/App/ConversationTools.swift index 108f5e217..ba4f788f6 100644 --- a/mobile/ios/App/ConversationTools.swift +++ b/mobile/ios/App/ConversationTools.swift @@ -3,7 +3,7 @@ import SwiftUI // MARK: - 浏览文件 -private enum BrowseTarget: Hashable { +enum BrowseTarget: Hashable { case directory(String) case file(String) } @@ -12,11 +12,17 @@ private enum BrowseTarget: Hashable { struct FileBrowserView: View { let client: HostClient let workspaceID: String + @Environment(\.dismiss) private var dismiss @State private var stack: [BrowseTarget] = [] var body: some View { NavigationStack(path: $stack) { DirectoryView(client: client, workspaceID: workspaceID, path: "", navigate: { stack.append($0) }) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("完成") { dismiss() } + } + } .navigationDestination(for: BrowseTarget.self) { target in switch target { case .directory(let path): @@ -29,10 +35,11 @@ struct FileBrowserView: View { } } -private struct DirectoryView: View { +struct DirectoryView: View { let client: HostClient let workspaceID: String let path: String + var rootTitle: String = "浏览文件" let navigate: (BrowseTarget) -> Void @State private var list = RemoteList() @State private var truncated = false @@ -40,7 +47,7 @@ private struct DirectoryView: View { var body: some View { content - .navigationTitle(path.isEmpty ? "浏览文件" : (path as NSString).lastPathComponent) + .navigationTitle(path.isEmpty ? rootTitle : (path as NSString).lastPathComponent) .navigationBarTitleDisplayMode(.inline) .task { await load() } } @@ -81,7 +88,9 @@ private struct DirectoryView: View { private func sections(_ entries: [WorkspaceEntry]) -> [BranchedSection] { let dirs = entries.filter(\.directory).map { BranchedItem(id: "d:" + $0.path, label: $0.name, icon: "folder") } - let files = entries.filter { !$0.directory }.map { BranchedItem(id: "f:" + $0.path, label: $0.name, icon: "doc.text") } + let files = entries.filter { !$0.directory }.map { + BranchedItem(id: "f:" + $0.path, label: $0.name, icon: FileGlyph.symbol(for: $0.name)) + } return [ BranchedSection(id: "dirs", label: "目录 \(dirs.count)", children: dirs), BranchedSection(id: "files", label: "文件 \(files.count)", children: files), @@ -98,21 +107,78 @@ private struct DirectoryView: View { } } -private struct FileContentView: View { +struct FileContentView: View { let client: HostClient let workspaceID: String let path: String @State private var file: WorkspaceFile? @State private var errorMessage: String? + @State private var showFullImage = false + + private var isImageFile: Bool { + let ext = (path as NSString).pathExtension.lowercased() + return ["png", "jpg", "jpeg", "gif", "webp", "heic", "ico", "bmp"].contains(ext) + } + + private var decodedImage: UIImage? { + if let content = file?.content, !content.isEmpty { + if let img = AttachmentImageStore.decodeImage(from: content) { + return img + } + if let data = Data(base64Encoded: content, options: .ignoreUnknownCharacters), + let img = UIImage(data: data) + { + return img + } + } + return AttachmentImageStore.decodeImage(from: path) + } var body: some View { Group { if let file { - if file.binary { - ContentUnavailableView("二进制文件无法预览", systemImage: "doc.zipper") + if let uiImage = decodedImage { + VStack(spacing: 16) { + MarkdownImageFrameView( + src: path, + alt: (path as NSString).lastPathComponent, + fixedImage: uiImage + ) + Button { + showFullImage = true + } label: { + Label("全屏查看与标注", systemImage: "arrow.up.left.and.arrow.down.right") + .font(.system(size: 13.5, weight: .semibold)) + .padding(.horizontal, 16) + .padding(.vertical, 9) + .background(Color.accentColor.opacity(0.12), in: Capsule()) + } + .buttonStyle(.plain) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding(20) + .fullScreenCover(isPresented: $showFullImage) { + ZoomableImagePreviewSheet( + item: PreviewableImageItem( + id: path, + image: uiImage, + urlString: nil, + title: (path as NSString).lastPathComponent + ) + ) + } + } else if file.binary { + ContentUnavailableView( + isImageFile ? "暂无法在远端直接流式读取此二进制图片" : "二进制文件无法预览", + systemImage: isImageFile ? "photo" : "doc.zipper" + ) } else { - CodeView(lines: (file.content ?? "").split(separator: "\n", omittingEmptySubsequences: false).map(String.init), - note: file.truncated ? "只显示前 256 KB" : nil) + CodeBlockView( + code: file.content ?? "", + title: path, + language: CodeLanguage.detect(path: path), + note: file.truncated ? "文件较大,只显示前 256 KB" : nil + ) } } else if let errorMessage { LoadFailureView(message: errorMessage) { Task { await load() } } @@ -135,38 +201,13 @@ private struct FileContentView: View { } } -private struct CodeView: View { - let lines: [String] - let note: String? - - var body: some View { - ScrollView([.vertical, .horizontal]) { - LazyVStack(alignment: .leading, spacing: 0) { - ForEach(Array(lines.enumerated()), id: \.offset) { index, text in - HStack(alignment: .top, spacing: 12) { - Text("\(index + 1)") - .foregroundStyle(.tertiary) - .frame(minWidth: 36, alignment: .trailing) - Text(text.isEmpty ? " " : text) - } - .font(.system(size: 12, design: .monospaced)) - .textSelection(.enabled) - } - if let note { - Text(note).font(.footnote).foregroundStyle(.secondary).padding(.top, 12) - } - } - .padding(12) - } - } -} - // MARK: - 代码差异 /// "代码差异": working tree against HEAD, file by file, line by line. struct DiffListView: View { let client: HostClient let workspaceID: String + @Environment(\.dismiss) private var dismiss @State private var list = RemoteList() var body: some View { @@ -174,6 +215,11 @@ struct DiffListView: View { content .navigationTitle("代码差异") .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("完成") { dismiss() } + } + } .navigationDestination(for: FileDiff.self) { DiffFileView(client: client, workspaceID: workspaceID, diff: $0) } @@ -330,6 +376,7 @@ struct FileDiffSheet: View { let client: HostClient let workspaceID: String let path: String + @Environment(\.dismiss) private var dismiss @State private var diff: FileDiff? @State private var missing = false @State private var errorMessage: String? @@ -349,6 +396,11 @@ struct FileDiffSheet: View { ProgressView() } } + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("完成") { dismiss() } + } + } } .task { await load() } } diff --git a/mobile/ios/App/ConversationsView.swift b/mobile/ios/App/ConversationsView.swift index ccdad1106..3b63947da 100644 --- a/mobile/ios/App/ConversationsView.swift +++ b/mobile/ios/App/ConversationsView.swift @@ -1,193 +1,1201 @@ import CompanionCore import SwiftUI -/// Conversations grouped by project: the root lists projects, a project lists only its own conversations. +private enum SidebarSectionTab: String, CaseIterable, Identifiable { + case conversations = "最近对话" + case files = "项目文件" + var id: String { rawValue } +} + +private struct StarterSuggestion: Identifiable { + let id: String + let label: String + let prompt: String +} + +/// 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. struct ConversationsView: View { let client: HostClient + var onChromeHiddenChange: ((Bool) -> Void)? = nil + var onLaunchRevealedChange: ((Bool) -> Void)? = nil + @Environment(CompanionAttentionCenter.self) private var attentionCenter: CompanionAttentionCenter? + @State private var list = RemoteList() @State private var projects: [ProjectSummary]? + @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? + + // 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 actionErrorMessage: String? + + // Landing page configuration state + @State private var selectedProjectID: String? + @State private var selectedAgentID: String? + @State private var selectedModelChoiceID: String? + @State private var selectedAccessModeID: String? + @State private var selectedEffortIndex: Int? + @State private var draft = "" + @State private var composerMenu: ComposerMenu? + @State private var isCreatingAndSending = false + @State private var showProjectPickerSheet = 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 visibleConversations: [ConversationListItem] { + (list.items ?? []).filter { !removedConversationIDs.contains($0.id) } + } + + private var groups: [ProjectGroup] { + ProjectGroup.make(conversations: visibleConversations, projects: projects ?? []) + } + + private var currentGroup: ProjectGroup? { + if let id = selectedProjectID, let match = groups.first(where: { $0.id == id }) { + return match + } + if let gitGroup = groups.first(where: { !$0.isHome && $0.id != "other" && $0.isGit }) { + return gitGroup + } + if let nonHome = groups.first(where: { !$0.isHome && $0.id != "other" }) { + return nonHome + } + return groups.first + } + + private var currentWorkspaceID: String? { + guard let group = currentGroup else { + return visibleConversations.first?.workspace_id + } + return workspaceID(for: group) + } + + 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 usableAgents: [CatalogAgent] { + let usable = agents.filter(\.usable) + return usable.isEmpty ? agents : 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 }) { + return match + } + return usableAgents.first + } var body: some View { - NavigationStack { - content - .navigationTitle("对话") - .navigationDestination(for: ProjectRoute.self) { route in - ProjectConversationsView( - client: client, - group: group(id: route.id), - projects: projects ?? [], - onRefresh: { await reload() } - ) + ZStack(alignment: .leading) { + Group { + if let activeConversation { + NavigationStack { + ConversationDetailView( + client: client, + conversation: activeConversation, + onToggleSidebar: { + withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { + isSidebarOpen.toggle() + } + }, + onReturnToLanding: { + withAnimation(.smooth(duration: 0.2)) { + self.activeConversation = nil + } + } + ) + .id(activeConversation.id) + } + } else { + landingWorkspaceView } - .navigationDestination(for: ConversationListItem.self) { - ConversationDetailView(client: client, conversation: $0) + } + .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) + } + } + .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]) + .presentationDragIndicator(.visible) + } + .onAppear { + consumePendingNavigationIfNeeded() + onChromeHiddenChange?(activeConversation != nil || isSidebarOpen) + if !launchLogoEntered { + withAnimation(.easeOut(duration: 0.36)) { + launchLogoEntered = true } + } + } + .onChange(of: activeConversation) { _, _ in + onChromeHiddenChange?(activeConversation != nil || isSidebarOpen) + } + .onChange(of: isSidebarOpen) { _, _ in + onChromeHiddenChange?(activeConversation != nil || isSidebarOpen) + } + .onChange(of: attentionCenter?.pendingNavigationConversation) { _, _ in + consumePendingNavigationIfNeeded() + } + .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 ? 30 : 4)) + try? await Task.sleep(for: .seconds(list.errorMessage == nil ? 25 : 4)) } } } - private var groups: [ProjectGroup] { - ProjectGroup.make(conversations: list.items ?? [], projects: projects ?? []) + // MARK: - Minimal, Focused AI Chat Landing View + + 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) + } + } + .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 + } + 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))) + } + + landingPromptBar + .opacity(isLaunchRevealed ? 1 : 0) + .scaleEffect(isLaunchRevealed ? 1 : 0.85) + .offset(y: isLaunchRevealed ? 0 : -195) + .blur(radius: isLaunchRevealed ? 0 : 6) + } + .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() + } + } 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("打开侧边栏") + + Spacer() + + HStack(spacing: 5) { + Circle() + .fill(isConnected ? Color.green : Color.orange) + .frame(width: 6, height: 6) + Text(isConnected ? "已连接" : "连接中") + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(.secondary) + } + + 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) + } + + 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) + + 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)) + } + .foregroundStyle(.secondary) + } + + Image(systemName: "chevron.up.chevron.down") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.tertiary) + .padding(.leading, 2) + } + .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 func group(id: String) -> ProjectGroup { - groups.first { $0.id == id } ?? ProjectGroup(id: id, name: "", conversations: []) + 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) + } + } + .padding(.horizontal, 14) + } } - @ViewBuilder - private var content: some View { - if let items = list.items { - if items.isEmpty { - ContentUnavailableView("最近没有对话", systemImage: "bubble.left.and.bubble.right") - } else if projects == nil { - // The Host did not describe its projects; fall back to one flat list. - List(items) { item in - NavigationLink(value: item) { ConversationRow(item: item) } + // 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) + } + } + .padding(3) + .background( + Capsule(style: .continuous) + .fill(Color(.tertiarySystemFill)) + ) + + Spacer() + + Button { + withAnimation(.spring(response: 0.26, dampingFraction: 0.86)) { + 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("新对话") + } + .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) } - .refreshable { await reload() } + } + .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) + } + } + .refreshable { + await reload() + } + } + .frame(width: 304) + .frame(maxHeight: .infinity) + .background( + Color(.secondarySystemGroupedBackground) + .ignoresSafeArea() + ) + .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) + } + + // MARK: Sidebar Tab 1: 最近对话 + + private var sidebarConversationsContent: some View { + let q = sidebarSearchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + let nonEmptyGroups = groups.filter { !$0.conversations.isEmpty } + + return VStack(alignment: .leading, spacing: 14) { + if nonEmptyGroups.isEmpty { + Text("暂无对话记录") + .font(.system(size: 13)) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity) + .padding(.vertical, 32) } else { - List(groups) { group in - NavigationLink(value: ProjectRoute(id: group.id)) { ProjectRow(group: group) } + 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 !filteredConvs.isEmpty { + VStack(alignment: .leading, spacing: 4) { + Text(group.name) + .font(.system(size: 11.5, weight: .semibold)) + .foregroundStyle(.secondary) + .padding(.horizontal, 16) + + VStack(spacing: 2) { + ForEach(filteredConvs) { item in + sidebarConversationRow(item) + } + } + .padding(.horizontal, 8) + } + } } - .refreshable { await reload() } } - } else if let message = list.errorMessage { - LoadFailureView(message: message) { Task { await reload() } } - } else { - ProgressView() } } - private func reload() async { - projects = try? await client.projects() - await list.load { - try await client.call( - "conversation_list_recent", - args: ["sinceDays": 30, "limit": 100], - as: [ConversationListItem].self + private func sidebarConversationRow(_ item: ConversationListItem) -> some View { + let isCurrent = activeConversation?.id == item.id + return Button { + withAnimation(.spring(response: 0.26, dampingFraction: 0.86)) { + 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: 4) + + if let date = item.updatedAt { + Text(relativeChinese(date)) + .font(.system(size: 10.5)) + .foregroundStyle(.tertiary) + .layoutPriority(1) + } + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + .background( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(isCurrent ? Color.accentColor.opacity(0.12) : Color.clear) ) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .contextMenu { + Button { + archiveSingleConversation(item) + } label: { + Label("归档对话", systemImage: "archivebox") + } + Button(role: .destructive) { + deleteSingleConversation(item) + } label: { + Label("删除对话", systemImage: "trash") + } } } -} -private struct ProjectRoute: Hashable { let id: String } + // MARK: Sidebar Tab 2: 项目文件 -extension ConversationListItem: Hashable { - public func hash(into hasher: inout Hasher) { hasher.combine(id) } -} + 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) + } -private struct ProjectConversationsView: View { - let client: HostClient - let group: ProjectGroup - let projects: [ProjectSummary] - let onRefresh: () async -> Void + 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) - @State private var agents: [CatalogAgent] = [] - @State private var created: ConversationListItem? - @State private var errorMessage: String? + Image(systemName: "folder") + .font(.system(size: 13.5)) + .foregroundStyle(.secondary) - var body: some View { - List(group.conversations) { item in - NavigationLink(value: item) { ConversationRow(item: item) } - } - .overlay { - if group.conversations.isEmpty { - ContentUnavailableView("这个项目还没有对话", systemImage: "bubble.left.and.bubble.right") - } - } - .navigationTitle(group.name) - .navigationBarTitleDisplayMode(.inline) - .toolbar { - if let workspace = workspaceID, group.id != "other" { - ToolbarItem(placement: .primaryAction) { - Menu { - ForEach(agents.filter(\.usable)) { agent in - Button(agent.displayName) { create(agent: agent, workspace: workspace) } + Text(group.name) + .font(.system(size: 13.5, weight: .medium)) + .foregroundStyle(.primary) + .lineLimit(1) + + Spacer(minLength: 4) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + if let ws { + Button { + isSidebarOpen = false + activeFileBrowserWorkspace = WorkspaceSheetTarget( + workspaceID: ws, + title: group.name + ) + } 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)) + ) + } + .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()) + } + .buttonStyle(.plain) + } + } } - } label: { - Image(systemName: "square.and.pencil") } - .accessibilityLabel("新对话") - .disabled(agents.allSatisfy { !$0.usable }) } + .padding(.horizontal, 8) } } - .safeAreaInset(edge: .bottom) { - if let errorMessage { - Text(errorMessage) - .font(.footnote) - .foregroundStyle(.red) - .padding(.horizontal, 16) - .padding(.vertical, 8) + } + + 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 + } + projectEntriesByWorkspace[workspaceID] = sorted } } - .navigationDestination(item: $created) { ConversationDetailView(client: client, conversation: $0) } - .refreshable { await onRefresh() } - .task { agents = (try? await client.agentCatalog()) ?? [] } } - /// New conversations go to the project's most recently used workspace. - private var workspaceID: String? { - group.conversations.first?.workspace_id - ?? projects.first { $0.id == group.id }?.workspaceIds.first + // MARK: - Landing PromptBar Integration + + private var landingModelChoices: [PromptChoice] { + guard let agent = currentAgent else { return [] } + let options = agent.modelOptions + let choices = options.flatMap { option in + option.choices.map { choice in + let id = "\(agent.id)|\(option.key)|\(choice.id)" + let isDefaultSelected = selectedModelChoiceID == nil && choice.value == option.value + return PromptChoice( + id: id, + title: choice.label, + tag: choice.description, + agentID: agent.id, + selected: selectedModelChoiceID == id || isDefaultSelected + ) + } + } + if choices.isEmpty { + return usableAgents.map { item in + PromptChoice( + id: "agent|\(item.id)", + title: AgentBrand.displayName(item.id, hostName: item.displayName), + agentID: item.id, + selected: item.id == agent.id + ) + } + } + return choices + } + + private var landingOtherModelGroups: [PromptGroup] { + let currentID = currentAgent?.id + return usableAgents.filter { $0.id != currentID }.map { agent in + let modelItems = agent.modelOptions.flatMap(\.choices) + let choices: [PromptChoice] = modelItems.isEmpty + ? [ + PromptChoice( + id: "switch-agent|\(agent.id)", + title: AgentBrand.displayName(agent.id, hostName: agent.displayName), + agentID: agent.id, + selected: false, + enabled: true + ), + ] + : modelItems.map { choice in + PromptChoice( + id: "switch-agent|\(agent.id)|\(choice.id)", + title: choice.label, + tag: choice.description, + agentID: agent.id, + selected: false, + enabled: true + ) + } + return PromptGroup( + title: AgentBrand.displayName(agent.id, hostName: agent.displayName), + agentID: agent.id, + choices: choices + ) + } } - private func create(agent: CatalogAgent, workspace: String) { + private var landingCurrentModelLabel: String? { + if let selectedID = selectedModelChoiceID, + let match = landingModelChoices.first(where: { $0.id == selectedID }) { + return match.title + } + if let firstSelected = landingModelChoices.first(where: \.selected) { + return firstSelected.title + } + if let agent = currentAgent { + return AgentBrand.displayName(agent.id, hostName: agent.displayName) + } + return "Claude Code" + } + + private var landingAccessChoices: [PromptChoice] { + if let agent = currentAgent, !agent.modes.isEmpty { + let activeID = selectedAccessModeID ?? agent.currentModeID ?? agent.modes.first?.id + return agent.modes.map { mode in + PromptChoice( + id: mode.id, + title: mode.label, + detail: mode.description, + icon: "shield", + selected: mode.id == activeID + ) + } + } + let activeID = selectedAccessModeID ?? "auto" + return [ + PromptChoice( + id: "manual", + title: "Manual", + detail: "Always ask before making changes", + icon: "shield", + selected: activeID == "manual" + ), + PromptChoice( + id: "accept_edits", + title: "Accept edits", + detail: "Automatically accept all file edits", + icon: "shield", + selected: activeID == "accept_edits" + ), + PromptChoice( + id: "plan", + title: "Plan", + detail: "Create a plan before making changes", + icon: "shield", + selected: activeID == "plan" + ), + PromptChoice( + id: "auto", + title: "Auto", + detail: "Agent handles permission decisions", + icon: "shield", + selected: activeID == "auto" + ), + PromptChoice( + id: "bypass", + title: "Bypass permissions", + detail: "Accepts all permissions", + icon: "shield", + selected: activeID == "bypass" + ), + ] + } + + private var landingEffortOption: ConfigOption? { + currentAgent?.otherOptions.first { + $0.category == "thought_level" + || $0.key.localizedCaseInsensitiveContains("effort") + || $0.key.localizedCaseInsensitiveContains("reasoning") + } + } + + private var landingEffort: PromptEffort? { + if let option = landingEffortOption, option.choices.count > 1 { + let defaultIdx = option.choices.firstIndex(where: { $0.value == option.value }) ?? 0 + let idx = min(max(selectedEffortIndex ?? defaultIdx, 0), option.choices.count - 1) + return PromptEffort(levels: option.choices.map(\.label), index: idx) + } + let levels = ["Low", "Medium", "High"] + let idx = min(max(selectedEffortIndex ?? 1, 0), levels.count - 1) + return PromptEffort(levels: levels, index: idx) + } + + private var landingPromptBar: some View { + PromptBar( + draft: $draft, + menu: $composerMenu, + isRunning: isCreatingAndSending, + busy: isCreatingAndSending, + hasAlert: false, + modelName: landingCurrentModelLabel, + agentID: currentAgent?.id ?? "claude_code", + modelChoices: landingModelChoices, + otherModelGroups: landingOtherModelGroups, + otherAgentNote: nil, + accessChoices: landingAccessChoices, + extraChoices: [], + effort: landingEffort, + openFiles: { + if let ws = currentWorkspaceID { + activeFileBrowserWorkspace = WorkspaceSheetTarget( + workspaceID: ws, + title: currentGroup?.name ?? "文件" + ) + } + }, + send: { + startNewConversation(with: draft) + }, + stop: {}, + pickModel: { id in + if id.hasPrefix("switch-agent|") { + let parts = id.split(separator: "|").map(String.init) + if parts.count >= 2 { + selectedAgentID = parts[1] + selectedModelChoiceID = nil + } + } else if id.hasPrefix("agent|") { + selectedAgentID = String(id.dropFirst("agent|".count)) + selectedModelChoiceID = nil + } else { + selectedModelChoiceID = id + } + composerMenu = nil + }, + pickAccess: { id in + selectedAccessModeID = id + composerMenu = nil + }, + pickExtra: { _ in }, + setEffort: { index in + selectedEffortIndex = index + } + ) + } + + private func startNewConversation(with text: String) { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, !isCreatingAndSending else { return } + guard let workspaceID = currentWorkspaceID else { + actionErrorMessage = "当前没有可用项目工作区,请先在桌面端导入项目" + return + } + let agentID = currentAgent?.id ?? visibleConversations.first?.agent_id ?? "claude_code" + + isCreatingAndSending = true + actionErrorMessage = nil + dismissKeyboard() + Task { + defer { isCreatingAndSending = false } do { - created = try await client.createConversation(workspaceID: workspace, agentID: agent.id) - errorMessage = nil + let created = try await client.createConversation( + workspaceID: workspaceID, + agentID: agentID + ) + try await client.sendMessage( + conversationID: created.id, + workspaceID: workspaceID, + agentID: agentID, + text: trimmed + ) + draft = "" + withAnimation(.smooth(duration: 0.22)) { + activeConversation = created + } + await reload() } catch { - errorMessage = describeHostFailure(error) + actionErrorMessage = describeHostFailure(error) } } } -} -private struct ProjectRow: View { - let group: ProjectGroup + // MARK: - Project Picker Sheet - var body: some View { - HStack(spacing: 12) { - Image(systemName: group.id == "other" ? "tray" : "folder") - .font(.system(size: 18)) - .foregroundStyle(.secondary) - .frame(width: 26) - VStack(alignment: .leading, spacing: 4) { - Text(group.name).lineLimit(1) - HStack(spacing: 8) { - Text("\(group.conversations.count) 个对话") - if let date = group.latest { - Text(date, format: .relative(presentation: .named)) + 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) + } + } + + 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("关闭") { showProjectPickerSheet = false } } - .font(.footnote) - .foregroundStyle(.secondary) } } } -} -private struct ConversationRow: View { - let item: ConversationListItem + // MARK: - Helpers & Data Loading - var body: some View { - VStack(alignment: .leading, spacing: 4) { - Text(item.title ?? "未命名对话").lineLimit(1) - HStack(spacing: 8) { - if let date = item.updatedAt { - Text(date, format: .relative(presentation: .named)) - } - Text("\(item.message_count) 条消息") - if let model = item.model { Text(model).lineLimit(1) } + private func consumePendingNavigationIfNeeded() { + guard let target = attentionCenter?.pendingNavigationConversation else { return } + attentionCenter?.pendingNavigationConversation = nil + isSidebarOpen = false + withAnimation(.smooth(duration: 0.2)) { + activeConversation = target + } + } + + private func archiveSingleConversation(_ item: ConversationListItem) { + let id = item.id + withAnimation { + _ = removedConversationIDs.insert(id) + if activeConversation?.id == id { + activeConversation = nil + } + } + Task { + do { + try await client.archiveConversation(conversationID: id) + actionErrorMessage = nil + await reload() + } catch { + withAnimation { _ = removedConversationIDs.remove(id) } + actionErrorMessage = describeHostFailure(error) + } + } + } + + private func deleteSingleConversation(_ item: ConversationListItem) { + let id = item.id + withAnimation { + _ = removedConversationIDs.insert(id) + if activeConversation?.id == id { + activeConversation = nil + } + } + Task { + do { + try await client.deleteConversation(conversationID: id) + actionErrorMessage = nil + await reload() + } catch { + withAnimation { _ = removedConversationIDs.remove(id) } + actionErrorMessage = describeHostFailure(error) + } + } + } + + 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( + "conversation_list_recent", + args: ["sinceDays": 30, "limit": 100], + as: [ConversationListItem].self + ) + let activeIDs = Set(fetched.map(\.id)) + removedConversationIDs.formIntersection(activeIDs) + if let current = activeConversation, + let updated = fetched.first(where: { $0.id == current.id }) { + activeConversation = updated } - .font(.footnote) - .foregroundStyle(.secondary) + return fetched } } } + +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) } +} + +private func relativeChinese(_ date: Date) -> String { + date.formatted(.relative(presentation: .named).locale(Locale(identifier: "zh_Hans_CN"))) +} diff --git a/mobile/ios/App/FilesView.swift b/mobile/ios/App/FilesView.swift index f4cadcd38..b965af9db 100644 --- a/mobile/ios/App/FilesView.swift +++ b/mobile/ios/App/FilesView.swift @@ -1,13 +1,61 @@ import CompanionCore import SwiftUI +private enum FilesRoute: Hashable { + case project(workspaceID: String, title: String) + case directory(workspaceID: String, path: String) + case file(workspaceID: String, path: String) +} + struct FilesView: View { let client: HostClient - @State private var list = RemoteList() + @State private var list = RemoteList() + @State private var stack: [FilesRoute] = [] + @State private var diffWorkspaceID: String? + @State private var searchQuery = "" var body: some View { - NavigationStack { - content.navigationTitle("文件") + NavigationStack(path: $stack) { + content + .navigationTitle("文件") + .navigationDestination(for: FilesRoute.self) { route in + switch route { + case .project(let workspaceID, let title): + DirectoryView( + client: client, + workspaceID: workspaceID, + path: "", + rootTitle: title, + navigate: { push($0, workspaceID: workspaceID) } + ) + .toolbar { + ToolbarItem(placement: .primaryAction) { + Button { + diffWorkspaceID = workspaceID + } label: { + Label("代码差异", systemImage: "plus.forwardslash.minus") + } + } + } + case .directory(let workspaceID, let path): + DirectoryView( + client: client, + workspaceID: workspaceID, + path: path, + navigate: { push($0, workspaceID: workspaceID) } + ) + case .file(let workspaceID, let path): + FileContentView(client: client, workspaceID: workspaceID, path: path) + } + } + } + .sheet(isPresented: Binding( + get: { diffWorkspaceID != nil }, + set: { if !$0 { diffWorkspaceID = nil } } + )) { + if let workspaceID = diffWorkspaceID { + DiffListView(client: client, workspaceID: workspaceID) + } } .task { while !Task.isCancelled { @@ -17,23 +65,79 @@ struct FilesView: View { } } + private var groups: [ProjectGroup] { + ProjectGroup.make(conversations: [], projects: list.items ?? []) + } + + private var searchResults: [SearchResultItem] { + let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !q.isEmpty else { return [] } + return groups.compactMap { group in + guard group.name.lowercased().contains(q) || group.rootPath.lowercased().contains(q), + let workspaceID = group.workspaceIds.first + else { return nil } + return SearchResultItem( + id: group.id, + title: group.name, + subtitle: group.rootPath, + icon: group.isGit ? "arrow.triangle.branch" : "folder", + action: { stack.append(.project(workspaceID: workspaceID, title: group.name)) } + ) + } + } + @ViewBuilder private var content: some View { if let items = list.items { if items.isEmpty { - ContentUnavailableView("还没有 Agent 生成的文件", systemImage: "folder") + ContentUnavailableView("还没有已导入项目", systemImage: "folder") } else { - List(items) { item in - VStack(alignment: .leading, spacing: 4) { - Text(item.fileName).lineLimit(1) - HStack(spacing: 8) { - Text(item.updatedAt, format: .relative(presentation: .named)) - Text(item.media_type).lineLimit(1) + List { + Section { + SearchListCard( + query: $searchQuery, + placeholder: "搜索项目…", + results: searchResults + ) + } + .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 4, trailing: 0)) + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + + Section { + ForEach(groups) { group in + if let workspaceID = group.workspaceIds.first { + NavigationLink(value: FilesRoute.project(workspaceID: workspaceID, title: group.name)) { + ImportedProjectRow(group: group) + } + .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) + .swipeActions(edge: .trailing) { + Button { + diffWorkspaceID = workspaceID + } label: { + Label("代码差异", systemImage: "plus.forwardslash.minus") + } + .tint(.orange) + } + } else { + ImportedProjectRow(group: group) + .listRowInsets(EdgeInsets(top: 8, leading: 14, bottom: 8, trailing: 14)) + } } - .font(.footnote) + } header: { + HStack(spacing: 6) { + Text("项目") + Text("\(groups.count)").foregroundStyle(.tertiary) + } + .font(.footnote.weight(.semibold)) .foregroundStyle(.secondary) + .textCase(nil) + .padding(.leading, -6) } } + .listSectionSpacing(14) + .contentMargins(.top, 2, for: .scrollContent) + .scrollDismissesKeyboard(.immediately) .refreshable { await reload() } } } else if let message = list.errorMessage { @@ -43,9 +147,58 @@ struct FilesView: View { } } + private func push(_ target: BrowseTarget, workspaceID: String) { + switch target { + case .directory(let path): + stack.append(.directory(workspaceID: workspaceID, path: path)) + case .file(let path): + stack.append(.file(workspaceID: workspaceID, path: path)) + } + } + private func reload() async { await list.load { - try await client.call("artifact_list", args: ["limit": 100], as: [ArtifactListItem].self) + try await client.projects() + } + } +} + +private struct ImportedProjectRow: View { + let group: ProjectGroup + + private var tint: Color { + if group.isHome { return .teal } + return group.isGit ? .orange : .blue + } + + private var displayPath: String { + // Collapse the macOS home prefix to "~" so paths stay readable. + if let range = group.rootPath.range(of: #"^/Users/[^/]+"#, options: .regularExpression) { + return "~" + group.rootPath[range.upperBound...] + } + return group.rootPath + } + + var body: some View { + HStack(spacing: 11) { + Image(systemName: group.isHome ? "house" : (group.isGit ? "arrow.triangle.branch" : "folder")) + .font(.system(size: 14, weight: .semibold)) + .foregroundStyle(tint) + .frame(width: 30, height: 30) + .background(tint.opacity(0.13), in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + VStack(alignment: .leading, spacing: 2) { + Text(group.name) + .font(.body.weight(.medium)) + .lineLimit(1) + if !group.rootPath.isEmpty { + Text(displayPath) + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.head) + } + } } + .padding(.leading, CGFloat(group.depth) * 18) } } diff --git a/mobile/ios/App/InteractionEnhancer.swift b/mobile/ios/App/InteractionEnhancer.swift new file mode 100644 index 000000000..e77a12c66 --- /dev/null +++ b/mobile/ios/App/InteractionEnhancer.swift @@ -0,0 +1,137 @@ +import SwiftUI +import UIKit + +extension Notification.Name { + static let vibexTapOutsideInput = Notification.Name("vibex.tapOutsideInput") +} + +@MainActor +func dismissKeyboard() { + UIApplication.shared.sendAction( + #selector(UIResponder.resignFirstResponder), + to: nil, + from: nil, + for: nil + ) +} + +/// Window-level interaction enhancer that: +/// 1. Dismisses the keyboard and notifies active search bars when tapping any blank / non-input area. +/// 2. Keeps interactive pop gesture (edge swipe to go back) enabled across NavigationStacks. +struct GlobalInteractionInstaller: UIViewRepresentable { + func makeCoordinator() -> Coordinator { + Coordinator() + } + + func makeUIView(context: Context) -> InstallerView { + let view = InstallerView() + view.coordinator = context.coordinator + return view + } + + func updateUIView(_ uiView: InstallerView, context: Context) { + uiView.coordinator = context.coordinator + uiView.installIfNeeded() + } + + final class InstallerView: UIView { + weak var coordinator: Coordinator? + + override func didMoveToWindow() { + super.didMoveToWindow() + installIfNeeded() + } + + func installIfNeeded() { + guard let window else { return } + coordinator?.attach(to: window) + } + } + + final class Coordinator: NSObject, UIGestureRecognizerDelegate { + private weak var attachedWindow: UIWindow? + private var tapRecognizer: UITapGestureRecognizer? + + func attach(to window: UIWindow) { + if attachedWindow === window, tapRecognizer != nil { + enableInteractivePopInHierarchy(from: window.rootViewController) + return + } + + if let oldTap = tapRecognizer, let oldWindow = attachedWindow { + oldWindow.removeGestureRecognizer(oldTap) + } + + let tap = UITapGestureRecognizer(target: self, action: #selector(handleWindowTap(_:))) + tap.cancelsTouchesInView = false + tap.delaysTouchesBegan = false + tap.delaysTouchesEnded = false + tap.delegate = self + window.addGestureRecognizer(tap) + + self.attachedWindow = window + self.tapRecognizer = tap + enableInteractivePopInHierarchy(from: window.rootViewController) + } + + @objc private func handleWindowTap(_ recognizer: UITapGestureRecognizer) { + guard recognizer.state == .ended, let window = attachedWindow else { return } + let location = recognizer.location(in: window) + let hitView = window.hitTest(location, with: nil) + let insideTextInput = Self.isInsideTextInput(hitView) + + NotificationCenter.default.post( + name: .vibexTapOutsideInput, + object: nil, + userInfo: [ + "location": NSValue(cgPoint: location), + "insideTextInput": insideTextInput, + ] + ) + + if !insideTextInput { + window.endEditing(true) + } + + enableInteractivePopInHierarchy(from: window.rootViewController) + } + + func gestureRecognizer( + _ gestureRecognizer: UIGestureRecognizer, + shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer + ) -> Bool { + true + } + + private static func isInsideTextInput(_ view: UIView?) -> Bool { + var current = view + while let v = current { + if v is UITextField || v is UITextView { + return true + } + let typeName = String(describing: type(of: v)) + if typeName.contains("TextField") || typeName.contains("SearchBar") { + return true + } + current = v.superview + } + return false + } + + private func enableInteractivePopInHierarchy(from root: UIViewController?) { + guard let root else { return } + if let nav = root as? UINavigationController { + nav.interactivePopGestureRecognizer?.isEnabled = true + if nav.viewControllers.count > 1 { + nav.interactivePopGestureRecognizer?.delegate = nil + } + } + for child in root.children { + enableInteractivePopInHierarchy(from: child) + } + if let presented = root.presentedViewController { + enableInteractivePopInHierarchy(from: presented) + } + } + } +} diff --git a/mobile/ios/App/KanbanUsageDashboardView.swift b/mobile/ios/App/KanbanUsageDashboardView.swift new file mode 100644 index 000000000..49c183722 --- /dev/null +++ b/mobile/ios/App/KanbanUsageDashboardView.swift @@ -0,0 +1,865 @@ +import CompanionCore +import SwiftUI + +struct KanbanUsageDashboardView: View { + let client: HostClient + let projects: [ProjectSummary] + let initialProjectID: String? + + @State private var selectedTarget: String = "global" + @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 + let sourceNote: String + + static let all: [PlanAgentDescriptor] = [ + PlanAgentDescriptor( + id: "claude_code", + title: "Claude Code 套餐", + sourceNote: "读取设置里的 Claude 订阅凭据" + ), + PlanAgentDescriptor( + id: "codex", + title: "Codex 套餐", + sourceNote: "读取已安装的 Codex 与账号限额" + ), + PlanAgentDescriptor( + id: "cursor", + title: "Cursor 套餐", + sourceNote: "读取本机 Cursor 登录凭据与官方用量接口" + ), + PlanAgentDescriptor( + id: "grok", + title: "Grok 套餐", + sourceNote: "读取本机 Grok 登录凭据与官方套餐接口" + ), + PlanAgentDescriptor( + id: "opencode", + title: "OpenCode Go 套餐", + sourceNote: "读取 OpenCode Go 订阅凭据与官方用量接口" + ), + PlanAgentDescriptor( + id: "kimi_code", + title: "Kimi 套餐", + sourceNote: "读取 Kimi Code 订阅凭据与官方用量接口" + ), + PlanAgentDescriptor( + id: "antigravity", + title: "Antigravity 套餐", + sourceNote: "读取设置里的 Antigravity 订阅凭据" + ), + ] + } + + var body: some View { + VStack(spacing: 0) { + filterHeader + Divider() + subTabBar + Divider() + + if activeTab == .plan { + planTabContent + } else if isLoading && statistics == nil { + Spacer() + ProgressView("正在加载计量统计…") + Spacer() + } else if let errorMessage, statistics == nil { + Spacer() + LoadFailureView(message: errorMessage) { + Task { await reloadStatistics() } + } + 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() + } + } + .padding(16) + } + .refreshable { + await reloadStatistics() + } + } else { + Spacer() + ContentUnavailableView("暂无数据", systemImage: "chart.bar.xaxis") + Spacer() + } + } + .task(id: "\(selectedTarget)-\(dateRange.rawValue)") { + await reloadStatistics() + } + .task(id: activeTab) { + if activeTab == .plan { + await loadPlanUsage(for: selectedPlanAgent.id) + } + } + .onAppear { + if let initialProjectID, !initialProjectID.isEmpty, selectedTarget == "global" { + selectedTarget = "project:\(initialProjectID)" + } + } + } + + // MARK: - Header Controls + + private var filterHeader: some View { + HStack(spacing: 10) { + 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") } + } + } + } + } label: { + HStack(spacing: 5) { + Image(systemName: selectedTarget == "global" ? "globe" : "folder") + .font(.caption) + 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()) + } + .buttonStyle(.plain) + + Spacer() + + if activeTab != .plan { + Picker("时间范围", selection: $dateRange) { + ForEach(UsageDateRange.allCases) { range in + Text(range.label).tag(range) + } + } + .pickerStyle(.segmented) + .frame(width: 156) + } + + Button { + Task { + if activeTab == .plan { + await loadPlanUsage(for: selectedPlanAgent.id, force: true) + } else { + await reloadStatistics() + } + } + } label: { + Image(systemName: "arrow.clockwise") + .font(.subheadline.weight(.medium)) + .frame(width: 30, height: 30) + .background(Color(.secondarySystemGroupedBackground), in: Circle()) + } + .buttonStyle(.plain) + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + .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 ?? "当前项目" + } + + private var subTabBar: some View { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + ForEach(UsageDashboardTab.allCases) { tab in + let isSelected = activeTab == tab + Button { + withAnimation(.easeInOut(duration: 0.18)) { + activeTab = tab + } + } label: { + HStack(spacing: 5) { + Image(systemName: tab.icon) + .font(.caption) + Text(tab.label) + .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) + } + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + } + .background(Color(.systemGroupedBackground)) + } + + // MARK: - Overview Tab + + @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)))/会话" + : "按协议与日志估算", + 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", + icon: "cpu.fill", + tint: .purple + ) + metricCard( + title: "缓存命中率", + value: stats.cacheHitRatePercent.map { String(format: "%.1f%%", $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) { + HStack { + Text("用量趋势") + .font(.subheadline.weight(.semibold)) + Spacer() + Text("\(stats.dailyUsage.count) 天") + .font(.caption) + .foregroundStyle(.secondary) + } + + let maxTokens = max( + 1, + stats.dailyUsage.map { $0.tokens.preferred.resolvedTotal }.max() ?? 1 + ) + + ForEach(stats.dailyUsage.suffix(14).reversed()) { day in + let dayTokens = day.tokens.preferred.resolvedTotal + VStack(spacing: 4) { + HStack { + Text(day.date) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + Spacer() + Text("\(day.sessions) 会话") + .font(.caption2) + .foregroundStyle(.secondary) + Text("\(Self.formatTokens(dayTokens)) Token") + .font(.caption.monospacedDigit().weight(.medium)) + if let cost = day.cost { + Text(Self.formatCost(cost)) + .font(.caption.monospacedDigit()) + .foregroundStyle(.green) + } + } + GeometryReader { geo in + ZStack(alignment: .leading) { + Capsule() + .fill(Color(.systemFill)) + Capsule() + .fill(Color.accentColor) + .frame( + width: dayTokens > 0 + ? max(4, geo.size.width * CGFloat(Double(dayTokens) / Double(maxTokens))) + : 0 + ) + } + } + .frame(height: 6) + } + } + } + .padding(14) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14)) + } + + // 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) { + AgentModelLabel(agent: AgentBrand.inferAgent(fromModel: item.model), model: item.model) + .font(.footnote.weight(.medium)) + Spacer() + Text("\(item.sessionCount) 会话") + .font(.caption) + .foregroundStyle(.secondary) + 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)) + } + } + .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) + } + .padding(12) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 12)) + } + } + } + } + + // MARK: - Plan Usage Tab + + private var planTabContent: some View { + ScrollView { + VStack(alignment: .leading, spacing: 16) { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + ForEach(PlanAgentDescriptor.all) { descriptor in + let isSelected = selectedPlanAgent.id == descriptor.id + Button { + selectedPlanAgent = descriptor + Task { await loadPlanUsage(for: descriptor.id) } + } label: { + HStack(spacing: 5) { + 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() + ) + } + .buttonStyle(.plain) + } + } + } + + VStack(alignment: .leading, spacing: 12) { + HStack { + VStack(alignment: .leading, spacing: 3) { + Text(selectedPlanAgent.title) + .font(.headline) + Text(selectedPlanAgent.sourceNote) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + if case .ok(let usage) = planUsageByAgent[selectedPlanAgent.id], + let planType = usage.planType, !planType.isEmpty + { + Text("\(planType.uppercased()) 套餐") + .font(.caption.weight(.semibold)) + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background(Color.accentColor.opacity(0.15), in: Capsule()) + } + } + + if isLoadingPlan && planUsageByAgent[selectedPlanAgent.id] == nil { + HStack { + Spacer() + ProgressView("正在读取额度…") + Spacer() + } + .padding(.vertical, 24) + } else if let response = planUsageByAgent[selectedPlanAgent.id] { + switch response { + case .ok(let usage): + if usage.windows.isEmpty { + Text("账号未返回任何限额窗口") + .font(.footnote) + .foregroundStyle(.secondary) + .padding(.vertical, 12) + } else { + ForEach(usage.windows) { window in + planWindowRow(window) + } + } + if let credits = usage.credits { + HStack(spacing: 8) { + Image(systemName: "creditcard") + .foregroundStyle(.secondary) + Text( + credits.unlimited + ? "额度不限量" + : "赠送额度余额:\(credits.balance ?? "--")" + ) + .font(.footnote) + .foregroundStyle(.secondary) + } + .padding(10) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Color(.tertiarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 10)) + } + case .unavailable: + HStack(spacing: 8) { + Image(systemName: "info.circle") + .foregroundStyle(.secondary) + Text(response.unavailableDescription ?? "暂不可用") + .font(.footnote) + .foregroundStyle(.secondary) + } + .padding(.vertical, 12) + case .error(let msg): + HStack(spacing: 8) { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(.orange) + Text(msg) + .font(.footnote) + .foregroundStyle(.secondary) + } + .padding(.vertical, 12) + } + } + } + .padding(16) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14)) + } + .padding(16) + } + } + + @ViewBuilder + private func planWindowRow(_ window: PlanUsageWindow) -> some View { + let used = window.clampedUsedPercent + let remaining = window.remainingPercent + let barColor: Color = { + guard let used else { return .accentColor } + if used >= 90 { return .red } + if used >= 70 { return .orange } + return .accentColor + }() + + VStack(alignment: .leading, spacing: 8) { + HStack(alignment: .top) { + VStack(alignment: .leading, spacing: 2) { + Text(window.localizedTitle) + .font(.subheadline.weight(.semibold)) + if let reset = window.resetLabel() { + Text(reset) + .font(.caption) + .foregroundStyle(.secondary) + } + } + Spacer() + VStack(alignment: .trailing, spacing: 2) { + Text(used.map { "已用 \($0)%" } ?? "--") + .font(.subheadline.monospacedDigit().weight(.semibold)) + Text(remaining.map { "剩余 \($0)%" } ?? "--") + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + } + GeometryReader { geo in + ZStack(alignment: .leading) { + Capsule() + .fill(Color(.systemFill)) + Capsule() + .fill(barColor) + .frame(width: geo.size.width * CGFloat(Double(used ?? 0) / 100.0)) + } + } + .frame(height: 8) + } + .padding(12) + .background(Color(.tertiarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 10)) + } + + // MARK: - Helpers + + private func metricCard( + title: String, + value: String, + subtitle: String, + icon: String, + tint: Color + ) -> some View { + VStack(alignment: .leading, spacing: 6) { + HStack { + Image(systemName: icon) + .foregroundStyle(tint) + .font(.subheadline) + Text(title) + .font(.caption) + .foregroundStyle(.secondary) + Spacer() + } + Text(value) + .font(.title3.monospacedDigit().weight(.bold)) + .lineLimit(1) + .minimumScaleFactor(0.75) + Text(subtitle) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + .padding(12) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 14)) + } + + private func reloadStatistics() async { + isLoading = true + defer { isLoading = false } + let scope = selectedTarget == "global" ? "global" : "project" + let projectID = selectedTarget == "global" + ? nil + : selectedTarget.replacingOccurrences(of: "project:", with: "") + do { + statistics = try await client.projectUsageStatistics( + scope: scope, + projectID: projectID, + dateRange: dateRange + ) + errorMessage = nil + } catch { + errorMessage = describeHostFailure(error) + } + } + + private func loadPlanUsage(for agentID: String, force: Bool = false) async { + if !force, planUsageByAgent[agentID] != nil { return } + isLoadingPlan = true + defer { isLoadingPlan = false } + do { + let res = try await client.agentPlanUsage(agentID: agentID) + planUsageByAgent[agentID] = res + } catch { + planUsageByAgent[agentID] = .error(message: describeHostFailure(error)) + } + } + + static func formatCost(_ cost: Double?) -> String { + guard let cost else { return "--" } + if cost == 0 { return "$0.00" } + if cost < 0.01 { return String(format: "$%.4f", cost) } + return String(format: "$%.2f", cost) + } + + static func formatTokens(_ count: Int64) -> String { + if count >= 1_000_000_000 { + return String(format: "%.2fB", Double(count) / 1_000_000_000.0) + } + if count >= 1_000_000 { + return String(format: "%.2fM", Double(count) / 1_000_000.0) + } + if count >= 1_000 { + return String(format: "%.1fK", Double(count) / 1_000.0) + } + return "\(count)" + } +} diff --git a/mobile/ios/App/MemberBotAvatarView.swift b/mobile/ios/App/MemberBotAvatarView.swift new file mode 100644 index 000000000..8e3adb578 --- /dev/null +++ b/mobile/ios/App/MemberBotAvatarView.swift @@ -0,0 +1,909 @@ +import CompanionCore +import SwiftUI + +extension Color { + init?(collabHex raw: String?) { + guard let raw = raw?.trimmingCharacters(in: .whitespacesAndNewlines), !raw.isEmpty else { + return nil + } + let normalized = CollabBotAvatarConfig.normalizeHexColor(raw, fallback: "") + guard normalized.count == 7, normalized.hasPrefix("#"), + let val = Int(normalized.dropFirst(), radix: 16) + else { + return nil + } + self.init( + red: Double((val >> 16) & 0xFF) / 255.0, + green: Double((val >> 8) & 0xFF) / 255.0, + blue: Double(val & 0xFF) / 255.0 + ) + } +} + +// MARK: - Bot Session Emotes (Desktop 12-Emote Sequence) + +enum BotSessionEmote: String, CaseIterable, Sendable { + case idle + case happy + case curious + case excited + case thinking + case nodding + case surprised + case laughing + case focused + case wink + case confused + case sleepy + case proud + + var expression: BotAvatarExpression { + switch self { + case .idle: return .neutral + case .happy: return .happy + case .curious: return .curious + case .excited: return .excited + case .thinking: return .attentive + case .nodding: return .proud + case .surprised: return .surprised + case .laughing: return .laughing + case .focused: return .suspicious + case .wink: return .shy + case .confused: return .confused + case .sleepy: return .sleepy + case .proud: return .proud + } + } + + static let sequence: [BotSessionEmote] = [ + .happy, .curious, .excited, .thinking, .nodding, .surprised, + .laughing, .focused, .wink, .confused, .sleepy, .proud, + ] +} + +// MARK: - Bot Avatar Shape Path (64x64 Coordinate Space, Desktop Parity) + +struct BotAvatarShapePath: Shape { + let shape: BotAvatarShape + + func path(in rect: CGRect) -> Path { + let sx = rect.width / 64.0 + let sy = rect.height / 64.0 + func pt(_ x: CGFloat, _ y: CGFloat) -> CGPoint { + CGPoint(x: rect.minX + x * sx, y: rect.minY + y * sy) + } + + var p = Path() + switch shape { + case .circle: + p.addEllipse(in: CGRect(x: rect.minX + 8 * sx, y: rect.minY + 8 * sy, width: 48 * sx, height: 48 * sy)) + + case .cloud: + p.move(to: pt(20.5, 48.5)) + p.addCurve(to: pt(6.8, 36.2), control1: pt(12, 48.5), control2: pt(6.8, 43.2)) + p.addCurve(to: pt(15.6, 24.8), control1: pt(6.8, 30.8), control2: pt(10.4, 26.2)) + p.addCurve(to: pt(32.8, 10.5), control1: pt(17.1, 16), control2: pt(24.2, 10.5)) + p.addCurve(to: pt(50.8, 25), control1: pt(41.8, 10.5), control2: pt(49.2, 16.5)) + p.addCurve(to: pt(57.2, 35.5), control1: pt(55, 26.8), control2: pt(57.2, 30.8)) + p.addCurve(to: pt(43, 48.5), control1: pt(57.2, 43.2), control2: pt(51, 48.5)) + p.closeSubpath() + + case .squircle: + p.addRoundedRect( + in: CGRect(x: rect.minX + 10.5 * sx, y: rect.minY + 10.5 * sy, width: 43 * sx, height: 43 * sy), + cornerSize: CGSize(width: 10.5 * sx, height: 10.5 * sy), + style: .continuous + ) + + case .sparkle: + p.move(to: pt(32, 6)) + p.addCurve(to: pt(46.2, 21.5), control1: pt(37.5, 6), control2: pt(41.2, 17.5)) + p.addCurve(to: pt(58, 32), control1: pt(51.2, 25.5), control2: pt(58, 27)) + p.addCurve(to: pt(46.2, 42.5), control1: pt(58, 37), control2: pt(51.2, 38.5)) + p.addCurve(to: pt(32, 58), control1: pt(41.2, 46.5), control2: pt(37.5, 58)) + p.addCurve(to: pt(17.8, 42.5), control1: pt(26.5, 58), control2: pt(22.8, 46.5)) + p.addCurve(to: pt(6, 32), control1: pt(12.8, 38.5), control2: pt(6, 37)) + p.addCurve(to: pt(17.8, 21.5), control1: pt(6, 27), control2: pt(12.8, 25.5)) + p.addCurve(to: pt(32, 6), control1: pt(22.8, 17.5), control2: pt(26.5, 6)) + p.closeSubpath() + + case .clover: + p.move(to: pt(32, 13.5)) + p.addCurve(to: pt(13.8, 21.8), control1: pt(24, 5.5), control2: pt(11.2, 10.8)) + p.addCurve(to: pt(13.8, 42.2), control1: pt(6.5, 25.2), control2: pt(6.5, 38.8)) + p.addCurve(to: pt(32, 50.5), control1: pt(11.2, 53.2), control2: pt(24, 58.5)) + p.addCurve(to: pt(50.2, 42.2), control1: pt(40, 58.5), control2: pt(52.8, 53.2)) + p.addCurve(to: pt(50.2, 21.8), control1: pt(57.5, 38.8), control2: pt(57.5, 25.2)) + p.addCurve(to: pt(32, 13.5), control1: pt(52.8, 10.8), control2: pt(40, 5.5)) + p.closeSubpath() + + case .heart: + p.move(to: pt(32, 53.5)) + p.addCurve(to: pt(8.5, 23.2), control1: pt(27.8, 50.6), control2: pt(8.5, 37.8)) + p.addCurve(to: pt(23.8, 8.5), control1: pt(8.5, 13.8), control2: pt(15.8, 8.5)) + p.addCurve(to: pt(32, 13), control1: pt(27.8, 8.5), control2: pt(30.5, 10.5)) + p.addCurve(to: pt(40.2, 8.5), control1: pt(33.5, 10.5), control2: pt(36.2, 8.5)) + p.addCurve(to: pt(55.5, 23.2), control1: pt(48.2, 8.5), control2: pt(55.5, 13.8)) + p.addCurve(to: pt(32, 53.5), control1: pt(55.5, 37.8), control2: pt(36.2, 50.6)) + p.closeSubpath() + + case .pebble: + p.move(to: pt(32, 9)) + p.addCurve(to: pt(42.5, 14), control1: pt(36, 6), control2: pt(42, 8.5)) + p.addCurve(to: pt(50.5, 23.5), control1: pt(48, 13.5), control2: pt(52.5, 18)) + p.addCurve(to: pt(52, 36.5), control1: pt(55.5, 26), control2: pt(56.5, 32.5)) + p.addCurve(to: pt(46, 47.5), control1: pt(55, 41.5), control2: pt(51.5, 47.5)) + p.addCurve(to: pt(34, 52.5), control1: pt(45, 53), control2: pt(39, 56)) + p.addCurve(to: pt(21.5, 49.5), control1: pt(30, 56.5), control2: pt(23.5, 55)) + p.addCurve(to: pt(13.5, 40), control1: pt(16, 50.5), control2: pt(11.5, 45.5)) + p.addCurve(to: pt(12, 27), control1: pt(8.5, 37.5), control2: pt(7.5, 31)) + p.addCurve(to: pt(18, 16), control1: pt(9, 22), control2: pt(12.5, 16)) + p.addCurve(to: pt(30, 11), control1: pt(19, 10.5), control2: pt(25, 7.5)) + p.closeSubpath() + + case .droplet: + p.move(to: pt(32, 7.5)) + p.addCurve(to: pt(53.5, 38.5), control1: pt(36.5, 7.5), control2: pt(53.5, 25.5)) + p.addCurve(to: pt(32, 55.8), control1: pt(53.5, 49.8), control2: pt(44.2, 55.8)) + p.addCurve(to: pt(10.5, 38.5), control1: pt(19.8, 55.8), control2: pt(10.5, 49.8)) + p.addCurve(to: pt(32, 7.5), control1: pt(10.5, 25.5), control2: pt(27.5, 7.5)) + p.closeSubpath() + + case .capsule: + p.addRoundedRect( + in: CGRect(x: rect.minX + 7.5 * sx, y: rect.minY + 15 * sy, width: 49 * sx, height: 34 * sy), + cornerSize: CGSize(width: 17 * sx, height: 17 * sy), + style: .continuous + ) + + case .triangle: + p.move(to: pt(26, 9.5)) + p.addQuadCurve(to: pt(38, 9.5), control: pt(32, 2.5)) + p.addLine(to: pt(55.5, 40)) + p.addQuadCurve(to: pt(50.5, 51.5), control: pt(60.5, 48.5)) + p.addQuadCurve(to: pt(13.5, 51.5), control: pt(32, 55.5)) + p.addQuadCurve(to: pt(8.5, 40), control: pt(3.5, 48.5)) + p.closeSubpath() + + case .pentagon: + p.move(to: pt(27.5, 9.2)) + p.addQuadCurve(to: pt(36.5, 9.2), control: pt(32, 6)) + p.addLine(to: pt(52.5, 20.8)) + p.addQuadCurve(to: pt(54.8, 28.8), control: pt(56.5, 23.8)) + p.addLine(to: pt(48.8, 47.5)) + p.addQuadCurve(to: pt(41.8, 52.5), control: pt(47.2, 52.5)) + p.addLine(to: pt(22.2, 52.5)) + p.addQuadCurve(to: pt(15.2, 47.5), control: pt(16.8, 52.5)) + p.addLine(to: pt(9.2, 28.8)) + p.addQuadCurve(to: pt(11.5, 20.8), control: pt(7.5, 23.8)) + p.closeSubpath() + + case .star: + p.move(to: pt(29, 7.5)) + p.addCurve(to: pt(36.5, 9.5), control1: pt(31.5, 4.5), control2: pt(35.5, 5.5)) + p.addCurve(to: pt(44, 12.5), control1: pt(37.5, 13.5), control2: pt(40.5, 14.5)) + p.addCurve(to: pt(49, 17.2), control1: pt(47.5, 10.5), control2: pt(51, 13.5)) + p.addCurve(to: pt(52.5, 25), control1: pt(47, 21), control2: pt(48.5, 24)) + p.addCurve(to: pt(53.5, 32.5), control1: pt(56.5, 26), control2: pt(57.2, 30.5)) + p.addCurve(to: pt(52, 41), control1: pt(49.8, 34.5), control2: pt(49.5, 37.8)) + p.addCurve(to: pt(48, 46.8), control1: pt(54.5, 44.2), control2: pt(52, 48.2)) + p.addCurve(to: pt(40.5, 51.2), control1: pt(44, 45.4), control2: pt(41, 47.2)) + p.addCurve(to: pt(33, 53), control1: pt(40, 55.2), control2: pt(35.5, 56.5)) + p.addCurve(to: pt(24.5, 52.5), control1: pt(30.5, 49.5), control2: pt(27.5, 49.5)) + p.addCurve(to: pt(18.2, 49.2), control1: pt(21.5, 55.5), control2: pt(17.2, 53.2)) + p.addCurve(to: pt(13.2, 42), control1: pt(19.2, 45.2), control2: pt(17.2, 42.5)) + p.addCurve(to: pt(11.5, 34.8), control1: pt(9.2, 41.5), control2: pt(8, 37)) + p.addCurve(to: pt(12.2, 26.5), control1: pt(15, 32.6), control2: pt(15.2, 29.5)) + p.addCurve(to: pt(15.5, 20.2), control1: pt(9.2, 23.5), control2: pt(11.5, 19.2)) + p.addCurve(to: pt(23, 15.2), control1: pt(19.5, 21.2), control2: pt(22.5, 19.2)) + p.addCurve(to: pt(29, 7.5), control1: pt(23.5, 11.2), control2: pt(26.5, 10.5)) + p.closeSubpath() + + case .hexagon: + p.move(to: pt(27.5, 8)) + p.addQuadCurve(to: pt(36.5, 8), control: pt(32, 5.4)) + p.addLine(to: pt(51.5, 16.8)) + p.addQuadCurve(to: pt(55.5, 24.2), control: pt(55.5, 19.4)) + p.addLine(to: pt(55.5, 39.8)) + p.addQuadCurve(to: pt(51.5, 47.2), control: pt(55.5, 44.6)) + p.addLine(to: pt(36.5, 56)) + p.addQuadCurve(to: pt(27.5, 56), control: pt(32, 58.6)) + p.addLine(to: pt(12.5, 47.2)) + p.addQuadCurve(to: pt(8.5, 39.8), control: pt(8.5, 44.6)) + p.addLine(to: pt(8.5, 24.2)) + p.addQuadCurve(to: pt(12.5, 16.8), control: pt(8.5, 19.4)) + p.closeSubpath() + } + return p + } +} + +// MARK: - Bot Avatar Eyes & Expressions (64x64 Coordinate Space) + +struct BotAvatarFaceView: View { + let expression: BotAvatarExpression + let eyeColor: Color + let size: CGFloat + + var body: some View { + Canvas { ctx, canvasSize in + let sx = canvasSize.width / 64.0 + let sy = canvasSize.height / 64.0 + func pt(_ x: CGFloat, _ y: CGFloat) -> CGPoint { + CGPoint(x: x * sx, y: y * sy) + } + func pill(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, rx: CGFloat) -> Path { + Path( + roundedRect: CGRect(x: x * sx, y: y * sy, width: w * sx, height: h * sy), + cornerSize: CGSize(width: rx * sx, height: rx * sy) + ) + } + + switch expression { + case .happy, .proud: + var left = Path() + left.move(to: pt(21.8, 33.2)) + left.addCurve(to: pt(30.4, 33.2), control1: pt(23.4, 26.8), control2: pt(28.8, 26.8)) + var right = Path() + right.move(to: pt(33.6, 33.2)) + right.addCurve(to: pt(42.2, 33.2), control1: pt(35.2, 26.8), control2: pt(40.6, 26.8)) + let style = StrokeStyle(lineWidth: 4.6 * sx, lineCap: .round) + ctx.stroke(left, with: .color(eyeColor), style: style) + ctx.stroke(right, with: .color(eyeColor), style: style) + + case .laughing: + var left = Path() + left.move(to: pt(21.8, 27.6)) + left.addLine(to: pt(28.4, 31.5)) + left.addLine(to: pt(21.8, 35.4)) + var right = Path() + right.move(to: pt(42.2, 27.6)) + right.addLine(to: pt(35.6, 31.5)) + right.addLine(to: pt(42.2, 35.4)) + let style = StrokeStyle(lineWidth: 4.4 * sx, lineCap: .round, lineJoin: .round) + ctx.stroke(left, with: .color(eyeColor), style: style) + ctx.stroke(right, with: .color(eyeColor), style: style) + + case .curious: + ctx.fill(pill(x: 23.8, y: 27, w: 5.2, h: 9.6, rx: 2.6), with: .color(eyeColor)) + ctx.fill(pill(x: 34.8, y: 23.5, w: 5.6, h: 14.5, rx: 2.8), with: .color(eyeColor)) + + case .confused: + ctx.fill(pill(x: 23.8, y: 25.5, w: 5.2, h: 12.6, rx: 2.6), with: .color(eyeColor)) + ctx.fill(pill(x: 34.8, y: 24.5, w: 5.4, h: 8.4, rx: 2.7), with: .color(eyeColor)) + + case .excited: + ctx.fill(pill(x: 23.4, y: 23.5, w: 5.8, h: 15.5, rx: 2.9), with: .color(eyeColor)) + ctx.fill(pill(x: 34.8, y: 23.5, w: 5.8, h: 15.5, rx: 2.9), with: .color(eyeColor)) + + case .surprised: + ctx.fill(pill(x: 22.8, y: 23.8, w: 6.6, h: 15, rx: 3.3), with: .color(eyeColor)) + ctx.fill(pill(x: 34.6, y: 23.8, w: 6.6, h: 15, rx: 3.3), with: .color(eyeColor)) + + case .attentive: + ctx.fill(pill(x: 24, y: 26, w: 5.2, h: 10.8, rx: 2.6), with: .color(eyeColor)) + ctx.fill(pill(x: 34.8, y: 26, w: 5.2, h: 10.8, rx: 2.6), with: .color(eyeColor)) + + case .suspicious: + ctx.fill(pill(x: 22.8, y: 28.2, w: 7.2, h: 5.8, rx: 2.9), with: .color(eyeColor)) + ctx.fill(pill(x: 34, y: 28.2, w: 7.2, h: 5.8, rx: 2.9), with: .color(eyeColor)) + + case .shy: + var left = Path() + left.move(to: pt(21.8, 32.5)) + left.addCurve(to: pt(30.2, 32.5), control1: pt(23.4, 27.2), control2: pt(28.6, 27.2)) + ctx.stroke(left, with: .color(eyeColor), style: StrokeStyle(lineWidth: 4.5 * sx, lineCap: .round)) + ctx.fill(pill(x: 34.6, y: 24.8, w: 5.4, h: 13.4, rx: 2.7), with: .color(eyeColor)) + + case .sleepy, .unimpressed: + ctx.fill(pill(x: 22.8, y: 29.6, w: 7.4, h: 4.4, rx: 2.2), with: .color(eyeColor)) + ctx.fill(pill(x: 33.8, y: 29.6, w: 7.4, h: 4.4, rx: 2.2), with: .color(eyeColor)) + + default: + // Default neutral upright pill eyes matching desktop + ctx.fill(pill(x: 23.8, y: 25, w: 5.4, h: 13, rx: 2.7), with: .color(eyeColor)) + ctx.fill(pill(x: 34.8, y: 25, w: 5.4, h: 13, rx: 2.7), with: .color(eyeColor)) + } + } + .frame(width: size, height: size) + .allowsHitTesting(false) + } +} + +// MARK: - Single Bot Avatar View (Animated Idle Blink + 12 Session Emotes) + +struct MemberBotAvatarView: View { + let config: CollabBotAvatarConfig + var size: CGFloat = 38 + var animated: Bool = true + var sessionActive: Bool = false + var selectedOutline: Bool = false + var silhouetteOutlineWidth: CGFloat? = nil + var gazeUpRight: Bool = false + var isLead: Bool = false + var isSupervisor: Bool = false + var reactionTrigger: Int = 0 + + // Animation state (in 64x64 units, scaled by k = size / 64) + @State private var currentEmote: BotSessionEmote = .idle + @State private var isBlinking = false + @State private var headOffset64: CGSize = .zero + @State private var headRotation: Double = 0 + @State private var headScale: CGSize = CGSize(width: 1, height: 1) + @State private var headYaw: Double = 0 + @State private var faceOffset64: CGSize = .zero + @State private var faceRotation: Double = 0 + @State private var faceScale: CGSize = CGSize(width: 1, height: 1) + @State private var emoteStep: Int = 0 + + private var fillColor: Color { + Color(collabHex: config.color) ?? Color(red: 0.08, green: 0.52, blue: 1.0) + } + + private var effectiveExpression: BotAvatarExpression { + currentEmote != .idle ? currentEmote.expression : config.expression + } + + private var k: CGFloat { size / 64.0 } + + private var seed: UInt32 { + CollabBotAvatarConfig.hashSeed("\(config.color):\(config.shape.rawValue)") + } + + var body: some View { + ZStack(alignment: .bottomTrailing) { + ZStack { + if selectedOutline { + BotAvatarShapePath(shape: config.shape) + .stroke( + Color(red: 0.82, green: 0.84, blue: 0.86), + style: StrokeStyle(lineWidth: 8 * k, lineCap: .round, lineJoin: .round) + ) + BotAvatarShapePath(shape: config.shape) + .stroke( + Color.white, + style: StrokeStyle(lineWidth: 4.5 * k, lineCap: .round, lineJoin: .round) + ) + } + + if let outlineWidth = silhouetteOutlineWidth { + BotAvatarShapePath(shape: config.shape) + .stroke( + Color(uiColor: .systemBackground), + style: StrokeStyle(lineWidth: outlineWidth * k, lineCap: .round, lineJoin: .round) + ) + } + + BotAvatarShapePath(shape: config.shape) + .fill(fillColor) + + BotAvatarFaceView( + expression: effectiveExpression, + eyeColor: .white, + size: size + ) + .scaleEffect( + x: isBlinking ? 1.03 : faceScale.width, + y: isBlinking ? 0.08 : faceScale.height + ) + .rotationEffect(.degrees(faceRotation)) + .offset( + x: ((gazeUpRight ? 3.0 : 0.0) + faceOffset64.width) * k, + y: ((gazeUpRight ? -4.0 : 0.0) + faceOffset64.height) * k + ) + } + .frame(width: size, height: size) + .scaleEffect(x: headScale.width, y: headScale.height) + .rotationEffect(.degrees(headRotation)) + .rotation3DEffect(.degrees(headYaw), axis: (x: 0, y: 1, z: 0)) + .offset(x: headOffset64.width * k, y: headOffset64.height * k) + + if isLead || isSupervisor { + Image(systemName: isSupervisor ? "crown.fill" : "star.fill") + .font(.system(size: max(8, size * 0.24), weight: .bold)) + .foregroundStyle(.yellow) + .padding(max(1.5, size * 0.04)) + .background(Color(uiColor: .systemBackground), in: Circle()) + .offset(x: 2, y: 2) + } + } + .frame(width: size, height: size) + .task(id: "\(animated)-\(sessionActive)-\(config.color)-\(config.shape.rawValue)") { + guard animated else { return } + emoteStep = Int(seed % UInt32(BotSessionEmote.sequence.count)) + + if sessionActive { + // Active session loop: cycle through the 12 desktop emotes every ~2.7s + while !Task.isCancelled { + let next = BotSessionEmote.sequence[emoteStep % BotSessionEmote.sequence.count] + emoteStep += 1 + await playEmote(next) + let pauseMs = 1350 + Int(seed % 650) + try? await Task.sleep(for: .milliseconds(pauseMs)) + } + } else { + // Idle life loop: natural blinking + periodic lively micro-emotes + let initialDelayMs = 600 + Int((seed % 25) * 90) + try? await Task.sleep(for: .milliseconds(initialDelayMs)) + var cycle = 0 + while !Task.isCancelled { + cycle += 1 + if cycle % 3 == 0 { + let next = BotSessionEmote.sequence[emoteStep % BotSessionEmote.sequence.count] + emoteStep += 1 + await playEmote(next) + } else { + await performBlink() + if seed % 2 == 0 { + try? await Task.sleep(for: .milliseconds(160)) + await performBlink() + } + } + let waitMs = 2800 + Int((seed % 20) * 110) + try? await Task.sleep(for: .milliseconds(waitMs)) + } + } + } + .onChange(of: reactionTrigger) { _, newValue in + guard newValue > 0 else { return } + let next = BotSessionEmote.sequence[(newValue - 1) % BotSessionEmote.sequence.count] + Task { @MainActor in + await playEmote(next) + } + } + } + + @MainActor + private func performBlink() async { + guard currentEmote == .idle else { return } + withAnimation(.easeInOut(duration: 0.09)) { + isBlinking = true + } + try? await Task.sleep(for: .milliseconds(100)) + withAnimation(.easeInOut(duration: 0.11)) { + isBlinking = false + } + } + + @MainActor + private func playEmote(_ emote: BotSessionEmote) async { + currentEmote = emote + switch emote { + case .happy: + withAnimation(.spring(response: 0.24, dampingFraction: 0.55)) { + headOffset64 = CGSize(width: -4.5, height: -4.5) + headRotation = -10 + headScale = CGSize(width: 0.96, height: 1.05) + faceOffset64 = CGSize(width: -2.5, height: -2.5) + faceRotation = -4 + } + try? await Task.sleep(for: .milliseconds(260)) + withAnimation(.spring(response: 0.24, dampingFraction: 0.55)) { + headOffset64 = CGSize(width: 4.5, height: -4.5) + headRotation = 10 + headScale = CGSize(width: 0.96, height: 1.05) + faceOffset64 = CGSize(width: 2.5, height: -2.5) + faceRotation = 4 + } + try? await Task.sleep(for: .milliseconds(320)) + + case .curious: + withAnimation(.spring(response: 0.32, dampingFraction: 0.65)) { + headOffset64 = CGSize(width: 2.2, height: -3.5) + headRotation = 13 + headScale = CGSize(width: 1.02, height: 0.97) + faceOffset64 = CGSize(width: 3.5, height: -4.8) + faceRotation = 5 + } + try? await Task.sleep(for: .milliseconds(580)) + + case .excited: + withAnimation(.easeInOut(duration: 0.72)) { + headOffset64 = CGSize(width: 0, height: -4.5) + headYaw = 360 + headScale = CGSize(width: 1.04, height: 1.06) + } + try? await Task.sleep(for: .milliseconds(740)) + headYaw = 0 + + case .thinking: + withAnimation(.easeInOut(duration: 0.28)) { + headOffset64 = CGSize(width: -2, height: -2.5) + headRotation = -6 + faceOffset64 = CGSize(width: -5.5, height: -4.2) + } + try? await Task.sleep(for: .milliseconds(340)) + withAnimation(.easeInOut(duration: 0.28)) { + headOffset64 = CGSize(width: 2, height: -2.5) + headRotation = 6 + faceOffset64 = CGSize(width: 5.5, height: -4.2) + } + try? await Task.sleep(for: .milliseconds(340)) + + case .nodding: + for _ in 0..<2 { + withAnimation(.easeInOut(duration: 0.16)) { + headOffset64 = CGSize(width: 0, height: 3) + headScale = CGSize(width: 1.04, height: 0.93) + faceOffset64 = CGSize(width: 0, height: 5.8) + } + try? await Task.sleep(for: .milliseconds(180)) + withAnimation(.easeInOut(duration: 0.16)) { + headOffset64 = CGSize(width: 0, height: -2) + headScale = CGSize(width: 0.98, height: 1.02) + faceOffset64 = CGSize(width: 0, height: -3) + } + try? await Task.sleep(for: .milliseconds(180)) + } + + case .surprised: + withAnimation(.spring(response: 0.24, dampingFraction: 0.52)) { + headOffset64 = CGSize(width: 0, height: -6) + headScale = CGSize(width: 0.92, height: 1.09) + faceOffset64 = CGSize(width: 0, height: -3.8) + faceScale = CGSize(width: 1.08, height: 1.08) + } + try? await Task.sleep(for: .milliseconds(520)) + + case .laughing: + for dir in [-1.0, 1.0, -1.0] { + withAnimation(.easeInOut(duration: 0.15)) { + headOffset64 = CGSize(width: 0, height: -4) + headRotation = 4 * dir + faceOffset64 = CGSize(width: 0, height: -3) + } + try? await Task.sleep(for: .milliseconds(160)) + withAnimation(.easeInOut(duration: 0.15)) { + headOffset64 = CGSize(width: 0, height: 1.8) + headRotation = -3 * dir + faceOffset64 = CGSize(width: 0, height: 2.5) + } + try? await Task.sleep(for: .milliseconds(160)) + } + + case .focused: + withAnimation(.easeInOut(duration: 0.22)) { + headScale = CGSize(width: 1.06, height: 1.04) + faceOffset64 = CGSize(width: -5.5, height: 1) + } + try? await Task.sleep(for: .milliseconds(300)) + withAnimation(.easeInOut(duration: 0.26)) { + faceOffset64 = CGSize(width: 5.5, height: 1) + } + try? await Task.sleep(for: .milliseconds(320)) + + case .wink: + withAnimation(.spring(response: 0.28, dampingFraction: 0.6)) { + headOffset64 = CGSize(width: -3, height: -2.5) + headRotation = -13 + headScale = CGSize(width: 1.03, height: 1.02) + faceOffset64 = CGSize(width: -3.5, height: -2) + faceRotation = -4 + } + try? await Task.sleep(for: .milliseconds(560)) + + case .confused: + withAnimation(.easeInOut(duration: 0.2)) { + headOffset64 = CGSize(width: -3, height: 0) + headRotation = -7 + faceOffset64 = CGSize(width: -6.5, height: 0) + } + try? await Task.sleep(for: .milliseconds(240)) + withAnimation(.easeInOut(duration: 0.2)) { + headOffset64 = CGSize(width: 3, height: 0) + headRotation = 7 + faceOffset64 = CGSize(width: 6.5, height: 0) + } + try? await Task.sleep(for: .milliseconds(240)) + + case .sleepy: + withAnimation(.easeInOut(duration: 0.42)) { + headOffset64 = CGSize(width: 1, height: 4.5) + headRotation = 6 + headScale = CGSize(width: 1.04, height: 0.94) + faceOffset64 = CGSize(width: 1.5, height: 6.5) + } + try? await Task.sleep(for: .milliseconds(480)) + withAnimation(.spring(response: 0.22, dampingFraction: 0.55)) { + headOffset64 = CGSize(width: -1.5, height: -3) + headRotation = -5 + faceOffset64 = CGSize(width: -2, height: -3.5) + } + try? await Task.sleep(for: .milliseconds(240)) + + case .proud: + withAnimation(.spring(response: 0.28, dampingFraction: 0.6)) { + headOffset64 = CGSize(width: -2, height: -4) + headRotation = -7 + headScale = CGSize(width: 1.06, height: 1.04) + faceOffset64 = CGSize(width: -2.5, height: -4.5) + } + try? await Task.sleep(for: .milliseconds(320)) + withAnimation(.spring(response: 0.28, dampingFraction: 0.6)) { + headOffset64 = CGSize(width: 2, height: -4) + headRotation = 7 + faceOffset64 = CGSize(width: 2.5, height: -4.5) + } + try? await Task.sleep(for: .milliseconds(320)) + + case .idle: + break + } + + withAnimation(.spring(response: 0.3, dampingFraction: 0.72)) { + currentEmote = .idle + headOffset64 = .zero + headRotation = 0 + headScale = CGSize(width: 1, height: 1) + faceOffset64 = .zero + faceRotation = 0 + faceScale = CGSize(width: 1, height: 1) + } + } +} + +// MARK: - Stacked Group Avatar View (Desktop GroupAvatar.tsx Parity) + +struct CollabGroupAvatarView: View { + let avatars: [CollabBotAvatarConfig] + var tagColorHex: String? = nil + var size: CGFloat = 40 + var sessionActive: Bool = false + + private struct Slot { + let x: CGFloat + let y: CGFloat + let slotSize: CGFloat + let z: Double + } + + private static let layouts: [Int: [Slot]] = [ + 1: [Slot(x: 4, y: 4, slotSize: 20, z: 1)], + 2: [ + Slot(x: 0.25, y: 5, slotSize: 18, z: 1), + Slot(x: 9.75, y: 5, slotSize: 18, z: 2), + ], + 3: [ + Slot(x: 5.5, y: 0.5, slotSize: 17, z: 1), + Slot(x: 10.5, y: 10, slotSize: 17, z: 2), + Slot(x: 0.5, y: 10, slotSize: 17, z: 3), + ], + 4: [ + Slot(x: 1, y: 1, slotSize: 16, z: 1), + Slot(x: 11, y: 1, slotSize: 16, z: 2), + Slot(x: 1, y: 11, slotSize: 16, z: 2), + Slot(x: 11, y: 11, slotSize: 16, z: 3), + ], + ] + + private var shown: [CollabBotAvatarConfig] { + let slice = Array(avatars.prefix(4)) + return slice.isEmpty ? [CollabBotAvatarConfig.derive(seed: "group")] : slice + } + + var body: some View { + let count = min(max(shown.count, 1), 4) + let slots = Self.layouts[count] ?? Self.layouts[1]! + let k = size / 28.0 + + ZStack(alignment: .topLeading) { + RoundedRectangle(cornerRadius: size * 0.28, style: .continuous) + .fill(Color(uiColor: .secondarySystemFill).opacity(0.65)) + + ForEach(Array(shown.enumerated()), id: \.offset) { index, avatar in + let slot = slots[index] + let px = slot.slotSize * k + let outlinePx = 0.75 * (size / 24.0) + let strokeWidth64 = ((outlinePx * 2.0) / max(px, 1.0)) * 64.0 + + MemberBotAvatarView( + config: avatar, + size: px, + animated: true, + sessionActive: sessionActive, + silhouetteOutlineWidth: strokeWidth64, + gazeUpRight: true + ) + .rotationEffect(.degrees(-12)) + .offset(x: slot.x * k, y: slot.y * k) + .zIndex(slot.z) + } + } + .frame(width: size, height: size) + .overlay { + if let hex = tagColorHex, let ringColor = Color(collabHex: hex) { + RoundedRectangle(cornerRadius: size * 0.28, style: .continuous) + .stroke(ringColor, lineWidth: max(1.5, (1.5 * size) / 24.0)) + } + } + } +} + +// MARK: - MemberBotAvatarPicker (Exact Desktop UI: 颜色 / 形状 + Preview + Swatches) + +struct MemberBotAvatarPicker: View { + @Binding var value: CollabBotAvatarConfig + var label: String = "头像" + + enum SectionTab: String, CaseIterable, Identifiable { + case color + case shape + var id: String { rawValue } + } + + @State private var activeSection: SectionTab = .color + @State private var reactionKey: Int = 0 + + private let firstRowColors = Array(CollabBotAvatarConfig.colorPresets.prefix(6)) + private let secondRowColors = Array(CollabBotAvatarConfig.colorPresets.dropFirst(6)) + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + // Top bar: "头像" label + "颜色 | 形状" segmented pill control + HStack { + Text(label) + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(.primary) + + Spacer() + + HStack(spacing: 2) { + segmentButton( + tab: .color, + title: "颜色", + systemImage: "paintpalette" + ) + segmentButton( + tab: .shape, + title: "形状", + systemImage: "square.on.circle" + ) + } + .padding(3) + .background( + Capsule(style: .continuous) + .fill(Color(uiColor: .secondarySystemFill)) + ) + } + + // Main layout: Left interactive character preview + Right rounded card + HStack(alignment: .center, spacing: 14) { + Button { + reactionKey += 1 + } label: { + MemberBotAvatarView( + config: value, + size: 68, + animated: true, + sessionActive: true, + reactionTrigger: reactionKey + ) + .frame(width: 74, height: 74) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("点击预览头像表情") + + ZStack { + RoundedRectangle(cornerRadius: 16, style: .continuous) + .fill(Color(uiColor: .systemBackground)) + RoundedRectangle(cornerRadius: 16, style: .continuous) + .stroke(Color.primary.opacity(0.09), lineWidth: 1) + + if activeSection == .color { + VStack(spacing: 10) { + HStack(spacing: 10) { + ForEach(firstRowColors) { preset in + colorSwatch(preset) + } + } + HStack(spacing: 10) { + ForEach(secondRowColors) { preset in + colorSwatch(preset) + } + } + } + .padding(.horizontal, 12) + .padding(.vertical, 14) + .transition(.opacity) + } else { + LazyVGrid( + columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 5), + spacing: 8 + ) { + ForEach(BotAvatarShape.allCases) { shape in + shapeButton(shape) + } + } + .padding(.horizontal, 10) + .padding(.vertical, 12) + .transition(.opacity) + } + } + .frame(maxWidth: .infinity) + } + } + } + + private func segmentButton(tab: SectionTab, title: String, systemImage: String) -> some View { + let isSelected = activeSection == tab + return Button { + withAnimation(.easeInOut(duration: 0.16)) { + activeSection = tab + } + } label: { + HStack(spacing: 5) { + Image(systemName: systemImage) + .font(.system(size: 12, weight: .semibold)) + Text(title) + .font(.system(size: 13, weight: .medium)) + } + .foregroundStyle(isSelected ? Color.primary : Color.secondary) + .padding(.horizontal, 12) + .padding(.vertical, 6) + .background { + if isSelected { + Capsule(style: .continuous) + .fill(Color(uiColor: .systemBackground)) + .shadow(color: .black.opacity(0.08), radius: 2, y: 1) + } + } + } + .buttonStyle(.plain) + } + + private func colorSwatch(_ preset: BotAvatarColorPreset) -> some View { + let selected = CollabBotAvatarConfig.normalizeHexColor(value.color) + == CollabBotAvatarConfig.normalizeHexColor(preset.hex) + let swatchColor = Color(collabHex: preset.hex) ?? .blue + + return Button { + value.color = CollabBotAvatarConfig.normalizeHexColor(preset.hex, fallback: value.color) + value.expression = .neutral + reactionKey += 1 + } label: { + ZStack { + if selected { + RoundedRectangle(cornerRadius: 12, style: .continuous) + .stroke(Color.primary.opacity(0.22), lineWidth: 2) + .frame(width: 34, height: 34) + } + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(swatchColor) + .frame(width: 26, height: 26) + } + .frame(width: 34, height: 34) + } + .buttonStyle(.plain) + .accessibilityLabel(preset.label) + } + + private func shapeButton(_ shape: BotAvatarShape) -> some View { + let selected = value.shape == shape + let previewConfig = CollabBotAvatarConfig( + color: value.color, + shape: shape, + expression: .neutral + ) + + return Button { + value.shape = shape + value.expression = .neutral + reactionKey += 1 + } label: { + MemberBotAvatarView( + config: previewConfig, + size: 32, + animated: false, + selectedOutline: selected + ) + .frame(width: 36, height: 36) + .background( + RoundedRectangle(cornerRadius: 10, style: .continuous) + .fill(selected ? Color.primary.opacity(0.06) : Color.clear) + ) + } + .buttonStyle(.plain) + .accessibilityLabel(shape.label) + } +} diff --git a/mobile/ios/App/PromptBar.swift b/mobile/ios/App/PromptBar.swift index 24e0ef49d..f0923ae12 100644 --- a/mobile/ios/App/PromptBar.swift +++ b/mobile/ios/App/PromptBar.swift @@ -1,7 +1,23 @@ +import PhotosUI import SwiftUI +import UIKit enum ComposerMenu: Equatable { - case access, model, effort + case access + case plusModel + case plusMode + case plusPerms + case model + case effort + + var isBottomDrawer: Bool { + switch self { + case .access, .plusModel, .plusMode, .plusPerms: + return true + case .model, .effort: + return false + } + } } struct PromptChoice: Identifiable, Equatable { @@ -10,6 +26,8 @@ struct PromptChoice: Identifiable, Equatable { var detail: String? var tag: String? var icon: String? + /// Agent whose brand mark leads the row (model choices). + var agentID: String? var selected = false var enabled = true } @@ -17,6 +35,7 @@ struct PromptChoice: Identifiable, Equatable { struct PromptGroup: Identifiable, Equatable { var id: String { title } let title: String + var agentID: String? let choices: [PromptChoice] } @@ -25,7 +44,19 @@ struct PromptEffort: Equatable { let index: Int } -/// SwiftUI port of the web PromptBar: one rounded field, a tool row, and floating menus above it. +struct AttachedImageItem: Identifiable, Equatable { + let id = UUID() + let token: String + var image: UIImage + let fileName: String + + static func == (lhs: AttachedImageItem, rhs: AttachedImageItem) -> Bool { + lhs.id == rhs.id && lhs.token == rhs.token && lhs.fileName == rhs.fileName + } +} + +/// SwiftUI port of the PromptBar: one rounded dock, a tool row, floating menus for inline pills, +/// and an expandable bottom action drawer when tapping `+`. struct PromptBar: View { @Binding var draft: String @Binding var menu: ComposerMenu? @@ -33,12 +64,14 @@ struct PromptBar: View { let busy: Bool let hasAlert: Bool let modelName: String? + var agentID: String? let modelChoices: [PromptChoice] let otherModelGroups: [PromptGroup] let otherAgentNote: String? let accessChoices: [PromptChoice] let extraChoices: [PromptChoice] let effort: PromptEffort? + var openFiles: (() -> Void)? = nil let send: () -> Void let stop: () -> Void let pickModel: (String) -> Void @@ -47,88 +80,218 @@ struct PromptBar: View { let setEffort: (Int) -> Void @FocusState private var focused: Bool + @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 private let spark = Color(red: 0.70, green: 0.62, blue: 1.0) private var armed: Bool { - isRunning || !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + isRunning || !draft.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 { - menuView(menu) + if let menu, !menu.isBottomDrawer { + floatingMenuView(menu) .padding(.horizontal, 12) .transition(.scale(scale: 0.98, anchor: .bottom).combined(with: .opacity)) } - field + dockSurface + } + .animation(.spring(response: 0.28, dampingFraction: 0.86), value: menu) + .photosPicker( + isPresented: $showPhotoPicker, + selection: $selectedPhotoItems, + maxSelectionCount: 4, + matching: .images + ) + .onChange(of: selectedPhotoItems) { _, items in + guard !items.isEmpty else { return } + Task { @MainActor in + for (idx, item) in items.enumerated() { + if let data = try? await item.loadTransferable(type: Data.self), + let uiImage = UIImage(data: data) + { + let fileName = "image-\(idx + 1).jpg" + let token = AttachmentImageStore.shared.register(image: uiImage, fileName: fileName) + attachedImages.append( + AttachedImageItem(token: token, image: uiImage, fileName: fileName) + ) + } + } + selectedPhotoItems.removeAll() + menu = nil + } + } + .sheet(isPresented: $showCameraSheet) { + CameraCaptureSheet { captured in + if let captured { + let fileName = "camera-photo.jpg" + let token = AttachmentImageStore.shared.register(image: captured, fileName: fileName) + attachedImages.append( + AttachedImageItem(token: token, image: captured, fileName: fileName) + ) + } + menu = nil + } + .ignoresSafeArea() + } + .fullScreenCover(item: $previewingAttached) { item in + ZoomableImagePreviewSheet( + item: PreviewableImageItem( + id: item.token, + image: item.image, + urlString: nil, + title: item.fileName + ), + onUpdateImage: { updated in + AttachmentImageStore.shared.update(token: item.token, image: updated, fileName: item.fileName) + if let idx = attachedImages.firstIndex(where: { $0.id == item.id }) { + attachedImages[idx].image = updated + } + } + ) } - .animation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.18), value: menu) } - // MARK: Field + // 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) - private var field: some View { - VStack(alignment: .leading, spacing: 8) { - TextField("发消息", text: $draft, axis: .vertical) - .lineLimit(1...5) - .font(.system(size: 16)) - .focused($focused) - .onChange(of: focused) { _, isFocused in if isFocused { menu = nil } } - .onChange(of: draft) { _, _ in menu = nil } - toolRow + 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)) + } + .offset(x: 4, y: -4) + } + } + } + .padding(.top, 2) + } + } + + TextField("发消息", text: $draft, axis: .vertical) + .lineLimit(1...5) + .font(.system(size: 15.5)) + .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 } + + if let menu, menu.isBottomDrawer { + Divider().opacity(0.55) + bottomDrawerContent(menu) + .transition(.move(edge: .bottom).combined(with: .opacity)) + } } - .padding(.horizontal, 16) - .padding(.top, 12) - .padding(.bottom, 8) .frame(maxWidth: .infinity) - .background(alignment: .bottom) { - // The dock runs to the screen edge so its colour and the home-indicator area are one surface. - let dock = UnevenRoundedRectangle(topLeadingRadius: 20, topTrailingRadius: 20) + .background { + let dock = RoundedRectangle(cornerRadius: 22, style: .continuous) ZStack { dock.fill(Color(.secondarySystemGroupedBackground)) dock .fill(RadialGradient( - colors: [spark.opacity(0.26), .clear], + colors: [spark.opacity(0.24), .clear], center: .bottomLeading, startRadius: 0, endRadius: 220 )) .opacity(effortAtMax ? 1 : 0) .animation(.easeInOut(duration: 0.5), value: effortAtMax) - dock.stroke(Color.primary.opacity(0.06)) + dock.strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.7) } - .shadow(color: .black.opacity(0.06), radius: 8, y: -2) - .ignoresSafeArea(edges: .bottom) + .shadow(color: .black.opacity(0.05), radius: 10, x: 0, y: 3) } - .contentShape(Rectangle()) - .onTapGesture { focused = true } + .padding(.horizontal, 14) + .padding(.bottom, 8) } private var toolRow: some View { - HStack(spacing: 4) { - ToolButton(icon: "plus", on: menu == .access, alert: hasAlert, label: "权限与模式") { - toggle(.access) + HStack(spacing: 6) { + ToolButton(icon: "plus", on: isPlusOpen, alert: hasAlert, label: "更多功能") { + focused = false + menu = isPlusOpen ? nil : .access } if let modelName { - PickPill(on: menu == .model, label: "选择模型") { toggle(.model) } content: { + PickPill(on: menu == .model || menu == .plusModel, label: "选择模型") { + toggle(.model) + } content: { + if agentID != nil { AgentIconView(agent: agentID, size: 13.5) } Text(modelName).lineLimit(1) - Image(systemName: "chevron.down").font(.system(size: 10, weight: .bold)) + Image(systemName: "chevron.down").font(.system(size: 9.5, weight: .bold)) } } if let effort { - PickPill(on: menu == .effort, tint: effortAtMax ? spark : nil, label: "推理强度") { + PickPill(on: menu == .effort || menu == .plusMode, tint: effortAtMax ? spark : nil, label: "推理强度") { toggle(.effort) } content: { - Image(systemName: "sparkles").font(.system(size: 12, weight: .semibold)) + Image(systemName: "sparkles").font(.system(size: 11.5, weight: .semibold)) Text(effort.levels[effort.index]) } } Spacer(minLength: 0) - SendButton(armed: armed, running: isRunning, busy: busy, send: send, stop: stop) + 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 + ) } } @@ -137,16 +300,152 @@ struct PromptBar: View { menu = menu == target ? nil : target } - // MARK: Menus + // MARK: Bottom Drawer (`+` Action Grid & Sub-panels) @ViewBuilder - private func menuView(_ kind: ComposerMenu) -> some View { + private func bottomDrawerContent(_ kind: ComposerMenu) -> some View { + switch kind { + case .access: + plusActionGrid + case .plusModel: + drawerSubpanel(title: "选择模型") { + DrawerChoiceList( + rows: modelChoices, + groups: otherModelGroups, + footnote: otherAgentNote, + empty: "电脑端没有配置可选模型", + select: pickModel + ) + } + 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) + } + } + } + case .plusPerms: + drawerSubpanel(title: "权限设置", accent: .orange) { + DrawerChoiceList( + rows: accessChoices, + empty: "当前 Agent 没有提供权限设置", + select: pickAccess + ) + } + default: + EmptyView() + } + } + + private var modeAndExtraChoices: [PromptChoice] { + let planModes = accessChoices.filter { + $0.id.localizedCaseInsensitiveContains("plan") || $0.title.localizedCaseInsensitiveContains("plan") + } + return planModes + extraChoices + } + + 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?() + } + PlusGridTile(title: "模型", systemImage: "cpu") { + menu = .plusModel + } + PlusGridTile(title: "模式", customIcon: .botMode) { + menu = .plusMode + } + PlusGridTile( + title: "权限", + systemImage: "exclamationmark.shield", + tint: .orange, + badge: hasAlert + ) { + menu = .plusPerms + } + } + .padding(.horizontal, 22) + .padding(.top, 18) + .padding(.bottom, 16) + } + + 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) + + Spacer() + + Text(title) + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(accent) + + Spacer() + + // Balance back button width + Color.clear.frame(width: 44, height: 1) + } + .padding(.horizontal, 16) + .padding(.top, 10) + + content() + .padding(.horizontal, 12) + .padding(.bottom, 12) + } + } + + // MARK: Floating Menus (for inline model / effort pills) + + @ViewBuilder + private func floatingMenuView(_ kind: ComposerMenu) -> some View { Group { switch kind { - case .access: - MenuList(rows: accessChoices + extraChoices, empty: "Agent 没有提供权限设置") { id in - if accessChoices.contains(where: { $0.id == id }) { pickAccess(id) } else { pickExtra(id) } - } case .model: MenuList( rows: modelChoices, @@ -155,18 +454,148 @@ struct PromptBar: View { empty: "电脑端没有配置可选模型", select: pickModel ) - .frame(maxWidth: 240) + .frame(maxWidth: 250) 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 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 + + 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) + } + } 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) + } + } + + Text(title) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(tint ?? .secondary) + .lineLimit(1) + } + .frame(maxWidth: .infinity) + .contentShape(Rectangle()) + } + .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 + } +} + +// MARK: - Camera Capture Fallback Sheet + +private struct CameraCaptureSheet: UIViewControllerRepresentable { + let onFinish: (UIImage?) -> Void + + func makeUIViewController(context: Context) -> UIImagePickerController { + let picker = UIImagePickerController() + picker.sourceType = UIImagePickerController.isSourceTypeAvailable(.camera) ? .camera : .photoLibrary + picker.delegate = context.coordinator + return picker + } + + func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {} + + func makeCoordinator() -> Coordinator { + Coordinator(onFinish: onFinish) + } + + final class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate { + let onFinish: (UIImage?) -> Void + init(onFinish: @escaping (UIImage?) -> Void) { self.onFinish = onFinish } + + func imagePickerController( + _ picker: UIImagePickerController, + didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] + ) { + let image = info[.originalImage] as? UIImage + onFinish(image) + } + + func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { + onFinish(nil) + } + } +} + // MARK: - Controls private struct ToolButton: View { @@ -179,11 +608,14 @@ private struct ToolButton: View { var body: some View { Button(action: action) { Image(systemName: icon) - .font(.system(size: 15, weight: .semibold)) + .font(.system(size: 14.5, weight: .semibold)) .rotationEffect(.degrees(on ? 45 : 0)) - .frame(width: 28, height: 28) - .background(on ? Color.primary.opacity(0.08) : .clear, in: RoundedRectangle(cornerRadius: 8)) - .foregroundStyle(on ? Color.primary : Color.primary.opacity(0.6)) + .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) } } @@ -203,12 +635,15 @@ private struct PickPill: View { var body: some View { Button(action: action) { - HStack(spacing: 4, content: content) - .font(.system(size: 12, weight: .medium)) - .padding(.horizontal, 8) - .frame(height: 28) - .background(on ? Color.primary.opacity(0.08) : .clear, in: RoundedRectangle(cornerRadius: 8)) - .foregroundStyle(tint ?? (on ? Color.primary : Color.primary.opacity(0.7))) + 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))) } .buttonStyle(PressStyle(scale: 0.96)) .accessibilityLabel(label) @@ -235,16 +670,16 @@ private struct SendButton: View { var body: some View { Button(action: running ? stop : send) { SendGlyph(morph: running ? 1 : 0) - .frame(width: 16, height: 16) - .frame(width: 28, height: 28) - .foregroundStyle(armed ? Color(.systemBackground) : Color.primary.opacity(0.35)) + .frame(width: 15, height: 15) + .frame(width: 30, height: 30) + .foregroundStyle(armed ? Color(.systemBackground) : Color.primary.opacity(0.32)) .background( - armed ? Color.primary : Color.primary.opacity(0.08), - in: RoundedRectangle(cornerRadius: 8) + armed ? Color.primary : Color.primary.opacity(0.07), + in: Circle() ) .animation(.easeOut(duration: 0.2), value: armed) } - .buttonStyle(PressStyle(scale: armed ? 0.96 : 1)) + .buttonStyle(PressStyle(scale: armed ? 0.95 : 1)) .disabled(!armed || (busy && !running)) .accessibilityLabel(running ? "停止" : "发送") } @@ -314,7 +749,59 @@ private struct SendGlyph: View { } } -// MARK: - Menus +// 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) {} } + } + 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] @@ -342,12 +829,15 @@ private struct MenuList: View { VStack(spacing: 0) { ForEach(rows) { row in MenuRow(row: row) { select(row.id) } } ForEach(groups) { group in - Text(group.title) - .font(.system(size: 11, weight: .medium)) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.horizontal, 8) - .padding(.top, 8) + 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) {} } } if let footnote { @@ -372,7 +862,11 @@ private struct MenuRow: View { var body: some View { Button(action: action) { HStack(spacing: 10) { - if let icon = row.icon { + 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) @@ -505,7 +999,7 @@ private struct EffortSlider: View { #Preview { struct Demo: View { @State private var draft = "" - @State private var menu: ComposerMenu? + @State private var menu: ComposerMenu? = .access @State private var effort = 4 var body: some View { diff --git a/mobile/ios/App/RootTabView.swift b/mobile/ios/App/RootTabView.swift index 6287b252a..f4e9bd8a0 100644 --- a/mobile/ios/App/RootTabView.swift +++ b/mobile/ios/App/RootTabView.swift @@ -1,46 +1,202 @@ +import CompanionCore import SwiftUI +import UIKit -enum AppTab: Hashable { - case conversations, board, space, files, settings +enum AppTab: Hashable, CaseIterable, Identifiable { + case conversations + case board + case space + case settings + + var id: Self { self } + + var title: String { + switch self { + case .conversations: return "对话" + case .board: return "看板" + case .space: return "协作空间" + case .settings: return "设置" + } + } + + var icon: String { + switch self { + case .conversations: return "message" + case .board: return "square.grid.2x2" + case .space: return "person.2" + case .settings: return "gearshape" + } + } + + var selectedIcon: String { + switch self { + case .conversations: return "message.fill" + case .board: return "square.grid.2x2.fill" + case .space: return "person.2.fill" + case .settings: return "gearshape.fill" + } + } } struct RootTabView: View { + @Environment(ServerStore.self) private var servers + @Environment(AppAppearanceStore.self) private var appearance @State private var selection: AppTab = .conversations + @State private var attentionCenter = CompanionAttentionCenter() + @State private var isConversationsChromeHidden = false + @State private var isLaunchRevealed = false + @State private var isKeyboardVisible = false + + 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 } + if selection == .conversations && isConversationsChromeHidden { return false } + return true + } + + private var isBottomBarRevealed: Bool { + isLaunchRevealed || servers.activeProfile == nil || selection != .conversations + } var body: some View { - TabView(selection: $selection) { - RequiresServer(selection: $selection) { ConversationsView(client: $0) } - .tabItem { Label("对话", systemImage: "bubble.left.and.bubble.right") } - .tag(AppTab.conversations) - UnsupportedTab(title: "看板", icon: "square.grid.2x2") - .tabItem { Label("看板", systemImage: "square.grid.2x2") } - .tag(AppTab.board) - UnsupportedTab(title: "协作空间", icon: "person.2") - .tabItem { Label("协作空间", systemImage: "person.2") } - .tag(AppTab.space) - RequiresServer(selection: $selection) { FilesView(client: $0) } - .tabItem { Label("文件", systemImage: "folder") } - .tag(AppTab.files) - SettingsView() - .tabItem { Label("设置", systemImage: "gearshape") } - .tag(AppTab.settings) + VStack(spacing: 0) { + 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 + } + } + ) + } + .opacity(selection == .conversations ? 1 : 0) + .allowsHitTesting(selection == .conversations) + + if selection == .board { + RequiresServer(selection: $selection) { BoardView(client: $0) } + .transition(.opacity) + } else if selection == .space { + RequiresServer(selection: $selection) { CollaborationSpaceView(client: $0) } + .transition(.opacity) + } else if selection == .settings { + SettingsView() + .transition(.opacity) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + + 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)) + } + } + .environment(attentionCenter) + .overlay(alignment: .top) { + if let client = activeClient { + CompanionToastOverlay( + client: client, + center: attentionCenter, + onOpenConversation: { conversation in + selection = .conversations + attentionCenter.openConversation(conversation) + } + ) + } + } + .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 + } + } + .dynamicTypeSize(appearance.fontSizePreset.dynamicTypeSize) + .fontDesign(appearance.fontStylePreset.fontDesign) + .preferredColorScheme(appearance.themeMode.colorScheme) + .onAppear { + appearance.applyInterfaceStyleToAllWindows(appearance.themeMode.uiInterfaceStyle) + } + .onChange(of: selection) { _, _ in + dismissKeyboard() + } + .background( + GlobalInteractionInstaller() + .frame(width: 0, height: 0) + .allowsHitTesting(false) + ) } -} -/// The Host does not grant the Companion preset access to this surface (ADR-0054). -private struct UnsupportedTab: View { - let title: String - let icon: String + private var bottomNavigationBar: some View { + VStack(spacing: 0) { + Rectangle() + .fill(Color.primary.opacity(0.08)) + .frame(height: 0.5) - var body: some View { - NavigationStack { - ContentUnavailableView(title, systemImage: icon, description: Text("手机端暂不支持")) - .navigationTitle(title) + HStack(spacing: 0) { + ForEach(AppTab.allCases) { tab in + let isSelected = selection == tab + Button { + if selection != tab { + withAnimation(.smooth(duration: 0.16)) { + selection = tab + } + } + } label: { + VStack(spacing: 3.5) { + Image(systemName: isSelected ? tab.selectedIcon : tab.icon) + .font(.system(size: 17.5, weight: isSelected ? .semibold : .regular)) + .frame(height: 22) + + Text(tab.title) + .font(.system(size: 10.5, weight: isSelected ? .semibold : .medium)) + .lineLimit(1) + } + .foregroundStyle(isSelected ? Color.primary : Color.secondary) + .frame(maxWidth: .infinity) + .padding(.top, 7) + .padding(.bottom, 4) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(tab.title) + } + } + .padding(.horizontal, 8) } + .background( + Color(.secondarySystemGroupedBackground) + .ignoresSafeArea(edges: .bottom) + ) } } #Preview { - RootTabView().environment(ServerStore(defaults: UserDefaults(suiteName: "preview")!)) + RootTabView() + .environment(ServerStore(defaults: UserDefaults(suiteName: "preview")!)) + .environment(AppAppearanceStore(defaults: UserDefaults(suiteName: "preview")!)) } diff --git a/mobile/ios/App/SearchCard.swift b/mobile/ios/App/SearchCard.swift new file mode 100644 index 000000000..f340bb4d2 --- /dev/null +++ b/mobile/ios/App/SearchCard.swift @@ -0,0 +1,311 @@ +import SwiftUI + +struct SearchResultItem: Identifiable, Equatable { + let id: String + let title: String + let subtitle: String? + let icon: String + let action: () -> Void + + static func == (lhs: SearchResultItem, rhs: SearchResultItem) -> Bool { + lhs.id == rhs.id && lhs.title == rhs.title && lhs.subtitle == rhs.subtitle && lhs.icon == rhs.icon + } +} + +/// Top status pill showing the paired computer and live connection health: +/// green dot when connected, yellow dot when disconnected or failing. +struct ConnectedDeviceBar: View { + @Environment(ServerStore.self) private var servers + let isConnected: Bool + + private var deviceTitle: String { + guard let profile = servers.activeProfile else { return "未配对电脑" } + if let host = URL(string: profile.origin)?.host, !host.isEmpty { + return "VibeX · \(host)" + } + return profile.origin + } + + private var statusText: String { + isConnected ? "已连接" : "连接异常" + } + + private var dotColor: Color { + isConnected ? Color.green : Color.yellow + } + + var body: some View { + HStack(spacing: 7) { + ZStack { + Circle() + .fill(dotColor.opacity(0.24)) + .frame(width: 14, height: 14) + Circle() + .fill(dotColor) + .frame(width: 7.5, height: 7.5) + } + Text(deviceTitle) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(.primary) + .lineLimit(1) + Text("·") + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(.tertiary) + Text(statusText) + .font(.system(size: 12)) + .foregroundStyle(isConnected ? Color.secondary : Color.orange) + } + .padding(.horizontal, 12) + .padding(.vertical, 6) + .background( + Capsule(style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + .shadow(color: .black.opacity(0.05), radius: 6, y: 2) + ) + .overlay( + Capsule(style: .continuous) + .strokeBorder(Color.primary.opacity(0.07), lineWidth: 0.5) + ) + } +} + +/// 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 { + @Binding var query: String + let placeholder: String + let results: [SearchResultItem] + var emptyTitle: String = "未找到匹配结果" + var emptyHint: String = "换个关键词试试" + + @FocusState private var isFocused: Bool + @State private var isSearchActive = false + @State private var selectedID: String? + @State private var cardGlobalFrame: CGRect = .zero + @Namespace private var glideNamespace + + private var trimmedQuery: String { + query.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var showDropdown: Bool { + isSearchActive && !trimmedQuery.isEmpty + } + + private var isEmptyResult: Bool { + !trimmedQuery.isEmpty && results.isEmpty + } + + private var showCancelButton: Bool { + isFocused || isSearchActive || !query.isEmpty + } + + var body: some View { + VStack(spacing: 0) { + // Input row (h-10 / 40pt) + HStack(spacing: 8) { + Image(systemName: "magnifyingglass") + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(isFocused ? Color.accentColor : Color.secondary) + .frame(width: 16, height: 16) + + TextField(placeholder, text: $query) + .font(.system(size: 13)) + .foregroundStyle(.primary) + .focused($isFocused) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .submitLabel(.search) + .onSubmit { + if let first = results.first { + selectResult(first) + } else { + isFocused = false + } + } + + if !query.isEmpty { + Button { + withAnimation(.easeOut(duration: 0.15)) { + query = "" + selectedID = nil + } + } label: { + Image(systemName: "xmark") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.secondary) + .frame(width: 24, height: 24) + .background( + Circle() + .fill(Color.primary.opacity(0.06)) + ) + } + .buttonStyle(.plain) + .accessibilityLabel("清除搜索") + .transition(.opacity.combined(with: .scale(scale: 0.9))) + } + + if showCancelButton { + Button { + cancelSearch() + } label: { + Text("取消") + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(Color.accentColor) + .padding(.leading, 2) + } + .buttonStyle(.plain) + .transition(.move(edge: .trailing).combined(with: .opacity)) + } + } + .padding(.horizontal, 12) + .frame(height: 40) + .contentShape(Rectangle()) + .onTapGesture { + if !isFocused { + isFocused = true + isSearchActive = true + } + } + + if showDropdown { + Divider() + .overlay(Color.primary.opacity(0.08)) + + if isEmptyResult { + VStack(spacing: 4) { + ZStack { + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color.primary.opacity(0.05)) + .frame(width: 32, height: 32) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.5) + ) + Image(systemName: "magnifyingglass") + .font(.system(size: 14, weight: .medium)) + .foregroundStyle(.secondary) + } + .padding(.bottom, 4) + + Text(emptyTitle) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(.primary) + Text(emptyHint) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity) + .padding(.horizontal, 16) + .padding(.vertical, 28) + .transition(.opacity) + } else { + VStack(spacing: 1) { + ForEach(results.prefix(6)) { item in + let isActive = selectedID == item.id + Button { + selectResult(item) + } label: { + HStack(spacing: 8) { + Image(systemName: item.icon) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .frame(width: 16) + Text(item.title) + .font(.system(size: 13)) + .foregroundStyle(.primary) + .lineLimit(1) + Spacer(minLength: 6) + if let subtitle = item.subtitle, !subtitle.isEmpty { + Text(subtitle) + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(.tertiary) + .lineLimit(1) + .truncationMode(.head) + } + } + .padding(.horizontal, 8) + .frame(height: 32) + .frame(maxWidth: .infinity, alignment: .leading) + .background { + if isActive { + RoundedRectangle(cornerRadius: 6, style: .continuous) + .fill(Color.primary.opacity(0.07)) + .matchedGeometryEffect(id: "glide-highlight", in: glideNamespace) + } + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + } + .padding(4) + .transition(.opacity) + } + } + } + .background( + 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) + } + .onChange(of: geo.frame(in: .global)) { _, newFrame in + cardGlobalFrame = newFrame + } + } + ) + .overlay( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .strokeBorder( + isFocused ? Color.accentColor.opacity(0.45) : Color.primary.opacity(0.08), + lineWidth: isFocused ? 1.0 : 0.5 + ) + ) + .animation(.easeOut(duration: 0.18), value: showDropdown) + .animation(.easeOut(duration: 0.18), value: isEmptyResult) + .animation(.easeOut(duration: 0.18), value: showCancelButton) + .onChange(of: isFocused) { _, focused in + if focused { + isSearchActive = true + } + } + .onChange(of: query) { _, newValue in + if !newValue.isEmpty { + isSearchActive = true + } + } + .onReceive(NotificationCenter.default.publisher(for: .vibexTapOutsideInput)) { note in + guard showCancelButton else { return } + if let locationValue = note.userInfo?["location"] as? NSValue { + let point = locationValue.cgPointValue + if !cardGlobalFrame.insetBy(dx: -8, dy: -8).contains(point) { + cancelSearch() + } + } + } + } + + private func selectResult(_ item: SearchResultItem) { + withAnimation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.2)) { + selectedID = item.id + isFocused = false + isSearchActive = false + query = "" + } + dismissKeyboard() + item.action() + } + + private func cancelSearch() { + withAnimation(.easeOut(duration: 0.18)) { + isFocused = false + isSearchActive = false + query = "" + selectedID = nil + } + dismissKeyboard() + } +} diff --git a/mobile/ios/App/ServerStore.swift b/mobile/ios/App/ServerStore.swift index 6aa3ba2c3..d003a7645 100644 --- a/mobile/ios/App/ServerStore.swift +++ b/mobile/ios/App/ServerStore.swift @@ -9,6 +9,14 @@ struct ServerProfile: Codable, Identifiable, Hashable { var serverVersion: String var protocolVersion: String var scopes: [String] + + var displayHost: String { + URL(string: origin)?.host ?? origin + } + + var serverName: String { + "VibeX (\(displayHost))" + } } @Observable @@ -55,6 +63,22 @@ final class ServerStore { /// The most recently paired computer is the one the tabs read from. var activeProfile: ServerProfile? { profiles.last } + func activeClient() -> HostClient? { + activeProfile.flatMap { client(for: $0) } + } + + func setActive(_ profileID: String) { + guard let idx = profiles.firstIndex(where: { $0.id == profileID }) else { return } + let chosen = profiles.remove(at: idx) + profiles.append(chosen) + persist() + } + + func remove(_ profileID: String) { + guard let profile = profiles.first(where: { $0.id == profileID }) else { return } + forget(profile) + } + func client(for profile: ServerProfile) -> HostClient? { guard let origin = try? HostOrigin.parse(profile.origin), let token = KeychainStore.read(account: profile.id) diff --git a/mobile/ios/App/SettingsView.swift b/mobile/ios/App/SettingsView.swift index 9cc4b396a..82271aaa7 100644 --- a/mobile/ios/App/SettingsView.swift +++ b/mobile/ios/App/SettingsView.swift @@ -1,36 +1,1297 @@ +import CompanionCore import SwiftUI struct SettingsView: View { @Environment(ServerStore.self) private var servers - @State private var showingPair = false + @Environment(AppAppearanceStore.self) private var appearance var body: some View { NavigationStack { List { - Section("电脑") { + // 1. 个人资料 + Section { + NavigationLink { + ProfileSettingsDetailView() + } label: { + HStack(spacing: 12) { + MemberBotAvatarView( + config: appearance.avatarConfig, + size: 42, + animated: true + ) + VStack(alignment: .leading, spacing: 1) { + HStack(spacing: 6) { + Text(appearance.userName) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(.primary) + Text(appearance.userHandle) + .font(.caption2) + .foregroundStyle(.secondary) + } + Text(appearance.userRoleTitle) + .font(.caption) + .foregroundStyle(.secondary) + if !appearance.userBio.isEmpty { + Text(appearance.userBio) + .font(.caption2) + .foregroundStyle(.tertiary) + .lineLimit(1) + } + } + } + } + .listRowInsets(EdgeInsets(top: 6, leading: 14, bottom: 6, trailing: 14)) + } + + // 2. 已配对的电脑 & 3. 技能 + Section { + NavigationLink { + PairedComputersSettingsView() + } label: { + HStack(spacing: 10) { + settingsIconBadge( + systemImage: "desktopcomputer", + tint: .blue + ) + VStack(alignment: .leading, spacing: 1) { + Text("已配对的电脑") + .font(.subheadline.weight(.medium)) + Text(pairedComputerSubtitle) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Spacer(minLength: 6) + if servers.activeProfile != nil { + HStack(spacing: 4) { + Circle() + .fill(Color.green) + .frame(width: 6.5, height: 6.5) + Text("已连接") + .font(.caption2.weight(.medium)) + .foregroundStyle(.secondary) + } + } else { + Text("去配对") + .font(.caption2) + .foregroundStyle(.secondary) + } + } + } + .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + + NavigationLink { + SkillsHubSettingsView() + } label: { + HStack(spacing: 10) { + settingsIconBadge( + systemImage: "sparkles.rectangle.stack.fill", + tint: .purple + ) + VStack(alignment: .leading, spacing: 1) { + Text("技能") + .font(.subheadline.weight(.medium)) + Text("技能 · MCP · 插件 · 子代理") + .font(.caption2) + .foregroundStyle(.secondary) + } + Spacer() + } + } + .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + } + + // 4. 主题 & 5. 字体 & 6. 通知 + Section { + HStack(spacing: 10) { + settingsIconBadge( + systemImage: appearance.themeMode.icon, + tint: .indigo + ) + Text("主题") + .font(.subheadline.weight(.medium)) + Spacer(minLength: 8) + Picker("主题", selection: Binding( + get: { appearance.themeMode }, + set: { appearance.setThemeModeWithTopRightReveal($0) } + )) { + ForEach(AppThemeMode.allCases) { mode in + Text(mode.title).tag(mode) + } + } + .pickerStyle(.segmented) + .labelsHidden() + .frame(maxWidth: 210) + } + .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + + NavigationLink { + FontSettingsDetailView() + } label: { + HStack(spacing: 10) { + settingsIconBadge( + systemImage: "textformat.size", + tint: .orange + ) + VStack(alignment: .leading, spacing: 1) { + Text("字体") + .font(.subheadline.weight(.medium)) + Text("字号大小与字体样式") + .font(.caption2) + .foregroundStyle(.secondary) + } + Spacer() + Text("\(appearance.fontStylePreset.shortTitle) · \(appearance.fontSizePreset.title)") + .font(.caption2) + .foregroundStyle(.secondary) + } + } + .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + + NavigationLink { + NotificationSettingsDetailView() + } label: { + HStack(spacing: 10) { + settingsIconBadge( + systemImage: "bell.badge.fill", + tint: .red + ) + VStack(alignment: .leading, spacing: 1) { + Text("通知") + .font(.subheadline.weight(.medium)) + Text("任务完成、审批与协作消息提醒") + .font(.caption2) + .foregroundStyle(.secondary) + } + Spacer() + Text(appearance.systemNotificationStatusText) + .font(.caption2) + .foregroundStyle(.secondary) + } + } + .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + } + + // 7. 关于 VibeX & 当前版本 + Section { + NavigationLink { + AboutVibeXDetailView() + } label: { + HStack(spacing: 10) { + settingsIconBadge( + systemImage: "info.circle.fill", + tint: .teal + ) + Text("关于 VibeX") + .font(.subheadline.weight(.medium)) + Spacer() + Text("本地优先 AI 研发平台") + .font(.caption2) + .foregroundStyle(.secondary) + } + } + .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + + HStack(spacing: 10) { + settingsIconBadge( + systemImage: "checkmark.seal.fill", + tint: .green + ) + Text("当前版本") + .font(.subheadline.weight(.medium)) + Spacer() + Text(currentVersionLabel) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + .listRowInsets(EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)) + } + } + .listSectionSpacing(8) + .contentMargins(.top, 2, for: .scrollContent) + .navigationTitle("设置") + .navigationBarTitleDisplayMode(.inline) + } + } + + private var pairedComputerSubtitle: String { + if let active = servers.activeProfile { + return "\(active.serverName) · 共 \(servers.profiles.count) 台历史设备" + } + return "查看历史配对电脑或配对新的电脑" + } + + private var currentVersionLabel: String { + if let active = servers.activeProfile { + return "v\(active.serverVersion) (协议 v\(active.protocolVersion))" + } + return "v0.4.2" + } + + private func settingsIconBadge(systemImage: String, tint: Color) -> some View { + ZStack { + RoundedRectangle(cornerRadius: 7, style: .continuous) + .fill(tint.opacity(0.14)) + .frame(width: 28, height: 28) + Image(systemName: systemImage) + .font(.system(size: 13.5, weight: .semibold)) + .foregroundStyle(tint) + } + } +} + +// MARK: - 1. 个人资料详情页 + +struct ProfileSettingsDetailView: View { + @Environment(AppAppearanceStore.self) private var appearance + @Environment(ServerStore.self) private var servers + @State private var hostInfo: HostUserSystemInfo? + + var body: some View { + @Bindable var bindableAppearance = appearance + Form { + Section { + VStack(spacing: 14) { + MemberBotAvatarView( + config: appearance.avatarConfig, + size: 76, + animated: true + ) + Text(appearance.userName) + .font(.title3.weight(.bold)) + Text(appearance.userRoleTitle) + .font(.caption) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 8) + + MemberBotAvatarPicker( + value: Binding( + get: { appearance.avatarConfig }, + set: { appearance.avatarConfig = $0 } + ) + ) + } header: { + Text("动态角色头像 (11 种配色 · 13 种形状)") + } + + Section("基本信息") { + LabeledContent("昵称") { + TextField("输入昵称", text: $bindableAppearance.userName) + .multilineTextAlignment(.trailing) + } + LabeledContent("标识 (Handle)") { + TextField("@handle", text: $bindableAppearance.userHandle) + .multilineTextAlignment(.trailing) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + } + LabeledContent("头衔 / 角色") { + TextField("头衔", text: $bindableAppearance.userRoleTitle) + .multilineTextAlignment(.trailing) + } + VStack(alignment: .leading, spacing: 6) { + Text("个人简介") + .font(.subheadline) + .foregroundStyle(.secondary) + TextField("介绍一下你的工作流...", text: $bindableAppearance.userBio, axis: .vertical) + .lineLimit(2...4) + } + } + + if let active = servers.activeProfile { + Section("当前绑定工作站环境") { + LabeledContent("工作站名称", value: active.serverName) + LabeledContent("本机设备名", value: active.deviceName) + if let env = hostInfo?.environment { + LabeledContent("操作系统", value: "\(env.osType) (\(env.bitness))") + LabeledContent("处理器架构", value: env.osArchitecture) + } + } + } + } + .navigationTitle("个人资料") + .navigationBarTitleDisplayMode(.inline) + .scrollDismissesKeyboard(.interactively) + .onDisappear { + dismissKeyboard() + } + .task { + if let client = servers.activeClient() { + hostInfo = try? await client.userSystemInfo() + } + } + } +} + +// MARK: - 2. 已配对的电脑(历史配对 + 配对新的电脑) + +struct PairedComputersSettingsView: View { + @Environment(ServerStore.self) private var servers + @State private var showingPairSheet = false + + var body: some View { + List { + Section { + Button { + showingPairSheet = true + } label: { + HStack(spacing: 12) { + ZStack { + RoundedRectangle(cornerRadius: 10, style: .continuous) + .fill(Color.accentColor.opacity(0.14)) + .frame(width: 40, height: 40) + Image(systemName: "qrcode.viewfinder") + .font(.system(size: 18, weight: .semibold)) + .foregroundStyle(Color.accentColor) + } + VStack(alignment: .leading, spacing: 3) { + Text("配对新的电脑") + .font(.headline) + .foregroundStyle(.primary) + Text("扫描桌面端二维码、粘贴邀请码或手动输入地址") + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + Image(systemName: "plus.circle.fill") + .font(.title3) + .foregroundStyle(Color.accentColor) + } + .padding(.vertical, 4) + } + } header: { + Text("新增连接") + } + + Section { + if servers.profiles.isEmpty { + ContentUnavailableView( + "暂无历史配对电脑", + systemImage: "desktopcomputer.trianglebadge.exclamationmark", + description: Text("点击上方「配对新的电脑」连接你的 VibeX 桌面端。") + ) + .padding(.vertical, 16) + } else { ForEach(servers.profiles) { profile in - NavigationLink(value: profile) { + let isActive = servers.activeProfile?.id == profile.id + NavigationLink { + ServerDetailView(profile: profile) + } label: { + HStack(spacing: 12) { + ZStack { + Circle() + .fill(isActive ? Color.green.opacity(0.15) : Color.secondary.opacity(0.12)) + .frame(width: 38, height: 38) + Image(systemName: isActive ? "laptopcomputer.and.iphone" : "desktopcomputer") + .font(.system(size: 16, weight: .semibold)) + .foregroundStyle(isActive ? Color.green : Color.secondary) + } + + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 6) { + Text(profile.serverName) + .font(.body.weight(.semibold)) + if isActive { + Text("当前连接") + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + Capsule().fill(Color.green.opacity(0.16)) + ) + .foregroundStyle(Color.green) + } + } + Text(profile.origin) + .font(.caption.monospaced()) + .foregroundStyle(.secondary) + Text("设备:\(profile.deviceName) · VibeX v\(profile.serverVersion)") + .font(.caption2) + .foregroundStyle(.tertiary) + } + + Spacer() + + if !isActive { + Button("连接") { + servers.setActive(profile.id) + } + .buttonStyle(.bordered) + .controlSize(.small) + } + } + .padding(.vertical, 4) + } + .swipeActions(edge: .trailing, allowsFullSwipe: true) { + Button(role: .destructive) { + servers.remove(profile.id) + } label: { + Label("移除", systemImage: "trash") + } + } + } + } + } header: { + Text("历史配对的电脑 (\(servers.profiles.count))") + } footer: { + Text("点击任意电脑可查看连接诊断详情,左滑可移除历史配对记录。") + } + } + .navigationTitle("已配对的电脑") + .navigationBarTitleDisplayMode(.inline) + .sheet(isPresented: $showingPairSheet) { + NavigationStack { + PairView() + } + } + } +} + +// MARK: - 3. 技能中心(技能 / MCP / 插件 / 子代理) + +enum SkillsHubSegment: String, CaseIterable, Identifiable { + case skills = "技能" + case mcp = "MCP" + case plugins = "插件" + case subagents = "子代理" + + var id: String { rawValue } + + var icon: String { + switch self { + case .skills: return "sparkles" + case .mcp: return "server.rack" + case .plugins: return "puzzlepiece.extension.fill" + case .subagents: return "person.2.badge.gearshape.fill" + } + } +} + +struct SkillsHubSettingsView: View { + @Environment(ServerStore.self) private var servers + @State private var selectedSegment: SkillsHubSegment = .skills + @State private var searchQuery = "" + @FocusState private var isSearchFocused: Bool + @State private var searchBarGlobalFrame: CGRect = .zero + + @State private var skills: [LocalSkillItem] = [] + @State private var mcpServers: [LocalMcpServerItem] = [] + @State private var plugins: [PluginCatalogItem] = [] + @State private var roles: [CollabRole] = [] + @State private var agents: [CatalogAgent] = [] + + @State private var isLoading = false + @State private var errorMessage: String? + @State private var selectedSkillForDetail: LocalSkillItem? + + var body: some View { + VStack(spacing: 0) { + // Top 4-tab segment bar: 技能 · MCP · 插件 · 子代理 + VStack(spacing: 10) { + HStack(spacing: 8) { + ForEach(SkillsHubSegment.allCases) { segment in + let isSelected = selectedSegment == segment + Button { + withAnimation(.snappy(duration: 0.22)) { + selectedSegment = segment + } + } label: { + HStack(spacing: 5) { + Image(systemName: segment.icon) + .font(.system(size: 12, weight: .semibold)) + Text(segment.rawValue) + .font(.subheadline.weight(.semibold)) + Text("\(count(for: segment))") + .font(.caption2.monospacedDigit()) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background( + Capsule().fill( + isSelected + ? Color.white.opacity(0.24) + : Color.secondary.opacity(0.14) + ) + ) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 8) + .background( + RoundedRectangle(cornerRadius: 10, style: .continuous) + .fill(isSelected ? Color.accentColor : Color(.secondarySystemGroupedBackground)) + ) + .foregroundStyle(isSelected ? Color.white : Color.primary) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, 14) + + // Search bar + HStack(spacing: 8) { + Image(systemName: "magnifyingglass") + .font(.system(size: 14)) + .foregroundStyle(isSearchFocused ? Color.accentColor : Color.secondary) + TextField("搜索\(selectedSegment.rawValue)...", text: $searchQuery) + .font(.subheadline) + .focused($isSearchFocused) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .submitLabel(.search) + if !searchQuery.isEmpty { + Button { + searchQuery = "" + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + } + if isSearchFocused || !searchQuery.isEmpty { + Button { + withAnimation(.easeOut(duration: 0.18)) { + isSearchFocused = false + searchQuery = "" + } + dismissKeyboard() + } label: { + Text("取消") + .font(.subheadline.weight(.medium)) + .foregroundStyle(Color.accentColor) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, 12) + .padding(.vertical, 8) + .background( + GeometryReader { geo in + RoundedRectangle(cornerRadius: 10, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + .onAppear { searchBarGlobalFrame = geo.frame(in: .global) } + .onChange(of: geo.frame(in: .global)) { _, f in searchBarGlobalFrame = f } + } + ) + .padding(.horizontal, 14) + } + .padding(.vertical, 10) + .background(Color(.systemGroupedBackground)) + + if isLoading && skills.isEmpty && mcpServers.isEmpty && plugins.isEmpty && roles.isEmpty { + Spacer() + ProgressView("正在同步\(selectedSegment.rawValue)目录...") + Spacer() + } else { + List { + if let errorMessage { + Section { + Text(errorMessage) + .font(.caption) + .foregroundStyle(.red) + } + } + + switch selectedSegment { + case .skills: + skillsListContent + case .mcp: + mcpListContent + case .plugins: + pluginsListContent + case .subagents: + subagentsListContent + } + } + .listStyle(.insetGrouped) + .scrollDismissesKeyboard(.immediately) + .refreshable { + await reloadAll() + } + } + } + .background(Color(.systemGroupedBackground)) + .navigationTitle("技能与扩展") + .navigationBarTitleDisplayMode(.inline) + .onDisappear { + dismissKeyboard() + } + .onReceive(NotificationCenter.default.publisher(for: .vibexTapOutsideInput)) { note in + guard isSearchFocused || !searchQuery.isEmpty else { return } + if let locationValue = note.userInfo?["location"] as? NSValue { + let point = locationValue.cgPointValue + if !searchBarGlobalFrame.insetBy(dx: -8, dy: -8).contains(point) { + withAnimation(.easeOut(duration: 0.18)) { + isSearchFocused = false + searchQuery = "" + } + dismissKeyboard() + } + } + } + .task { + await reloadAll() + } + .sheet(item: $selectedSkillForDetail) { skill in + if let client = servers.activeClient() { + LocalSkillDetailSheet(skill: skill, client: client) + } + } + } + + private func count(for segment: SkillsHubSegment) -> Int { + switch segment { + case .skills: return skills.count + case .mcp: return mcpServers.count + case .plugins: return plugins.count + case .subagents: return roles.count + agents.count + } + } + + @ViewBuilder + private var skillsListContent: some View { + let filtered = filteredSkills + if filtered.isEmpty { + ContentUnavailableView( + "暂无匹配的技能", + systemImage: "sparkles", + description: Text("桌面端安装的本地与全局 Agent 技能将在此显示。") + ) + } else { + Section("已安装技能 (\(filtered.count))") { + ForEach(filtered) { skill in + Button { + selectedSkillForDetail = skill + } label: { + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 8) { + Image(systemName: "sparkles") + .font(.caption.weight(.bold)) + .foregroundStyle(.purple) + Text(skill.name) + .font(.body.weight(.semibold)) + .foregroundStyle(.primary) + Spacer() + if skill.global { + Text("全局") + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Capsule().fill(Color.purple.opacity(0.14))) + .foregroundStyle(.purple) + } + Image(systemName: "chevron.right") + .font(.caption2) + .foregroundStyle(.tertiary) + } + if let desc = skill.description, !desc.isEmpty { + Text(desc) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + } + if !skill.apps.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 6) { + ForEach(skill.apps, id: \.self) { app in + Text(app) + .font(.caption2.monospaced()) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(Color.secondary.opacity(0.12)) + ) + .foregroundStyle(.secondary) + } + } + } + } + } + .padding(.vertical, 4) + } + .buttonStyle(.plain) + } + } + } + } + + @ViewBuilder + private var mcpListContent: some View { + let filtered = filteredMcpServers + if filtered.isEmpty { + ContentUnavailableView( + "暂无 MCP 服务", + systemImage: "server.rack", + description: Text("在桌面端配置的本地或远程 MCP 服务器会同步显示在此处。") + ) + } else { + Section("已配置 MCP 服务 (\(filtered.count))") { + ForEach(filtered) { server in + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 8) { + Image(systemName: "server.rack") + .font(.caption.weight(.bold)) + .foregroundStyle(.blue) + Text(server.id) + .font(.body.weight(.semibold)) + Spacer() + Text(server.transportLabel) + .font(.caption2.monospaced().weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Capsule().fill(Color.blue.opacity(0.14))) + .foregroundStyle(.blue) + if server.global { + Text("全局") + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Capsule().fill(Color.green.opacity(0.14))) + .foregroundStyle(.green) + } + } + Text(server.commandSummary) + .font(.caption.monospaced()) + .foregroundStyle(.secondary) + .lineLimit(2) + if !server.apps.isEmpty { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 6) { + ForEach(server.apps, id: \.self) { app in + Text(app) + .font(.caption2.monospaced()) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + RoundedRectangle(cornerRadius: 5, style: .continuous) + .fill(Color.secondary.opacity(0.12)) + ) + .foregroundStyle(.secondary) + } + } + } + } + } + .padding(.vertical, 4) + } + } + } + } + + @ViewBuilder + private var pluginsListContent: some View { + let filtered = filteredPlugins + if filtered.isEmpty { + ContentUnavailableView( + "暂无已安装插件", + systemImage: "puzzlepiece.extension", + description: Text("在 VibeX 桌面端插件中心安装的插件将显示在此处。") + ) + } else { + Section("已安装插件 (\(filtered.count))") { + ForEach(filtered) { plugin in + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 8) { + Image(systemName: "puzzlepiece.extension.fill") + .font(.caption.weight(.bold)) + .foregroundStyle(plugin.enabled ? .orange : .secondary) + Text(plugin.name) + .font(.body.weight(.semibold)) + Text("v\(plugin.version)") + .font(.caption2.monospaced()) + .foregroundStyle(.secondary) + Spacer() + Text(plugin.enabled ? "已启用" : "已停用") + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background( + Capsule().fill( + plugin.enabled + ? Color.green.opacity(0.15) + : Color.secondary.opacity(0.14) + ) + ) + .foregroundStyle(plugin.enabled ? .green : .secondary) + } + if let desc = plugin.description, !desc.isEmpty { + Text(desc) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + } + HStack(spacing: 10) { + Label(plugin.builtin ? "内置插件" : plugin.sourceKind, systemImage: "shippingbox") + .font(.caption2) + .foregroundStyle(.tertiary) + if !plugin.skills.isEmpty { + Label("\(plugin.skills.count) 项技能", systemImage: "sparkles") + .font(.caption2) + .foregroundStyle(.tertiary) + } + if plugin.mcpCount > 0 { + Label("\(plugin.mcpCount) 个 MCP", systemImage: "server.rack") + .font(.caption2) + .foregroundStyle(.tertiary) + } + } + } + .padding(.vertical, 4) + } + } + } + } + + @ViewBuilder + private var subagentsListContent: some View { + let matchedRoles = filteredRoles + let matchedAgents = filteredAgents + + if matchedRoles.isEmpty && matchedAgents.isEmpty { + ContentUnavailableView( + "暂无子代理与角色", + systemImage: "person.2.badge.gearshape", + description: Text("协作空间角色与已启用的子代理执行器将在此展示。") + ) + } else { + if !matchedRoles.isEmpty { + Section("子代理角色预设 (\(matchedRoles.count))") { + ForEach(matchedRoles) { role in + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 8) { + Image(systemName: "person.crop.circle.badge.Checkmark") + .foregroundStyle(.indigo) + Text(role.name) + .font(.body.weight(.semibold)) + if let team = role.teamId, !team.isEmpty { + Text(team) + .font(.caption2.weight(.medium)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Capsule().fill(Color.indigo.opacity(0.14))) + .foregroundStyle(.indigo) + } + Spacer() + AgentModelLabel(agent: role.agentId, model: AgentBrand.displayName(role.agentId), iconSize: 12) + .font(.caption2) + .foregroundStyle(.secondary) + } + let desc = role.summary.isEmpty ? role.personaPrompt : role.summary + if !desc.isEmpty { + Text(desc) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + } + } + .padding(.vertical, 4) + } + } + } + + if !matchedAgents.isEmpty { + Section("可用 Agent 执行引擎 (\(matchedAgents.count))") { + ForEach(matchedAgents) { agent in + HStack(spacing: 10) { + AgentIconView(agent: agent.id, size: 22) + .overlay(alignment: .bottomTrailing) { + Circle() + .fill(agent.usable ? Color.green : Color.orange) + .frame(width: 7, height: 7) + .overlay(Circle().stroke(Color(.secondarySystemGroupedBackground), lineWidth: 1.5)) + .offset(x: 2, y: 2) + } VStack(alignment: .leading, spacing: 2) { - Text(profile.origin) - Text("VibeX \(profile.serverVersion)") - .font(.footnote) + Text(AgentBrand.displayName(agent.id, hostName: agent.displayName)) + .font(.body.weight(.medium)) + Text(agent.id) + .font(.caption2.monospaced()) + .foregroundStyle(.secondary) + } + Spacer() + Text(agent.usable ? "就绪" : "未就绪") + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 7) + .padding(.vertical, 3) + .background( + Capsule().fill( + agent.usable + ? Color.green.opacity(0.15) + : Color.orange.opacity(0.15) + ) + ) + .foregroundStyle(agent.usable ? .green : .orange) + } + .padding(.vertical, 2) + } + } + } + } + } + + private var filteredSkills: [LocalSkillItem] { + let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !q.isEmpty else { return skills } + return skills.filter { + $0.name.lowercased().contains(q) + || ($0.description?.lowercased().contains(q) ?? false) + || $0.id.lowercased().contains(q) + } + } + + private var filteredMcpServers: [LocalMcpServerItem] { + let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !q.isEmpty else { return mcpServers } + return mcpServers.filter { + $0.id.lowercased().contains(q) + || $0.commandSummary.lowercased().contains(q) + } + } + + private var filteredPlugins: [PluginCatalogItem] { + let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !q.isEmpty else { return plugins } + return plugins.filter { + $0.name.lowercased().contains(q) + || ($0.description?.lowercased().contains(q) ?? false) + || $0.id.lowercased().contains(q) + } + } + + private var filteredRoles: [CollabRole] { + let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !q.isEmpty else { return roles } + return roles.filter { + $0.name.lowercased().contains(q) + || $0.personaPrompt.lowercased().contains(q) + || $0.agentId.lowercased().contains(q) + } + } + + private var filteredAgents: [CatalogAgent] { + let q = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + guard !q.isEmpty else { return agents } + return agents.filter { + $0.displayName.lowercased().contains(q) + || $0.id.lowercased().contains(q) + } + } + + private func reloadAll() async { + guard let client = servers.activeClient() else { + errorMessage = "当前未连接电脑,请先配对电脑后查看技能与扩展。" + return + } + isLoading = true + errorMessage = nil + defer { isLoading = false } + + async let fetchedSkills = try? client.localSkills() + async let fetchedMcp = try? client.localMcpServers() + async let fetchedPlugins = try? client.pluginCatalog() + async let fetchedRoles = try? client.collabRoles() + async let fetchedCatalog = try? client.agentCatalog() + + if let s = await fetchedSkills { skills = s } + if let m = await fetchedMcp { mcpServers = m } + if let p = await fetchedPlugins { plugins = p } + if let r = await fetchedRoles { roles = r } + if let c = await fetchedCatalog { agents = c } + } +} + +struct LocalSkillDetailSheet: View { + let skill: LocalSkillItem + let client: HostClient + + @Environment(\.dismiss) private var dismiss + @State private var content: LocalSkillContentItem? + @State private var isLoading = true + + var body: some View { + NavigationStack { + ScrollView { + VStack(alignment: .leading, spacing: 14) { + VStack(alignment: .leading, spacing: 6) { + HStack { + Text(skill.name) + .font(.title3.weight(.bold)) + Spacer() + if skill.global { + Text("全局技能") + .font(.caption.weight(.semibold)) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background(Capsule().fill(Color.purple.opacity(0.15))) + .foregroundStyle(.purple) + } + } + if let desc = skill.description, !desc.isEmpty { + Text(desc) + .font(.subheadline) + .foregroundStyle(.secondary) + } + if !skill.path.isEmpty { + Text(skill.path) + .font(.caption2.monospaced()) + .foregroundStyle(.tertiary) + } + } + .padding(14) + .background( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + + if isLoading { + HStack { + Spacer() + ProgressView("读取 SKILL.md...") + Spacer() + } + .padding(.vertical, 32) + } else if let content, !content.content.isEmpty { + Text(content.content) + .font(.system(.footnote, design: .monospaced)) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(14) + .background( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + } else { + Text("未能读取到技能内容") + .font(.subheadline) + .foregroundStyle(.secondary) + } + } + .padding(16) + } + .background(Color(.systemGroupedBackground)) + .navigationTitle(skill.name) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("完成") { dismiss() } + } + } + .task { + isLoading = true + content = try? await client.readLocalSkill(skillID: skill.id) + isLoading = false + } + } + } +} + +// MARK: - 5. 字体设置页(字号大小 + 字体样式) + +struct FontSettingsDetailView: View { + @Environment(AppAppearanceStore.self) private var appearance + + var body: some View { + List { + Section("实时预览") { + VStack(alignment: .leading, spacing: 10) { + HStack { + Text("VibeX 字体与排版预览") + .font(.system(size: appearance.fontSizePreset.pointPreviewSize + 2, weight: .semibold, design: appearance.fontStylePreset.fontDesign)) + Spacer() + Text("\(appearance.fontSizePreset.title) · \(appearance.fontSizePreset.scaleLabel)") + .font(.caption.monospacedDigit()) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background(Capsule().fill(Color.accentColor.opacity(0.14))) + .foregroundStyle(Color.accentColor) + } + + Text("支持多智能体协作空间、四列看板与实时代码审查。The quick brown fox jumps over the lazy dog.") + .font(.system(size: appearance.fontSizePreset.pointPreviewSize, design: appearance.fontStylePreset.fontDesign)) + .foregroundStyle(.primary) + + Text("let session = try await client.createConversation(agentId: \"claude_code\")") + .font(.system(size: max(12, appearance.fontSizePreset.pointPreviewSize - 2), design: .monospaced)) + .foregroundStyle(.secondary) + .padding(8) + .frame(maxWidth: .infinity, alignment: .leading) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color.secondary.opacity(0.10)) + ) + } + .padding(.vertical, 6) + } + + Section("字号大小") { + HStack(spacing: 8) { + ForEach(AppFontSizePreset.allCases) { preset in + let isSelected = appearance.fontSizePreset == preset + Button { + withAnimation(.snappy(duration: 0.2)) { + appearance.fontSizePreset = preset + } + } label: { + VStack(spacing: 4) { + Text(preset.title) + .font(.subheadline.weight(.semibold)) + Text(preset.scaleLabel) + .font(.caption2.monospacedDigit()) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 10) + .background( + RoundedRectangle(cornerRadius: 10, style: .continuous) + .fill(isSelected ? Color.accentColor : Color.secondary.opacity(0.10)) + ) + .foregroundStyle(isSelected ? Color.white : Color.primary) + } + .buttonStyle(.plain) + } + } + .padding(.vertical, 4) + } + + Section("字体样式") { + ForEach(AppFontStylePreset.allCases) { style in + let isSelected = appearance.fontStylePreset == style + Button { + withAnimation(.snappy(duration: 0.2)) { + appearance.fontStylePreset = style + } + } label: { + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 3) { + Text(style.title) + .font(.system(.body, design: style.fontDesign).weight(.semibold)) + .foregroundStyle(.primary) + Text(style.subtitle) + .font(.caption) .foregroundStyle(.secondary) } + Spacer() + if isSelected { + Image(systemName: "checkmark.circle.fill") + .foregroundStyle(Color.accentColor) + .font(.title3) + } } + .padding(.vertical, 4) } - .onDelete { offsets in - offsets.map { servers.profiles[$0] }.forEach(servers.forget) + .buttonStyle(.plain) + } + } + } + .navigationTitle("字体") + .navigationBarTitleDisplayMode(.inline) + } +} + +// MARK: - 6. 通知设置页 + +struct NotificationSettingsDetailView: View { + @Environment(AppAppearanceStore.self) private var appearance + + var body: some View { + @Bindable var bindableAppearance = appearance + Form { + Section("系统推送权限") { + HStack { + VStack(alignment: .leading, spacing: 3) { + Text("iOS 系统通知状态") + .font(.body.weight(.medium)) + Text(appearance.systemNotificationStatusText) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + Button("请求/刷新权限") { + Task { + await appearance.requestSystemNotificationPermission() + } } - Button("配对电脑", systemImage: "plus") { showingPair = true } + .buttonStyle(.borderedProminent) + .controlSize(.small) } } - .navigationTitle("设置") - .navigationDestination(for: ServerProfile.self) { ServerDetailView(profile: $0) } - .sheet(isPresented: $showingPair) { PairView() } + + Section("事件提醒") { + Toggle("任务完成通知", isOn: $bindableAppearance.notifyTurnCompleted) + Toggle("权限审批与提问提醒", isOn: $bindableAppearance.notifyApprovalRequired) + Toggle("协作空间 @ 与新消息通知", isOn: $bindableAppearance.notifyCollabMessages) + } + + Section("声音与触感") { + Toggle("消息提示音", isOn: $bindableAppearance.notificationSound) + Toggle("触感震动反馈 (Haptics)", isOn: $bindableAppearance.hapticFeedback) + } + } + .navigationTitle("通知") + .navigationBarTitleDisplayMode(.inline) + .task { + await appearance.refreshNotificationAuthorizationStatus() + } + } +} + +// MARK: - 7. 关于 VibeX 详情页 + +struct AboutVibeXDetailView: View { + @Environment(ServerStore.self) private var servers + + 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") + .font(.title3.weight(.bold)) + Text("本地优先的多智能体研发工作台 iOS 伴侣端") + .font(.caption) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 12) + } + + Section("版本与协议信息") { + LabeledContent("iOS 客户端版本", value: "v0.4.2") + LabeledContent("远程通讯协议", value: "Remote Protocol v1") + if let active = servers.activeProfile { + LabeledContent("已连接桌面端", value: active.serverName) + LabeledContent("桌面端版本", value: "v\(active.serverVersion)") + LabeledContent("桌面端地址", value: active.origin) + } + } + + 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") + } } + .navigationTitle("关于 VibeX") + .navigationBarTitleDisplayMode(.inline) } } #Preview { - SettingsView().environment(ServerStore(defaults: UserDefaults(suiteName: "preview")!)) + SettingsView() + .environment(ServerStore(defaults: UserDefaults(suiteName: "preview")!)) + .environment(AppAppearanceStore(defaults: UserDefaults(suiteName: "preview")!)) } diff --git a/mobile/ios/App/StreamingText.swift b/mobile/ios/App/StreamingText.swift index 1857a51a0..99db5c717 100644 --- a/mobile/ios/App/StreamingText.swift +++ b/mobile/ios/App/StreamingText.swift @@ -1,97 +1,1854 @@ import SwiftUI +import UIKit -/// An assistant answer. As the transcript grows, the new words resolve out of blur one after another; -/// once the turn is done a small action row appears. -struct StreamingMessageText: View { - let text: String - let streaming: Bool +// MARK: - Attachment Image Store & Preview Item - @State private var settled = 0 - @State private var progress = 1.0 - @State private var copied = false +struct PreviewableImageItem: Identifiable, Equatable { + let id: String + let image: UIImage? + let urlString: String? + let title: String + + init(id: String = UUID().uuidString, image: UIImage? = nil, urlString: String? = nil, title: String = "图片预览") { + self.id = id + self.image = image + self.urlString = urlString + self.title = title + } + + static func == (lhs: PreviewableImageItem, rhs: PreviewableImageItem) -> Bool { + lhs.id == rhs.id && lhs.urlString == rhs.urlString && lhs.title == rhs.title + } +} + +/// Keeps user-attached `UIImage`s in memory (and caches decoded data-URLs) so user bubbles, +/// Markdown images, and the zoomable lightbox can render and annotate them natively. +@MainActor +final class AttachmentImageStore { + static let shared = AttachmentImageStore() + private var images: [String: (image: UIImage, fileName: String)] = [:] + + func register(image: UIImage, fileName: String) -> String { + let token = "att-\(UUID().uuidString.prefix(8).lowercased())" + images[token] = (image, fileName) + return token + } + + func update(token: String, image: UIImage, fileName: String) { + images[token] = (image, fileName) + } + + func lookup(token: String) -> (image: UIImage, fileName: String)? { + images[token] + } + + func latestImages(limit: Int) -> [(token: String, image: UIImage, fileName: String)] { + Array(images.map { (token: $0.key, image: $0.value.image, fileName: $0.value.fileName) }.suffix(limit)) + } + + /// Parses attachment markers like `[图片附件: photo.jpg #att-1a2b3c4d]` or legacy `[图片附件 ×N]` + /// from the beginning of a user message, returning extracted preview items and the remaining text. + func extractUserAttachments(from text: String) -> (items: [PreviewableImageItem], cleanText: String) { + var found: [PreviewableImageItem] = [] + var remainingLines: [String] = [] + let lines = text.components(separatedBy: "\n") + + for line in lines { + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.hasPrefix("[图片附件"), trimmed.hasSuffix("]") { + // Extract all `#att-xxxxxxxx` tokens on this line + let pattern = #"#(att-[a-z0-9]+)"# + if let regex = try? NSRegularExpression(pattern: pattern) { + let ns = trimmed as NSString + let matches = regex.matches(in: trimmed, range: NSRange(location: 0, length: ns.length)) + for match in matches where match.numberOfRanges > 1 { + let token = ns.substring(with: match.range(at: 1)) + if let entry = lookup(token: token) { + found.append( + PreviewableImageItem( + id: token, + image: entry.image, + urlString: nil, + title: entry.fileName + ) + ) + } + } + } + if found.isEmpty { + // Fallback placeholder item when legacy `[图片附件 ×N]` has no cached token + found.append( + PreviewableImageItem( + id: trimmed, + image: nil, + urlString: nil, + title: trimmed.trimmingCharacters(in: CharacterSet(charactersIn: "[]")) + ) + ) + } + } else { + remainingLines.append(line) + } + } + + let cleaned = remainingLines.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) + return (found, cleaned) + } + + static func decodeImage(from src: String) -> UIImage? { + let trimmed = src.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.hasPrefix("att-"), let entry = AttachmentImageStore.shared.lookup(token: trimmed) { + return entry.image + } + if trimmed.hasPrefix("data:image/"), + let comma = trimmed.firstIndex(of: ",") + { + let base64 = String(trimmed[trimmed.index(after: comma)...]) + if let data = Data(base64Encoded: base64, options: .ignoreUnknownCharacters) { + return UIImage(data: data) + } + } + if trimmed.hasPrefix("file://"), + let url = URL(string: trimmed), + let data = try? Data(contentsOf: url) + { + return UIImage(data: data) + } + if trimmed.hasPrefix("/"), + FileManager.default.fileExists(atPath: trimmed), + let data = try? Data(contentsOf: URL(fileURLWithPath: trimmed)) + { + return UIImage(data: data) + } + return nil + } +} + +// MARK: - Zoomable Image Preview (`ZoomableImagePreview.tsx` + `ImagePreviewToolbar.tsx`) + +enum ImageAnnotationTool: String, Equatable { + case view + case rect + case ellipse + case triangle + case brush +} + +struct ImageAnnotationItem: Identifiable, Equatable { + enum Kind: Equatable { + case rect(start: CGPoint, end: CGPoint) + case ellipse(start: CGPoint, end: CGPoint) + case triangle(start: CGPoint, end: CGPoint) + case brush(points: [CGPoint]) + } + + let id = UUID() + var kind: Kind + var color: Color + var lineWidth: CGFloat +} + +/// Full-screen lightbox and annotation studio matching VibeX desktop's `ZoomableImagePreview` + `ImagePreviewDialog`. +struct ZoomableImagePreviewSheet: View { + let item: PreviewableImageItem + var onUpdateImage: ((UIImage) -> Void)? = nil + + @Environment(\.dismiss) private var dismiss + @State private var loadedImage: UIImage? + @State private var isLoading = false + @State private var scale: CGFloat = 1.0 + @State private var lastScale: CGFloat = 1.0 + @State private var offset: CGSize = .zero + @State private var lastOffset: CGSize = .zero + + // Annotation state matching `ImagePreviewToolbar.tsx` + @State private var tool: ImageAnnotationTool = .view + @State private var activeMarkKind: ImageAnnotationTool = .rect + @State private var selectedColor: Color = Color(red: 0.94, green: 0.27, blue: 0.27) + @State private var strokeWidth: CGFloat = 3.5 + @State private var history: [[ImageAnnotationItem]] = [[]] + @State private var historyIndex: Int = 0 + @State private var draftAnnotation: ImageAnnotationItem? + @State private var chromeVisible = true + @State private var copiedToast = false + @State private var savedToast = false + + private static let presetColors: [Color] = [ + Color(red: 0.94, green: 0.27, blue: 0.27), // Red + Color(red: 0.96, green: 0.62, blue: 0.04), // Amber + Color(red: 0.06, green: 0.73, blue: 0.51), // Emerald + Color(red: 0.23, green: 0.51, blue: 0.96), // Blue + Color(red: 0.66, green: 0.33, blue: 0.97), // Purple + Color.white, + ] + + private static let zoomPresets: [CGFloat] = [0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0] + + private var annotations: [ImageAnnotationItem] { + guard history.indices.contains(historyIndex) else { return [] } + return history[historyIndex] + } + + private var visibleAnnotations: [ImageAnnotationItem] { + if let draftAnnotation { + return annotations + [draftAnnotation] + } + return annotations + } + + private var canUndo: Bool { historyIndex > 0 } + private var canRedo: Bool { historyIndex + 1 < history.count } var body: some View { - VStack(alignment: .leading, spacing: 8) { - rendered - .font(.system(size: 15)) - .lineSpacing(4) - .textSelection(.enabled) - .frame(maxWidth: .infinity, alignment: .leading) - if !streaming && !text.isEmpty { + ZStack { + Color.black.ignoresSafeArea() + + // Dot-grid backdrop matching `zoomableImagePreview.css` + GeometryReader { geo in + Canvas { context, size in + let spacing: CGFloat = 22 + let dotRadius: CGFloat = 0.8 + var y: CGFloat = spacing / 2 + while y < size.height { + var x: CGFloat = spacing / 2 + while x < size.width { + let rect = CGRect(x: x - dotRadius, y: y - dotRadius, width: dotRadius * 2, height: dotRadius * 2) + context.fill(Path(ellipseIn: rect), with: .color(.white.opacity(0.11))) + x += spacing + } + y += spacing + } + } + .ignoresSafeArea() + + if let uiImage = loadedImage ?? item.image { + imageCanvas(uiImage: uiImage, viewportSize: geo.size) + } else if isLoading { + VStack(spacing: 12) { + ProgressView().tint(.white) + Text("正在加载图片…") + .font(.system(size: 13)) + .foregroundStyle(.white.opacity(0.7)) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + VStack(spacing: 12) { + Image(systemName: "photo") + .font(.system(size: 38, weight: .light)) + .foregroundStyle(.white.opacity(0.55)) + Text(item.title) + .font(.system(size: 14, weight: .medium)) + .foregroundStyle(.white.opacity(0.85)) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + + // Top Chrome Bar + VStack { + topBar + Spacer() + if let uiImage = loadedImage ?? item.image { + bottomToolbar(uiImage: uiImage) + } + } + .padding(.horizontal, 14) + .padding(.vertical, 10) + + if copiedToast || savedToast { + VStack { + Text(copiedToast ? "已复制图片到剪贴板" : "已保存到相册") + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(.white) + .padding(.horizontal, 14) + .padding(.vertical, 8) + .background(.ultraThinMaterial, in: Capsule()) + .padding(.top, 64) + Spacer() + } + .transition(.opacity.combined(with: .move(edge: .top))) + } + } + .preferredColorScheme(.dark) + .task { + await loadImageIfNeeded() + } + } + + private var topBar: some View { + HStack(spacing: 10) { + Button { + if let uiImage = loadedImage ?? item.image, !annotations.isEmpty, let onUpdateImage { + onUpdateImage(renderAnnotatedImage(base: uiImage)) + } + dismiss() + } label: { + Image(systemName: "xmark") + .font(.system(size: 14, weight: .semibold)) + .foregroundStyle(.white) + .frame(width: 34, height: 34) + .background(.ultraThinMaterial, in: Circle()) + } + .buttonStyle(.plain) + + VStack(alignment: .leading, spacing: 1) { + Text(item.title) + .font(.system(size: 13.5, weight: .semibold)) + .foregroundStyle(.white) + .lineLimit(1) + if let uiImage = loadedImage ?? item.image { + Text("\(Int(uiImage.size.width * uiImage.scale)) × \(Int(uiImage.size.height * uiImage.scale)) px · \(Int(round(scale * 100)))%") + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(.white.opacity(0.65)) + } + } + + Spacer(minLength: 8) + + if let uiImage = loadedImage ?? item.image { Button { - UIPasteboard.general.string = text - withAnimation { copied = true } + let finalImage = annotations.isEmpty ? uiImage : renderAnnotatedImage(base: uiImage) + UIPasteboard.general.image = finalImage + UIImpactFeedbackGenerator(style: .light).impactOccurred() + withAnimation { copiedToast = true } Task { try? await Task.sleep(for: .seconds(1.5)) - withAnimation { copied = false } + withAnimation { copiedToast = false } } } label: { - Image(systemName: copied ? "checkmark" : "doc.on.doc") - .font(.system(size: 13)) - .foregroundStyle(.secondary) - .frame(width: 28, height: 24) - .contentTransition(.symbolEffect(.replace)) + Image(systemName: copiedToast ? "checkmark" : "doc.on.doc") + .font(.system(size: 13.5, weight: .semibold)) + .foregroundStyle(copiedToast ? .green : .white) + .frame(width: 34, height: 34) + .background(.ultraThinMaterial, in: Circle()) + } + .buttonStyle(.plain) + + Button { + let finalImage = annotations.isEmpty ? uiImage : renderAnnotatedImage(base: uiImage) + UIImageWriteToSavedPhotosAlbum(finalImage, nil, nil, nil) + UIImpactFeedbackGenerator(style: .medium).impactOccurred() + withAnimation { savedToast = true } + Task { + try? await Task.sleep(for: .seconds(1.5)) + withAnimation { savedToast = false } + } + } label: { + Image(systemName: savedToast ? "checkmark" : "square.and.arrow.down") + .font(.system(size: 13.5, weight: .semibold)) + .foregroundStyle(savedToast ? .green : .white) + .frame(width: 34, height: 34) + .background(.ultraThinMaterial, in: Circle()) + } + .buttonStyle(.plain) + } + } + } + + private func imageCanvas(uiImage: UIImage, viewportSize: CGSize) -> some View { + let fitted = fittedImageSize(for: uiImage.size, in: viewportSize) + return ZStack { + Image(uiImage: uiImage) + .resizable() + .scaledToFit() + .frame(width: fitted.width, height: fitted.height) + .overlay { + Canvas { context, size in + for ann in visibleAnnotations { + drawAnnotation(ann, in: &context, size: size) + } + } + } + .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous)) + .shadow(color: .black.opacity(0.45), radius: 18, y: 6) + .scaleEffect(scale) + .offset(offset) + .gesture(canvasDragGesture(in: fitted)) + .simultaneousGesture( + MagnificationGesture() + .onChanged { value in + guard tool == .view else { return } + scale = min(max(0.25, lastScale * value), 6.0) + } + .onEnded { _ in + lastScale = scale + if scale <= 1.0 { + withAnimation(.spring(response: 0.28, dampingFraction: 0.86)) { + offset = .zero + lastOffset = .zero + } + } + } + ) + .onTapGesture(count: 2) { + withAnimation(.spring(response: 0.3, dampingFraction: 0.85)) { + if abs(scale - 1.0) > 0.08 { + scale = 1.0 + lastScale = 1.0 + offset = .zero + lastOffset = .zero + } else { + scale = 2.4 + lastScale = 2.4 + } + } + } + } + .frame(width: viewportSize.width, height: viewportSize.height) + } + + private func canvasDragGesture(in fittedSize: CGSize) -> some Gesture { + DragGesture(minimumDistance: 1) + .onChanged { value in + if tool == .view { + offset = CGSize( + width: lastOffset.width + value.translation.width, + height: lastOffset.height + value.translation.height + ) + } else { + let normStart = CGPoint( + x: min(max(0, value.startLocation.x / max(1, fittedSize.width)), 1), + y: min(max(0, value.startLocation.y / max(1, fittedSize.height)), 1) + ) + let normCur = CGPoint( + x: min(max(0, value.location.x / max(1, fittedSize.width)), 1), + y: min(max(0, value.location.y / max(1, fittedSize.height)), 1) + ) + switch tool { + case .rect: + draftAnnotation = ImageAnnotationItem( + kind: .rect(start: normStart, end: normCur), + color: selectedColor, + lineWidth: strokeWidth + ) + case .ellipse: + draftAnnotation = ImageAnnotationItem( + kind: .ellipse(start: normStart, end: normCur), + color: selectedColor, + lineWidth: strokeWidth + ) + case .triangle: + draftAnnotation = ImageAnnotationItem( + kind: .triangle(start: normStart, end: normCur), + color: selectedColor, + lineWidth: strokeWidth + ) + case .brush: + if var existing = draftAnnotation, case .brush(var pts) = existing.kind { + pts.append(normCur) + existing.kind = .brush(points: pts) + draftAnnotation = existing + } else { + draftAnnotation = ImageAnnotationItem( + kind: .brush(points: [normStart, normCur]), + color: selectedColor, + lineWidth: strokeWidth + 1.5 + ) + } + case .view: + break + } + } + } + .onEnded { _ in + if tool == .view { + lastOffset = offset + } else if let draftAnnotation { + var next = annotations + next.append(draftAnnotation) + let trimmedHistory = Array(history.prefix(historyIndex + 1)) + [next] + history = trimmedHistory + historyIndex = trimmedHistory.count - 1 + self.draftAnnotation = nil + } + } + } + + private func bottomToolbar(uiImage _: UIImage) -> some View { + VStack(spacing: 8) { + if chromeVisible && tool != .view { + // Color & shape sub-bar + HStack(spacing: 10) { + if tool == .rect || tool == .ellipse || tool == .triangle { + ForEach([ + (ImageAnnotationTool.rect, "square"), + (ImageAnnotationTool.ellipse, "circle"), + (ImageAnnotationTool.triangle, "triangle"), + ], id: \.0.rawValue) { kind, icon in + Button { + activeMarkKind = kind + tool = kind + } label: { + Image(systemName: icon) + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(tool == kind ? .black : .white) + .frame(width: 28, height: 28) + .background(tool == kind ? Color.white : Color.white.opacity(0.12), in: Circle()) + } + .buttonStyle(.plain) + } + Divider().frame(height: 16).overlay(.white.opacity(0.2)) + } + + ForEach(Array(Self.presetColors.enumerated()), id: \.offset) { _, color in + Button { + selectedColor = color + } label: { + Circle() + .fill(color) + .frame(width: 20, height: 20) + .overlay( + Circle() + .strokeBorder(Color.white, lineWidth: selectedColor == color ? 2.2 : 0.6) + ) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, 12) + .padding(.vertical, 7) + .background(.ultraThinMaterial, in: Capsule()) + } + + HStack(spacing: 6) { + if chromeVisible { + toolbarToolButton( + icon: "arrow.up.and.down.and.arrow.left.and.right", + active: tool == .view + ) { + tool = .view + } + + toolbarToolButton( + icon: activeMarkKind == .ellipse ? "circle" : (activeMarkKind == .triangle ? "triangle" : "square"), + active: tool == .rect || tool == .ellipse || tool == .triangle + ) { + tool = activeMarkKind + } + + toolbarToolButton( + icon: "paintbrush.pointed", + active: tool == .brush + ) { + tool = .brush + } + + Divider().frame(height: 18).overlay(.white.opacity(0.2)) + + Button { + if canUndo { historyIndex -= 1 } + } label: { + Image(systemName: "arrow.uturn.backward") + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(canUndo ? .white : .white.opacity(0.3)) + .frame(width: 30, height: 30) + } + .buttonStyle(.plain) + .disabled(!canUndo) + + Button { + if canRedo { historyIndex += 1 } + } label: { + Image(systemName: "arrow.uturn.forward") + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(canRedo ? .white : .white.opacity(0.3)) + .frame(width: 30, height: 30) + } + .buttonStyle(.plain) + .disabled(!canRedo) + + Divider().frame(height: 18).overlay(.white.opacity(0.2)) + + Menu { + ForEach(Self.zoomPresets, id: \.self) { preset in + Button("\(Int(preset * 100))%") { + withAnimation(.spring(response: 0.26, dampingFraction: 0.86)) { + scale = preset + lastScale = preset + if preset == 1.0 { + offset = .zero + lastOffset = .zero + } + } + } + } + } label: { + Text("\(Int(round(scale * 100)))%") + .font(.system(size: 12, weight: .semibold, design: .monospaced)) + .foregroundStyle(.white) + .padding(.horizontal, 8) + .frame(height: 28) + .background(Color.white.opacity(0.12), in: Capsule()) + } + + Button { + withAnimation(.spring(response: 0.26, dampingFraction: 0.86)) { + scale = 1.0 + lastScale = 1.0 + offset = .zero + lastOffset = .zero + } + } label: { + Image(systemName: "arrow.up.left.and.down.right.magnifyingglass") + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(.white) + .frame(width: 30, height: 30) + } + .buttonStyle(.plain) + } + + Button { + withAnimation(.spring(response: 0.25, dampingFraction: 0.86)) { + chromeVisible.toggle() + } + } label: { + Image(systemName: chromeVisible ? "chevron.down.2" : "chevron.up.2") + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(.white.opacity(0.85)) + .frame(width: 30, height: 30) } .buttonStyle(.plain) - .accessibilityLabel("复制") - .transition(.opacity) } + .padding(.horizontal, 10) + .padding(.vertical, 6) + .background(.ultraThinMaterial, in: Capsule()) + } + } + + private func toolbarToolButton(icon: String, active: Bool, action: @escaping () -> Void) -> some View { + Button(action: action) { + Image(systemName: icon) + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(active ? .black : .white) + .frame(width: 30, height: 30) + .background(active ? Color.white : Color.clear, in: Circle()) + } + .buttonStyle(.plain) + } + + private func fittedImageSize(for imageSize: CGSize, in viewport: CGSize) -> CGSize { + let maxW = max(1, viewport.width - 24) + let maxH = max(1, viewport.height - 140) + guard imageSize.width > 0, imageSize.height > 0 else { + return CGSize(width: maxW, height: maxH) + } + let ratio = min(maxW / imageSize.width, maxH / imageSize.height) + return CGSize(width: imageSize.width * ratio, height: imageSize.height * ratio) + } + + private func drawAnnotation(_ ann: ImageAnnotationItem, in context: inout GraphicsContext, size: CGSize) { + let style = StrokeStyle(lineWidth: ann.lineWidth, lineCap: .round, lineJoin: .round) + switch ann.kind { + case .rect(let s, let e): + let rect = CGRect( + x: min(s.x, e.x) * size.width, + y: min(s.y, e.y) * size.height, + width: abs(e.x - s.x) * size.width, + height: abs(e.y - s.y) * size.height + ) + context.stroke(Path(roundedRect: rect, cornerRadius: 4), with: .color(ann.color), style: style) + case .ellipse(let s, let e): + let rect = CGRect( + x: min(s.x, e.x) * size.width, + y: min(s.y, e.y) * size.height, + width: abs(e.x - s.x) * size.width, + height: abs(e.y - s.y) * size.height + ) + context.stroke(Path(ellipseIn: rect), with: .color(ann.color), style: style) + case .triangle(let s, let e): + let minX = min(s.x, e.x) * size.width + let maxX = max(s.x, e.x) * size.width + let minY = min(s.y, e.y) * size.height + let maxY = max(s.y, e.y) * size.height + var path = Path() + path.move(to: CGPoint(x: (minX + maxX) / 2, y: minY)) + path.addLine(to: CGPoint(x: maxX, y: maxY)) + path.addLine(to: CGPoint(x: minX, y: maxY)) + path.closeSubpath() + context.stroke(path, with: .color(ann.color), style: style) + case .brush(let points): + guard let first = points.first else { return } + var path = Path() + path.move(to: CGPoint(x: first.x * size.width, y: first.y * size.height)) + for pt in points.dropFirst() { + path.addLine(to: CGPoint(x: pt.x * size.width, y: pt.y * size.height)) + } + context.stroke(path, with: .color(ann.color.opacity(0.88)), style: style) + } + } + + private func renderAnnotatedImage(base: UIImage) -> UIImage { + let renderer = UIGraphicsImageRenderer(size: base.size) + return renderer.image { _ in + base.draw(in: CGRect(origin: .zero, size: base.size)) + guard let cg = UIGraphicsGetCurrentContext() else { return } + let scaleFactor = max(base.size.width, base.size.height) / 360.0 + for ann in annotations { + cg.saveGState() + cg.setStrokeColor(UIColor(ann.color).cgColor) + cg.setLineWidth(ann.lineWidth * max(1, scaleFactor)) + cg.setLineCap(.round) + cg.setLineJoin(.round) + switch ann.kind { + case .rect(let s, let e): + let rect = CGRect( + x: min(s.x, e.x) * base.size.width, + y: min(s.y, e.y) * base.size.height, + width: abs(e.x - s.x) * base.size.width, + height: abs(e.y - s.y) * base.size.height + ) + cg.stroke(rect) + case .ellipse(let s, let e): + let rect = CGRect( + x: min(s.x, e.x) * base.size.width, + y: min(s.y, e.y) * base.size.height, + width: abs(e.x - s.x) * base.size.width, + height: abs(e.y - s.y) * base.size.height + ) + cg.strokeEllipse(in: rect) + case .triangle(let s, let e): + let minX = min(s.x, e.x) * base.size.width + let maxX = max(s.x, e.x) * base.size.width + let minY = min(s.y, e.y) * base.size.height + let maxY = max(s.y, e.y) * base.size.height + cg.beginPath() + cg.move(to: CGPoint(x: (minX + maxX) / 2, y: minY)) + cg.addLine(to: CGPoint(x: maxX, y: maxY)) + cg.addLine(to: CGPoint(x: minX, y: maxY)) + cg.closePath() + cg.strokePath() + case .brush(let points): + if let first = points.first { + cg.beginPath() + cg.move(to: CGPoint(x: first.x * base.size.width, y: first.y * base.size.height)) + for pt in points.dropFirst() { + cg.addLine(to: CGPoint(x: pt.x * base.size.width, y: pt.y * base.size.height)) + } + cg.strokePath() + } + } + cg.restoreGState() + } + } + } + + private func loadImageIfNeeded() async { + if item.image != nil { return } + guard let raw = item.urlString?.trimmingCharacters(in: .whitespacesAndNewlines), !raw.isEmpty else { return } + if let decoded = AttachmentImageStore.decodeImage(from: raw) { + loadedImage = decoded + return + } + guard let url = URL(string: raw), url.scheme == "http" || url.scheme == "https" else { return } + isLoading = true + defer { isLoading = false } + if let (data, _) = try? await URLSession.shared.data(from: url), + let img = UIImage(data: data) + { + loadedImage = img } - .animation(.easeOut(duration: 0.3), value: streaming) - .onAppear { settled = text.count } - .onChange(of: text) { old, new in - guard new.hasPrefix(old), new.count > old.count else { - settled = new.count - progress = 1 + } +} + +// MARK: - Inline Image Frame (`.conv-md-image-frame`) + +struct MarkdownImageFrameView: View { + let src: String + let alt: String + var fixedImage: UIImage? = nil + + @State private var loadedImage: UIImage? + @State private var previewItem: PreviewableImageItem? + + var body: some View { + let displayImage = fixedImage ?? loadedImage ?? AttachmentImageStore.decodeImage(from: src) + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + previewItem = PreviewableImageItem( + id: src.isEmpty ? alt : src, + image: displayImage, + urlString: src.isEmpty ? nil : src, + title: alt.isEmpty ? ((src as NSString).lastPathComponent.isEmpty ? "图片预览" : (src as NSString).lastPathComponent) : alt + ) + } label: { + if let displayImage { + VStack(alignment: .leading, spacing: 0) { + Image(uiImage: displayImage) + .resizable() + .scaledToFit() + .frame(maxWidth: 320, maxHeight: 280) + .background(Color(.tertiarySystemGroupedBackground)) + + if !alt.isEmpty { + HStack(spacing: 6) { + Image(systemName: "photo") + .font(.system(size: 10.5, weight: .medium)) + .foregroundStyle(.secondary) + Text(alt) + .font(.system(size: 11.5)) + .foregroundStyle(.secondary) + .lineLimit(1) + Spacer(minLength: 4) + Image(systemName: "arrow.up.left.and.arrow.down.right") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.tertiary) + } + .padding(.horizontal, 10) + .padding(.vertical, 6) + .background(Color(.secondarySystemGroupedBackground)) + } + } + .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(Color.primary.opacity(0.10), lineWidth: 0.75) + ) + } else { + // `.conv-md-image-placeholder` + HStack(spacing: 6) { + Image(systemName: "photo") + .font(.system(size: 11.5, weight: .medium)) + .foregroundStyle(.secondary) + Text(alt.isEmpty ? (src as NSString).lastPathComponent : alt) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(.secondary) + .lineLimit(1) + Image(systemName: "arrow.up.left.and.arrow.down.right") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.tertiary) + } + .padding(.horizontal, 10) + .padding(.vertical, 5) + .background( + Capsule() + .fill(Color(.secondarySystemGroupedBackground)) + ) + .overlay( + Capsule() + .strokeBorder(Color.primary.opacity(0.10), lineWidth: 0.75) + ) + } + } + .buttonStyle(.plain) + .task(id: src) { + guard fixedImage == nil, loadedImage == nil else { return } + if let decoded = AttachmentImageStore.decodeImage(from: src) { + loadedImage = decoded return } - settled = old.count - var instant = Transaction() - instant.disablesAnimations = true - withTransaction(instant) { progress = 0 } - Task { @MainActor in - await Task.yield() - withAnimation(.easeOut(duration: 0.55)) { progress = 1 } + guard let url = URL(string: src), url.scheme == "http" || url.scheme == "https" else { return } + if let (data, _) = try? await URLSession.shared.data(from: url), + let img = UIImage(data: data) + { + loadedImage = img } } + .fullScreenCover(item: $previewItem) { item in + ZoomableImagePreviewSheet(item: item) + } } +} - @ViewBuilder - private var rendered: some View { - let display = streaming ? text + "▍" : text - if #available(iOS 18.0, *) { - Text(display).textRenderer(RevealRenderer(settled: settled, progress: progress, hasCursor: streaming)) - } else { - Text(display) +// MARK: - VibeX Conversation Markdown Component (`AstryxMarkdown.tsx` + `conv-markdown.css`) + +struct StreamingMessageText: View { + let text: String + let isStreaming: Bool + let showCopyButton: Bool + let copyPayload: String? + + @State private var displayedText: String + @State private var targetText: String + @State private var animationTask: Task? + @State private var copiedMessage = false + + init( + text: String, + streaming: Bool, + showCopyButton: Bool = true, + copyPayload: String? = nil + ) { + self.text = text + self.isStreaming = streaming + self.showCopyButton = showCopyButton + self.copyPayload = copyPayload + _displayedText = State(initialValue: text) + _targetText = State(initialValue: text) + } + + init( + text: String, + isStreaming: Bool, + showCopyButton: Bool = true, + copyPayload: String? = nil + ) { + self.init( + text: text, + streaming: isStreaming, + showCopyButton: showCopyButton, + copyPayload: copyPayload + ) + } + + var body: some View { + let blocks = MarkdownBlockParser.parse(displayedText) + VStack(alignment: .leading, spacing: 8) { + ForEach(Array(blocks.enumerated()), id: \.offset) { index, block in + let isLastBlock = index == blocks.count - 1 + MarkdownBlockView( + block: block, + showCursor: isStreaming && isLastBlock + ) + } + if blocks.isEmpty && isStreaming { + StreamingCursorPill() + } + if !isStreaming && showCopyButton && !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + HStack { + Button { + UIPasteboard.general.string = copyPayload ?? text + UIImpactFeedbackGenerator(style: .light).impactOccurred() + withAnimation(.easeInOut(duration: 0.15)) { copiedMessage = true } + Task { + try? await Task.sleep(for: .milliseconds(1200)) + withAnimation(.easeInOut(duration: 0.15)) { copiedMessage = false } + } + } label: { + HStack(spacing: 4) { + Image(systemName: copiedMessage ? "checkmark" : "doc.on.doc") + .font(.system(size: 11, weight: .medium)) + if copiedMessage { + Text("已复制") + .font(.system(size: 11, weight: .medium)) + } + } + .foregroundStyle(copiedMessage ? .green : .secondary.opacity(0.75)) + .padding(.vertical, 2) + } + .buttonStyle(.plain) + Spacer() + } + .padding(.top, 2) + } + } + .textSelection(.enabled) + .onChange(of: text) { _, newValue in + targetText = newValue + if !isStreaming { + animationTask?.cancel() + displayedText = newValue + return + } + startSmoothCatchUpIfNeeded() + } + .onChange(of: isStreaming) { _, streaming in + if !streaming { + animationTask?.cancel() + displayedText = targetText + } + } + .onDisappear { + animationTask?.cancel() + } + } + + private func startSmoothCatchUpIfNeeded() { + if !targetText.hasPrefix(displayedText) { + displayedText = targetText + return + } + guard animationTask == nil else { return } + animationTask = Task { @MainActor in + defer { animationTask = nil } + while !Task.isCancelled { + let currentCount = displayedText.count + let targetCount = targetText.count + let remaining = targetCount - currentCount + guard remaining > 0 else { break } + + let step: Int + if remaining > 160 { + step = max(24, remaining / 3) + } else if remaining > 48 { + step = max(8, remaining / 4) + } else if remaining > 14 { + step = 4 + } else { + step = 2 + } + + let nextCount = min(targetCount, currentCount + step) + if let endIdx = targetText.index(targetText.startIndex, offsetBy: nextCount, limitedBy: targetText.endIndex) { + displayedText = String(targetText[.. [MarkdownBlock] { + guard !source.isEmpty else { return [] } + let normalized = source.replacingOccurrences(of: "\r\n", with: "\n") + let lines = normalized.components(separatedBy: "\n") + var blocks: [MarkdownBlock] = [] + var i = 0 + + while i < lines.count { + let line = lines[i] + let trimmed = line.trimmingCharacters(in: .whitespaces) + + if trimmed.isEmpty { + i += 1 + continue + } + + // 1. Display Math Block `$$ ... $$` + if trimmed.hasPrefix("$$") { + if trimmed.count > 4, trimmed.hasSuffix("$$") { + let inner = String(trimmed.dropFirst(2).dropLast(2)).trimmingCharacters(in: .whitespacesAndNewlines) + blocks.append(.mathBlock(tex: inner)) + i += 1 + continue + } + i += 1 + var texLines: [String] = [] + while i < lines.count { + let cur = lines[i].trimmingCharacters(in: .whitespaces) + if cur.hasSuffix("$$") { + let tail = String(cur.dropLast(2)).trimmingCharacters(in: .whitespaces) + if !tail.isEmpty { texLines.append(tail) } + i += 1 + break + } + texLines.append(lines[i]) + i += 1 + } + blocks.append(.mathBlock(tex: texLines.joined(separator: "\n"))) + continue + } + + // 2. Fenced Code Block ```lang + if trimmed.hasPrefix("```") { + let lang = String(trimmed.dropFirst(3)).trimmingCharacters(in: .whitespaces) + i += 1 + var codeLines: [String] = [] + while i < lines.count { + let cur = lines[i] + if cur.trimmingCharacters(in: .whitespaces).hasPrefix("```") { + i += 1 + break + } + codeLines.append(cur) + i += 1 + } + blocks.append(.codeBlock(language: lang, code: codeLines.joined(separator: "\n"))) + continue + } + + // 3. Horizontal rule + if trimmed == "---" || trimmed == "***" || trimmed == "___" { + blocks.append(.divider) + i += 1 + continue + } + + // 4. Standalone Markdown Image `![alt](src)` + if let img = parseStandaloneImage(trimmed) { + blocks.append(.image(alt: img.alt, src: img.src)) + i += 1 + continue + } - func draw(layout: Text.Layout, in context: inout GraphicsContext) { - let slices = layout.flatMap { $0 }.flatMap { $0 } - let fresh = max(1, slices.count - settled - (hasCursor ? 1 : 0)) - for (index, slice) in slices.enumerated() { - if index < settled || (hasCursor && index == slices.count - 1) { - context.draw(slice) + // 5. Heading `#` .. `######` + if let (level, headingText) = parseHeading(trimmed) { + blocks.append(.heading(level: level, text: headingText)) + i += 1 continue } - let order = Double(index - settled) / Double(fresh) - let local = min(1, max(0, progress * 1.6 - 0.6 * order)) - var copy = context - copy.opacity = local - copy.addFilter(.blur(radius: (1 - local) * 4)) - copy.draw(slice) + + // 6. GFM Table + if i + 1 < lines.count, + trimmed.contains("|"), + let alignments = parseTableDelimiterRow(lines[i + 1].trimmingCharacters(in: .whitespaces)) + { + let headers = splitTableCells(trimmed, expectedCount: alignments.count) + i += 2 + var rows: [[String]] = [] + while i < lines.count { + let rowLine = lines[i].trimmingCharacters(in: .whitespaces) + guard !rowLine.isEmpty, rowLine.contains("|") else { break } + rows.append(splitTableCells(rowLine, expectedCount: headers.count)) + i += 1 + } + blocks.append(.table(headers: headers, alignments: alignments, rows: rows)) + continue + } + + // 7. Blockquote or GitHub Alert `> [!NOTE]` + if trimmed.hasPrefix(">") { + var quoteLines: [String] = [] + while i < lines.count { + let cur = lines[i].trimmingCharacters(in: .whitespaces) + guard cur.hasPrefix(">") else { break } + var content = String(cur.dropFirst()) + if content.hasPrefix(" ") { content.removeFirst() } + quoteLines.append(content) + i += 1 + } + if let first = quoteLines.first, + let alertKind = parseAlertTag(first) + { + let body = Array(quoteLines.dropFirst()).joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) + blocks.append(.alert(kind: alertKind, text: body)) + } else { + blocks.append(.blockquote(text: quoteLines.joined(separator: "\n"))) + } + continue + } + + // 8. Task List `- [ ]` / `- [x]` + if let firstTask = parseTaskItem(trimmed) { + var items: [(checked: Bool, text: String)] = [firstTask] + i += 1 + while i < lines.count { + let cur = lines[i].trimmingCharacters(in: .whitespaces) + guard let nextTask = parseTaskItem(cur) else { break } + items.append(nextTask) + i += 1 + } + blocks.append(.taskList(items: items)) + continue + } + + // 9. Bullet List `- ` / `* ` / `+ ` + if let firstBullet = parseBulletItem(trimmed) { + var items: [String] = [firstBullet] + i += 1 + while i < lines.count { + let cur = lines[i].trimmingCharacters(in: .whitespaces) + if parseTaskItem(cur) != nil { break } + guard let next = parseBulletItem(cur) else { break } + items.append(next) + i += 1 + } + blocks.append(.bulletList(items: items)) + continue + } + + // 10. Numbered List `1. ` + if let firstNum = parseNumberedItem(trimmed) { + var items: [(number: Int, text: String)] = [firstNum] + i += 1 + while i < lines.count { + let cur = lines[i].trimmingCharacters(in: .whitespaces) + guard let next = parseNumberedItem(cur) else { break } + items.append(next) + i += 1 + } + blocks.append(.numberedList(items: items)) + continue + } + + // 11. Paragraph + var paraLines: [String] = [line] + i += 1 + while i < lines.count { + let nextLine = lines[i] + let nextTrim = nextLine.trimmingCharacters(in: .whitespaces) + if nextTrim.isEmpty + || nextTrim.hasPrefix("```") + || nextTrim.hasPrefix("$$") + || nextTrim == "---" + || nextTrim == "***" + || nextTrim == "___" + || parseStandaloneImage(nextTrim) != nil + || parseHeading(nextTrim) != nil + || nextTrim.hasPrefix(">") + || parseTaskItem(nextTrim) != nil + || parseBulletItem(nextTrim) != nil + || parseNumberedItem(nextTrim) != nil + || (i + 1 < lines.count && nextTrim.contains("|") && parseTableDelimiterRow(lines[i + 1].trimmingCharacters(in: .whitespaces)) != nil) + { + break + } + paraLines.append(nextLine) + i += 1 + } + blocks.append(.paragraph(text: paraLines.joined(separator: "\n"))) + } + + return blocks + } + + private static func parseHeading(_ line: String) -> (Int, String)? { + var count = 0 + for ch in line { + if ch == "#" { count += 1 } else { break } + } + guard (1...6).contains(count), line.count > count else { return nil } + let idx = line.index(line.startIndex, offsetBy: count) + guard line[idx] == " " else { return nil } + return (count, String(line[line.index(after: idx)...]).trimmingCharacters(in: .whitespaces)) + } + + private static func parseAlertTag(_ line: String) -> MarkdownAlertKind? { + let trimmed = line.trimmingCharacters(in: .whitespaces).uppercased() + guard trimmed.hasPrefix("[!"), trimmed.hasSuffix("]") else { return nil } + let raw = String(trimmed.dropFirst(2).dropLast()) + return MarkdownAlertKind(rawValue: raw) + } + + private static func parseTaskItem(_ line: String) -> (checked: Bool, text: String)? { + for prefix in ["- [ ] ", "* [ ] ", "+ [ ] "] { + if line.hasPrefix(prefix) { + return (false, String(line.dropFirst(prefix.count))) + } + } + for prefix in ["- [x] ", "- [X] ", "* [x] ", "* [X] ", "+ [x] ", "+ [X] "] { + if line.hasPrefix(prefix) { + return (true, String(line.dropFirst(prefix.count))) + } + } + return nil + } + + private static func parseBulletItem(_ line: String) -> String? { + for prefix in ["- ", "* ", "+ ", "• "] { + if line.hasPrefix(prefix) { + return String(line.dropFirst(prefix.count)) + } + } + return nil + } + + private static func parseNumberedItem(_ line: String) -> (Int, String)? { + guard let dotIndex = line.firstIndex(of: ".") else { return nil } + let numPart = line[.. (alt: String, src: String)? { + guard line.hasPrefix("![") && line.hasSuffix(")"), + let mid = line.range(of: "](") + else { return nil } + let alt = String(line[line.index(line.startIndex, offsetBy: 2).. [MarkdownTableAlignment]? { + guard line.contains("|") && line.contains("-") else { return nil } + let rawCells = splitRawCells(line) + guard !rawCells.isEmpty else { return nil } + var alignments: [MarkdownTableAlignment] = [] + for cell in rawCells { + let c = cell.trimmingCharacters(in: .whitespaces) + guard !c.isEmpty else { return nil } + let core = c.trimmingCharacters(in: CharacterSet(charactersIn: ":")) + guard core.count >= 1, core.allSatisfy({ $0 == "-" }) else { return nil } + let starts = c.hasPrefix(":") + let ends = c.hasSuffix(":") + if starts && ends { + alignments.append(.center) + } else if ends { + alignments.append(.trailing) + } else { + alignments.append(.leading) + } + } + return alignments + } + + private static func splitTableCells(_ line: String, expectedCount: Int) -> [String] { + var cells = splitRawCells(line).map { $0.trimmingCharacters(in: .whitespaces) } + if cells.count < expectedCount { + cells.append(contentsOf: Array(repeating: "", count: expectedCount - cells.count)) + } else if cells.count > expectedCount && expectedCount > 0 { + cells = Array(cells.prefix(expectedCount)) + } + return cells + } + + private static func splitRawCells(_ line: String) -> [String] { + var s = line.trimmingCharacters(in: .whitespaces) + if s.hasPrefix("|") { s.removeFirst() } + if s.hasSuffix("|") { s.removeLast() } + return s.components(separatedBy: "|") + } +} + +// MARK: - Block View Renderer (`AstryxMarkdown` + `conv-markdown.css`) + +private struct MarkdownBlockView: View { + let block: MarkdownBlock + let showCursor: Bool + + var body: some View { + switch block { + case .heading(let level, let text): + HStack(alignment: .lastTextBaseline, spacing: 4) { + Text(Self.inlineAttributed(text)) + .font(.system(size: headingSize(level), weight: .semibold)) + .tracking(0.1) + .foregroundStyle(.primary) + if showCursor { StreamingCursorPill() } + } + .padding(.top, level <= 2 ? 3 : 1) + + case .paragraph(let text): + HStack(alignment: .lastTextBaseline, spacing: 3) { + Text(Self.inlineAttributed(text)) + .font(.system(size: 14.5)) + .lineSpacing(4.5) + .foregroundStyle(.primary) + if showCursor { StreamingCursorPill() } + } + + case .codeBlock(let language, let code): + VibeXMarkdownCodeSwitch(language: language, code: code) + + case .bulletList(let items): + VStack(alignment: .leading, spacing: 5) { + ForEach(Array(items.enumerated()), id: \.offset) { idx, item in + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text("•") + .font(.system(size: 14.5, weight: .bold)) + .foregroundStyle(.secondary) + .frame(width: 10, alignment: .center) + HStack(alignment: .lastTextBaseline, spacing: 3) { + Text(Self.inlineAttributed(item)) + .font(.system(size: 14.5)) + .lineSpacing(4) + .foregroundStyle(.primary) + if showCursor && idx == items.count - 1 { + StreamingCursorPill() + } + } + } + } + } + .padding(.vertical, 2) + + case .numberedList(let items): + VStack(alignment: .leading, spacing: 5) { + ForEach(Array(items.enumerated()), id: \.offset) { idx, entry in + HStack(alignment: .firstTextBaseline, spacing: 7) { + Text("\(entry.number).") + .font(.system(size: 13.5, weight: .medium, design: .monospaced)) + .foregroundStyle(.secondary) + HStack(alignment: .lastTextBaseline, spacing: 3) { + Text(Self.inlineAttributed(entry.text)) + .font(.system(size: 14.5)) + .lineSpacing(4) + .foregroundStyle(.primary) + if showCursor && idx == items.count - 1 { + StreamingCursorPill() + } + } + } + } + } + .padding(.vertical, 2) + + case .taskList(let items): + VStack(alignment: .leading, spacing: 6) { + ForEach(Array(items.enumerated()), id: \.offset) { idx, item in + HStack(alignment: .firstTextBaseline, spacing: 8) { + Image(systemName: item.checked ? "checkmark.square.fill" : "square") + .font(.system(size: 14, weight: .medium)) + .foregroundStyle(item.checked ? Color.accentColor : .secondary) + HStack(alignment: .lastTextBaseline, spacing: 3) { + Text(Self.inlineAttributed(item.text)) + .font(.system(size: 14.5)) + .lineSpacing(4) + .strikethrough(item.checked, color: .secondary) + .foregroundStyle(item.checked ? .secondary : .primary) + if showCursor && idx == items.count - 1 { + StreamingCursorPill() + } + } + } + } + } + .padding(.vertical, 2) + + case .blockquote(let text): + // Matches `.conv-markdown :where(blockquote)` in `conv-markdown.css`: + // padding 6px 10px, border 1px solid var(--conv-border-subtle), background var(--conv-surface-control), border-radius 8px + Text(Self.inlineAttributed(text)) + .font(.system(size: 14)) + .lineSpacing(4) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 10) + .padding(.vertical, 7) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(Color.primary.opacity(0.09), lineWidth: 0.75) + ) + + case .alert(let kind, let text): + VStack(alignment: .leading, spacing: 5) { + HStack(spacing: 6) { + Image(systemName: kind.icon) + .font(.system(size: 12.5, weight: .semibold)) + Text(kind.title) + .font(.system(size: 12.5, weight: .semibold)) + } + .foregroundStyle(kind.tint) + + if !text.isEmpty { + Text(Self.inlineAttributed(text)) + .font(.system(size: 13.5)) + .lineSpacing(3.5) + .foregroundStyle(.primary.opacity(0.9)) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 11) + .padding(.vertical, 8) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(kind.tint.opacity(0.08)) + ) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(kind.tint.opacity(0.25), lineWidth: 0.8) + ) + + case .table(let headers, let alignments, let rows): + VibeXMarkdownTableView(headers: headers, alignments: alignments, rows: rows) + + case .image(let alt, let src): + MarkdownImageFrameView(src: src, alt: alt) + + case .mathBlock(let tex): + ScrollView(.horizontal, showsIndicators: false) { + Text(tex) + .font(.system(size: 13.5, design: .serif).italic()) + .foregroundStyle(.primary) + .padding(.horizontal, 12) + .padding(.vertical, 8) + } + .frame(maxWidth: .infinity, alignment: .leading) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.6) + ) + + case .divider: + Divider() + .padding(.top, 8) + .padding(.bottom, 12) + } + } + + private func headingSize(_ level: Int) -> CGFloat { + switch level { + case 1: return 17 + case 2: return 16 + case 3: return 15 + default: return 14.5 + } + } + + /// Parses inline Markdown (`**bold**`, `*italic*`, `` `code` ``, `[label](url)`, `$math$`) + /// and styles inline code & file references to match `AstryxMarkdown.tsx` + `conv-markdown.css`. + static func inlineAttributed(_ raw: String) -> AttributedString { + let normalized = raw.replacingOccurrences(of: #"\$([^$\n]+)\$"#, with: "`$1`", options: .regularExpression) + let options = AttributedString.MarkdownParsingOptions( + interpretedSyntax: .inlineOnlyPreservingWhitespace + ) + guard var attributed = try? AttributedString(markdown: normalized, options: options) else { + return AttributedString(raw) + } + for run in attributed.runs { + if run.inlinePresentationIntent?.contains(.code) == true { + let textSlice = String(attributed[run.range].characters) + attributed[run.range].font = .system(size: 13, weight: .medium, design: .monospaced) + if looksLikeWorkspaceResource(textSlice) { + attributed[run.range].foregroundColor = .accentColor + attributed[run.range].backgroundColor = Color.accentColor.opacity(0.10) + } else { + attributed[run.range].backgroundColor = Color.primary.opacity(0.07) + } + } else if run.link != nil { + attributed[run.range].foregroundColor = .accentColor + attributed[run.range].underlineStyle = .single + } + } + return attributed + } + + private static func looksLikeWorkspaceResource(_ candidate: String) -> Bool { + let trimmed = candidate.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, !trimmed.contains(" ") else { return false } + if trimmed.hasPrefix("/") || trimmed.hasPrefix("./") || trimmed.contains("/") { + return trimmed.contains(".") + } + let exts = [".swift", ".ts", ".tsx", ".rs", ".js", ".jsx", ".json", ".md", ".css", ".py", ".go", ".toml", ".yaml", ".yml", ".html"] + return exts.contains { trimmed.lowercased().hasSuffix($0) } + } +} + +// MARK: - GFM Table View (`.conv-markdown table`) + +private struct VibeXMarkdownTableView: View { + let headers: [String] + let alignments: [MarkdownTableAlignment] + let rows: [[String]] + + var body: some View { + ScrollView(.horizontal, showsIndicators: false) { + Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) { + // Header row (`thead tr th`) + GridRow { + ForEach(Array(headers.enumerated()), id: \.offset) { colIdx, header in + tableCell( + text: header, + isHeader: true, + alignment: alignment(for: colIdx), + isLastCol: colIdx == headers.count - 1, + isLastRow: rows.isEmpty + ) + } + } + .background(Color(.tertiarySystemGroupedBackground)) + + // Body rows (`tbody tr td`) + ForEach(Array(rows.enumerated()), id: \.offset) { rowIdx, row in + GridRow { + ForEach(Array(row.enumerated()), id: \.offset) { colIdx, cell in + tableCell( + text: cell, + isHeader: false, + alignment: alignment(for: colIdx), + isLastCol: colIdx == row.count - 1, + isLastRow: rowIdx == rows.count - 1 + ) + } + } + } + } + .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(Color.primary.opacity(0.10), lineWidth: 0.75) + ) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + } + .padding(.vertical, 2) + } + + private func alignment(for colIdx: Int) -> Alignment { + guard alignments.indices.contains(colIdx) else { return .leading } + switch alignments[colIdx] { + case .leading: return .leading + case .center: return .center + case .trailing: return .trailing + } + } + + private func tableCell( + text: String, + isHeader: Bool, + alignment: Alignment, + isLastCol: Bool, + isLastRow: Bool + ) -> some View { + Text(MarkdownBlockView.inlineAttributed(text)) + .font(.system(size: 13, weight: isHeader ? .semibold : .regular)) + .foregroundStyle(.primary) + .padding(.horizontal, 12) + .padding(.vertical, 8) + .frame(minWidth: 68, maxWidth: 260, alignment: alignment) + .overlay(alignment: .bottom) { + if !isLastRow { + Rectangle() + .fill(Color.primary.opacity(0.08)) + .frame(height: 0.6) + } + } + .overlay(alignment: .trailing) { + if !isLastCol { + Rectangle() + .fill(Color.primary.opacity(0.08)) + .frame(width: 0.6) + } + } + } +} + +// MARK: - Code Switch (`MarkdownCodeSwitch` + `CodeBlock.tsx` + `conv-markdown.css`) + +private struct VibeXMarkdownCodeSwitch: View { + let language: String + let code: String + @State private var copied = false + + private var detectedLanguage: CodeLanguage { + CodeLanguage.detectFromFence(language) + } + + private var isSingleLine: Bool { + !code.contains("\n") + } + + private var isMermaid: Bool { + language.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == "mermaid" + } + + var body: some View { + if isMermaid { + mermaidBlock + } else if isSingleLine { + compactSingleLineBlock + } else { + fencedCodeBlock + } + } + + // Matches `CompactCodeBlock` (`.conv-md-codeblock-single`) in `CodeBlock.tsx` + private var compactSingleLineBlock: some View { + let highlighted = CodeHighlighter.highlight(code, language: detectedLanguage) + return HStack(spacing: 8) { + ScrollView(.horizontal, showsIndicators: false) { + if let first = highlighted.first { + Text(first) + .font(.system(size: 13, design: .monospaced)) + } else { + Text(code) + .font(.system(size: 13, design: .monospaced)) + } + } + Spacer(minLength: 4) + copyButton + } + .padding(.horizontal, 12) + .padding(.vertical, 8) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(Color.primary.opacity(0.09), lineWidth: 0.75) + ) + .padding(.vertical, 2) + } + + // Matches `CodeBlock` (`.conv-md-codeblock`) in `CodeBlock.tsx` + `conv-markdown.css` + private var fencedCodeBlock: some View { + let highlighted = CodeHighlighter.highlight(code, language: detectedLanguage) + let label = language.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ? "TEXT" + : language.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() + + return VStack(alignment: .leading, spacing: 0) { + // `.conv-md-codeblock-header` + HStack(spacing: 8) { + Text(label) + .font(.system(size: 11, weight: .semibold)) + .tracking(0.45) + .foregroundStyle(.secondary) + Spacer() + copyButton + } + .padding(.leading, 10) + .padding(.trailing, 6) + .padding(.vertical, 3) + .frame(minHeight: 28) + .background(Color(.tertiarySystemGroupedBackground)) + + Divider().opacity(0.5) + + // `.conv-md-codeblock pre` + ScrollView(.horizontal, showsIndicators: false) { + VStack(alignment: .leading, spacing: 2) { + ForEach(Array(highlighted.enumerated()), id: \.offset) { _, line in + Text(line.characters.isEmpty ? AttributedString(" ") : line) + .font(.system(size: 13, design: .monospaced)) + } + } + .padding(.horizontal, 12) + .padding(.top, 10) + .padding(.bottom, 12) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(Color.primary.opacity(0.09), lineWidth: 0.75) + ) + .padding(.vertical, 3) + } + + // Matches `.conv-md-mermaid` + private var mermaidBlock: some View { + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 6) { + Image(systemName: "point.3.connected.trianglepath.dotted") + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(Color.accentColor) + Text("MERMAID 流程图") + .font(.system(size: 11, weight: .semibold)) + .tracking(0.4) + .foregroundStyle(.secondary) + Spacer() + copyButton + } + .padding(.leading, 10) + .padding(.trailing, 6) + .padding(.vertical, 4) + .frame(minHeight: 28) + .background(Color(.tertiarySystemGroupedBackground)) + + Divider().opacity(0.5) + + ScrollView(.horizontal, showsIndicators: false) { + Text(code) + .font(.system(size: 12.5, design: .monospaced)) + .foregroundStyle(.primary) + .padding(12) + } + } + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder(Color.primary.opacity(0.09), lineWidth: 0.75) + ) + .padding(.vertical, 3) + } + + // Matches `.conv-md-codeblock-copy` & `.is-copied` + private var copyButton: some View { + Button { + UIPasteboard.general.string = code + UIImpactFeedbackGenerator(style: .light).impactOccurred() + withAnimation(.easeInOut(duration: 0.15)) { copied = true } + Task { + try? await Task.sleep(for: .milliseconds(1200)) + withAnimation(.easeInOut(duration: 0.15)) { copied = false } + } + } label: { + Image(systemName: copied ? "checkmark" : "doc.on.doc") + .font(.system(size: 11.5, weight: .semibold)) + .foregroundStyle(copied ? .green : .secondary) + .frame(width: 24, height: 24) + .background( + RoundedRectangle(cornerRadius: 6, style: .continuous) + .fill(copied ? Color.green.opacity(0.10) : Color.clear) + ) + .overlay( + RoundedRectangle(cornerRadius: 6, style: .continuous) + .strokeBorder(copied ? Color.green.opacity(0.45) : Color.clear, lineWidth: 0.75) + ) } + .buttonStyle(.plain) + .accessibilityLabel(copied ? "已复制" : "复制代码") } } diff --git a/mobile/ios/App/ThinkingView.swift b/mobile/ios/App/ThinkingView.swift index e55087cd6..b5fb230a1 100644 --- a/mobile/ios/App/ThinkingView.swift +++ b/mobile/ios/App/ThinkingView.swift @@ -2,54 +2,104 @@ import CompanionCore import SwiftUI /// Expandable reasoning the Agent produced before answering. -/// Open while work is in progress, then settles and stays expandable. +/// Collapsed by default; tap to inspect the full reasoning trace. struct ThinkingView: View { - let item: TimelineItem + let text: String + let durationMs: Int? let working: Bool - @State private var manual: Bool? + @State private var expanded = false - private var expanded: Bool { manual ?? working } + init(text: String, durationMs: Int? = nil, working: Bool) { + self.text = text + self.durationMs = durationMs + self.working = working + } + + init(item: TimelineItem, working: Bool) { + self.text = item.thinking + self.durationMs = item.durationMs + self.working = working + } + + private var previewLine: String? { + let lines = text + .split(whereSeparator: \.isNewline) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + return lines.last + } var body: some View { - VStack(alignment: .leading, spacing: 4) { + VStack(alignment: .leading, spacing: 6) { Button { - withAnimation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.4)) { manual = !expanded } + withAnimation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.3)) { + expanded.toggle() + } } label: { - HStack(spacing: 8) { - Image(systemName: "sparkle") - .font(.system(size: 13)) - .foregroundStyle(working ? Color.primary.opacity(0.7) : Color.secondary) + HStack(spacing: 7) { + if working { + ProgressView() + .controlSize(.mini) + } else { + Image(systemName: "sparkles") + .font(.system(size: 11.5, weight: .semibold)) + .foregroundStyle(.secondary) + } + if working { ShimmerText(text: workingLabel) + .font(.system(size: 12.5, weight: .medium)) } else { - Text(doneLabel).foregroundStyle(.secondary) + Text(doneLabel) + .font(.system(size: 12.5, weight: .medium)) + .foregroundStyle(.secondary) + } + + if !expanded, let previewLine { + Text("·") + .foregroundStyle(.quaternary) + Text(previewLine) + .font(.system(size: 12)) + .foregroundStyle(.tertiary) + .lineLimit(1) + .truncationMode(.tail) } - Image(systemName: "chevron.down") - .font(.system(size: 10, weight: .semibold)) + + Spacer(minLength: 4) + + Image(systemName: "chevron.right") + .font(.system(size: 10, weight: .bold)) .foregroundStyle(.tertiary) - .rotationEffect(.degrees(expanded ? 180 : 0)) + .rotationEffect(.degrees(expanded ? 90 : 0)) } - .font(.system(size: 13, weight: .medium)) - .padding(.vertical, 4) + .padding(.horizontal, 10) + .padding(.vertical, 6) + .background( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .strokeBorder(Color.primary.opacity(0.06), lineWidth: 0.5) + ) .contentShape(Rectangle()) } .buttonStyle(.plain) - if expanded { - HStack(alignment: .top, spacing: 12) { - Rectangle().fill(Color.primary.opacity(0.12)).frame(width: 1) - VStack(alignment: .leading, spacing: 6) { - if !item.thinking.isEmpty { - Text(item.thinking) - .font(.system(size: 12.5)) - .foregroundStyle(.secondary) - .lineSpacing(3) - .textSelection(.enabled) - } - } - .padding(.vertical, 2) + if expanded && !text.isEmpty { + HStack(alignment: .top, spacing: 10) { + Capsule() + .fill(Color.primary.opacity(0.16)) + .frame(width: 2) + Text(text) + .font(.system(size: 12.5)) + .foregroundStyle(.secondary) + .lineSpacing(3) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) } - .padding(.leading, 6) + .padding(.horizontal, 10) + .padding(.vertical, 4) .transition(.opacity.combined(with: .move(edge: .top))) } } @@ -58,7 +108,7 @@ struct ThinkingView: View { private var workingLabel: String { "思考中" } private var doneLabel: String { - if let ms = item.durationMs, ms >= 1000 { return "思考了 \(ms / 1000) 秒" } + if let ms = durationMs, ms >= 1000 { return "已思考 \(ms / 1000) 秒" } return "已思考" } } diff --git a/mobile/ios/App/ToolChips.swift b/mobile/ios/App/ToolChips.swift index abaf466a7..4662aabb1 100644 --- a/mobile/ios/App/ToolChips.swift +++ b/mobile/ios/App/ToolChips.swift @@ -1,63 +1,163 @@ import CompanionCore import SwiftUI -/// An agent run as compact rows: tool calls with inline chips, then file-diff chips for the edits. +/// An agent run as compact rows: tool calls collapsed by default, then file-diff chips for the edits. struct ToolChipsView: View { - let item: TimelineItem + let tools: [ToolStep] + let changes: [FileChangeItem] let working: Bool let openDiff: (FileChangeItem) -> Void - @State private var runOpen = true + @State private var runOpen = false @State private var openRows: Set = [] + init( + tools: [ToolStep], + changes: [FileChangeItem] = [], + working: Bool, + openDiff: @escaping (FileChangeItem) -> Void + ) { + self.tools = tools + self.changes = changes + self.working = working + self.openDiff = openDiff + } + + init( + item: TimelineItem, + working: Bool, + openDiff: @escaping (FileChangeItem) -> Void + ) { + self.tools = item.tools + self.changes = item.changes + self.working = working + self.openDiff = openDiff + } + + private var regularTools: [ToolStep] { + tools.filter { !$0.isAskQuestion || $0.questions.isEmpty } + } + + private var questionTools: [ToolStep] { + tools.filter { $0.isAskQuestion && !$0.questions.isEmpty } + } + + private var anyToolRunning: Bool { + working && regularTools.contains(where: { !$0.isFinished }) + } + + private var latestToolSummary: String? { + guard let last = regularTools.last else { return nil } + if let preview = last.preview, !preview.isEmpty { + if preview.lowercased().hasPrefix(last.label.lowercased()) { + return preview + } + return "\(last.label) \(preview)" + } + return last.label + } + var body: some View { - VStack(alignment: .leading, spacing: 4) { - if !item.tools.isEmpty { + VStack(alignment: .leading, spacing: 6) { + if !regularTools.isEmpty { Button { - withAnimation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.3)) { runOpen.toggle() } + withAnimation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.28)) { + runOpen.toggle() + } } label: { - HStack(spacing: 6) { - Image(systemName: "chevron.down") + HStack(spacing: 7) { + if anyToolRunning { + ProgressView() + .controlSize(.mini) + } else { + Image(systemName: "wrench.and.screwdriver") + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.secondary) + } + + Text(anyToolRunning ? "正在执行工具 (\(regularTools.count))" : "\(regularTools.count) 次工具调用") + .font(.system(size: 12.5, weight: .medium)) + .monospacedDigit() + .foregroundStyle(.secondary) + + if !runOpen, let summary = latestToolSummary { + Text("·") + .foregroundStyle(.quaternary) + Text(summary) + .font(.system(size: 11.5, design: .monospaced)) + .foregroundStyle(.tertiary) + .lineLimit(1) + .truncationMode(.tail) + } + + Spacer(minLength: 4) + + Image(systemName: "chevron.right") .font(.system(size: 10, weight: .bold)) - .rotationEffect(.degrees(runOpen ? 0 : -90)) - Text("\(item.tools.count) 次工具调用").monospacedDigit() + .foregroundStyle(.tertiary) + .rotationEffect(.degrees(runOpen ? 90 : 0)) } - .font(.system(size: 12.5)) - .foregroundStyle(.secondary) - .padding(.vertical, 4) + .padding(.horizontal, 10) + .padding(.vertical, 6) + .background( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + ) + .overlay( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .strokeBorder(Color.primary.opacity(0.06), lineWidth: 0.5) + ) .contentShape(Rectangle()) } .buttonStyle(.plain) + if runOpen { - VStack(alignment: .leading, spacing: 6) { - ForEach(item.tools) { tool in toolRow(tool) } + VStack(alignment: .leading, spacing: 5) { + ForEach(regularTools) { tool in toolRow(tool) } } + .padding(.leading, 4) + .padding(.top, 2) .transition(.opacity.combined(with: .move(edge: .top))) } } - if !item.changes.isEmpty { - Divider().padding(.top, 8) + + ForEach(questionTools) { questionTool in + AskQuestionToolCardView(tool: questionTool) + } + + if !changes.isEmpty { FlowLayout(spacing: 6) { - ForEach(item.changes.prefix(Self.visibleChanges)) { change in + ForEach(changes.prefix(Self.visibleChanges)) { change in Button { openDiff(change) } label: { - HStack(spacing: 8) { + HStack(spacing: 6) { + Image(systemName: FileGlyph.symbol(for: change.path)) + .font(.system(size: 10.5)) + .foregroundStyle(.secondary) Text((change.path as NSString).lastPathComponent).lineLimit(1) - if let additions = change.additions { Text("+\(additions)").foregroundStyle(.green) } + if let additions = change.additions { + Text("+\(additions)").foregroundStyle(.green) + } if let deletions = change.deletions, deletions > 0 { Text("−\(deletions)").foregroundStyle(.red) } } - .font(.system(size: 12, design: .monospaced)) - .padding(.horizontal, 10) - .frame(height: 30) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 9, style: .continuous)) - .overlay(RoundedRectangle(cornerRadius: 9, style: .continuous).stroke(Color.primary.opacity(0.08))) + .font(.system(size: 11.5, design: .monospaced)) + .padding(.horizontal, 9) + .frame(height: 28) + .background( + Color(.secondarySystemGroupedBackground), + in: RoundedRectangle(cornerRadius: 8, style: .continuous) + ) + .overlay( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .stroke(Color.primary.opacity(0.08), lineWidth: 0.5) + ) } .buttonStyle(.plain) .accessibilityLabel("查看 \(change.path) 的差异") } - if item.changes.count > Self.visibleChanges { - Text("+\(item.changes.count - Self.visibleChanges)") + if changes.count > Self.visibleChanges { + Text("+\(changes.count - Self.visibleChanges)") .font(.system(size: 11.5, design: .monospaced)) .foregroundStyle(.tertiary) .frame(height: 28) @@ -73,54 +173,78 @@ struct ToolChipsView: View { private func toolRow(_ tool: ToolStep) -> some View { let isOpen = openRows.contains(tool.id) - return VStack(alignment: .leading, spacing: 2) { + let isInlineCommand = (tool.preview?.lowercased().hasPrefix(tool.label.lowercased()) ?? false) + && tool.name == tool.preview + let rowLabel = isInlineCommand ? "终端" : tool.label + return VStack(alignment: .leading, spacing: 3) { Button { - withAnimation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.3)) { + withAnimation(.timingCurve(0.23, 1, 0.32, 1, duration: 0.25)) { if isOpen { openRows.remove(tool.id) } else { openRows.insert(tool.id) } } } label: { HStack(spacing: 8) { ZStack { if tool.isFinished || !working { - Image(systemName: icon(for: tool.name)).font(.system(size: 12)) + Image(systemName: isInlineCommand ? "terminal" : icon(for: tool.name)).font(.system(size: 11.5)) } else { ProgressView().controlSize(.mini) } } - .foregroundStyle(.tertiary) + .foregroundStyle(.secondary) .frame(width: 16) - Text(tool.label) - .font(.system(size: 13, weight: .semibold)) + + Text(rowLabel) + .font(.system(size: 12.5, weight: .semibold)) .lineLimit(1) .fixedSize() - Text(tool.preview ?? " ") - .font(.system(size: 12.5, design: .monospaced)) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.tail) - .padding(.horizontal, 10) - .frame(maxWidth: .infinity, alignment: .leading) - .frame(height: 30) - .background(Color(.secondarySystemGroupedBackground), in: RoundedRectangle(cornerRadius: 9, style: .continuous)) - .overlay(RoundedRectangle(cornerRadius: 9, style: .continuous).stroke(Color.primary.opacity(0.06))) - .opacity(tool.preview == nil ? 0 : 1) + + if let preview = tool.preview, !preview.isEmpty { + Text(preview) + .font(.system(size: 12, design: .monospaced)) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.tail) + .padding(.horizontal, 8) + .frame(maxWidth: .infinity, alignment: .leading) + .frame(height: 26) + .background( + Color(.secondarySystemGroupedBackground), + in: RoundedRectangle(cornerRadius: 7, style: .continuous) + ) + .overlay( + RoundedRectangle(cornerRadius: 7, style: .continuous) + .stroke(Color.primary.opacity(0.06), lineWidth: 0.5) + ) + } else { + Spacer(minLength: 0) + } + + if !tool.detail.isEmpty { + Image(systemName: "chevron.right") + .font(.system(size: 9, weight: .bold)) + .foregroundStyle(.tertiary) + .rotationEffect(.degrees(isOpen ? 90 : 0)) + } } - .frame(minHeight: 34) + .frame(minHeight: 30) .contentShape(Rectangle()) } .buttonStyle(.plain) + if isOpen && !tool.detail.isEmpty { VStack(alignment: .leading, spacing: 2) { ForEach(Array(tool.detail.enumerated()), id: \.offset) { _, line in Text(line) .font(.system(size: 11.5, design: .monospaced)) .foregroundStyle(.secondary) - .lineLimit(1) + .lineLimit(2) } } .padding(.leading, 12) - .padding(.vertical, 2) - .overlay(alignment: .leading) { Rectangle().fill(Color.primary.opacity(0.12)).frame(width: 1) } + .padding(.vertical, 3) + .overlay(alignment: .leading) { + Rectangle().fill(Color.primary.opacity(0.14)).frame(width: 1.5) + } .padding(.leading, 8) .transition(.opacity.combined(with: .move(edge: .top))) } diff --git a/mobile/ios/App/VibeXCompanionApp.swift b/mobile/ios/App/VibeXCompanionApp.swift index d39acf3d2..9947471a1 100644 --- a/mobile/ios/App/VibeXCompanionApp.swift +++ b/mobile/ios/App/VibeXCompanionApp.swift @@ -3,11 +3,13 @@ import SwiftUI @main struct VibeXCompanionApp: App { @State private var servers = ServerStore() + @State private var appearance = AppAppearanceStore() var body: some Scene { WindowGroup { RootTabView() .environment(servers) + .environment(appearance) } } } diff --git a/mobile/ios/Sources/CompanionCore/BoardModels.swift b/mobile/ios/Sources/CompanionCore/BoardModels.swift new file mode 100644 index 000000000..8d705a259 --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/BoardModels.swift @@ -0,0 +1,1002 @@ +import Foundation + +// MARK: - Kanban View & Status Enums + +public enum KanbanViewMode: String, CaseIterable, Identifiable, Sendable { + case columns + case sessionHub + case usage + + public var id: String { rawValue } + + public var title: String { + switch self { + case .columns: return "四栏看板" + case .sessionHub: return "会话中心" + case .usage: return "计量统计" + } + } + + public var icon: String { + switch self { + case .columns: return "rectangle.split.3x1" + case .sessionHub: return "list.bullet.rectangle.portrait" + case .usage: return "chart.bar.xaxis" + } + } +} + +public enum KanbanSessionStatus: String, CaseIterable, Codable, Identifiable, Sendable { + case todo + case inprogress + case inreview + case done + case archived + + public var id: String { rawValue } + + public static let activeColumns: [KanbanSessionStatus] = [ + .todo, .inprogress, .inreview, .done, + ] + + public init(rawStatus: String?) { + guard let raw = rawStatus?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() else { + self = .todo + return + } + switch raw { + case "inprogress", "in_progress", "running": + self = .inprogress + case "inreview", "in_review", "review": + self = .inreview + case "done", "completed", "complete": + self = .done + case "archived", "archive": + self = .archived + default: + self = .todo + } + } + + public var title: String { + switch self { + case .todo: return "待开始" + case .inprogress: return "进行中" + case .inreview: return "待检查" + case .done: return "已完成" + case .archived: return "已归档" + } + } + + public var columnHeaderLabel: String { + switch self { + case .todo: return "TODO" + case .inprogress: return "IN PROGRESS" + case .inreview: return "IN REVIEW" + case .done: return "DONE" + case .archived: return "ARCHIVED" + } + } + + public var sortOrder: Int { + switch self { + case .todo: return 0 + case .inprogress: return 1 + case .inreview: return 2 + case .done: return 3 + case .archived: return 4 + } + } +} + +public enum KanbanSortField: String, CaseIterable, Identifiable, Sendable { + case defaultOrder + case name + case time + case status + case agent + + public var id: String { rawValue } + + public var label: String { + switch self { + case .defaultOrder: return "默认顺序" + case .name: return "名称" + case .time: return "时间" + case .status: return "状态" + case .agent: return "Agent" + } + } +} + +// MARK: - Kanban Session & Workspace Models + +public struct KanbanSessionCollaboration: Decodable, Equatable, Hashable, Sendable { + public let memberId: String? + public let memberName: String? + public let threadId: String? + public let threadKind: String? + public let threadName: String? + + private enum CodingKeys: String, CodingKey { + case memberId, member_id + case memberName, member_name + case threadId, thread_id + case threadKind, thread_kind + case threadName, thread_name + } + + public init( + memberId: String? = nil, + memberName: String? = nil, + threadId: String? = nil, + threadKind: String? = nil, + threadName: String? = nil + ) { + self.memberId = memberId + self.memberName = memberName + self.threadId = threadId + self.threadKind = threadKind + self.threadName = threadName + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + memberId = (try? c.decodeIfPresent(String.self, forKey: .memberId)) + ?? (try? c.decodeIfPresent(String.self, forKey: .member_id)) + memberName = (try? c.decodeIfPresent(String.self, forKey: .memberName)) + ?? (try? c.decodeIfPresent(String.self, forKey: .member_name)) + threadId = (try? c.decodeIfPresent(String.self, forKey: .threadId)) + ?? (try? c.decodeIfPresent(String.self, forKey: .thread_id)) + threadKind = (try? c.decodeIfPresent(String.self, forKey: .threadKind)) + ?? (try? c.decodeIfPresent(String.self, forKey: .thread_kind)) + threadName = (try? c.decodeIfPresent(String.self, forKey: .threadName)) + ?? (try? c.decodeIfPresent(String.self, forKey: .thread_name)) + } +} + +public struct KanbanSessionSummary: Decodable, Identifiable, Equatable, Hashable, Sendable { + public let id: String + public let workspaceId: String + public let taskId: String? + public var name: String? + public let displayName: String? + public var status: KanbanSessionStatus + public let executor: String? + public let agentId: String? + public let workspaceName: String? + public let workspaceBranch: String? + public let createdAt: String + public var updatedAt: String + public let firstPrompt: String? + public var isRunning: Bool + public var pinnedAt: String? + public let model: String? + public let collaboration: KanbanSessionCollaboration? + + private enum CodingKeys: String, CodingKey { + case id + case workspaceId, workspace_id + case taskId, task_id + case name + case displayName, display_name + case status + case executor + case agentId, agent_id + case workspaceName, workspace_name + case workspaceBranch, workspace_branch + case createdAt, created_at + case updatedAt, updated_at + case firstPrompt, first_prompt + case isRunning, is_running + case pinnedAt, pinned_at + case model + case collaboration + } + + public init( + id: String, + workspaceId: String, + taskId: String? = nil, + name: String? = nil, + displayName: String? = nil, + status: KanbanSessionStatus = .todo, + executor: String? = nil, + agentId: String? = nil, + workspaceName: String? = nil, + workspaceBranch: String? = nil, + createdAt: String = "", + updatedAt: String = "", + firstPrompt: String? = nil, + isRunning: Bool = false, + pinnedAt: String? = nil, + model: String? = nil, + collaboration: KanbanSessionCollaboration? = nil + ) { + self.id = id + self.workspaceId = workspaceId + self.taskId = taskId + self.name = name + self.displayName = displayName + self.status = status + self.executor = executor + self.agentId = agentId + self.workspaceName = workspaceName + self.workspaceBranch = workspaceBranch + self.createdAt = createdAt + self.updatedAt = updatedAt + self.firstPrompt = firstPrompt + self.isRunning = isRunning + self.pinnedAt = pinnedAt + self.model = model + self.collaboration = collaboration + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = try c.decode(String.self, forKey: .id) + workspaceId = (try? c.decode(String.self, forKey: .workspaceId)) + ?? (try? c.decode(String.self, forKey: .workspace_id)) + ?? "" + taskId = (try? c.decodeIfPresent(String.self, forKey: .taskId)) + ?? (try? c.decodeIfPresent(String.self, forKey: .task_id)) + name = try? c.decodeIfPresent(String.self, forKey: .name) + displayName = (try? c.decodeIfPresent(String.self, forKey: .displayName)) + ?? (try? c.decodeIfPresent(String.self, forKey: .display_name)) + let rawStatus = try? c.decodeIfPresent(String.self, forKey: .status) + status = KanbanSessionStatus(rawStatus: rawStatus) + executor = try? c.decodeIfPresent(String.self, forKey: .executor) + agentId = (try? c.decodeIfPresent(String.self, forKey: .agentId)) + ?? (try? c.decodeIfPresent(String.self, forKey: .agent_id)) + workspaceName = (try? c.decodeIfPresent(String.self, forKey: .workspaceName)) + ?? (try? c.decodeIfPresent(String.self, forKey: .workspace_name)) + workspaceBranch = (try? c.decodeIfPresent(String.self, forKey: .workspaceBranch)) + ?? (try? c.decodeIfPresent(String.self, forKey: .workspace_branch)) + createdAt = (try? c.decodeIfPresent(String.self, forKey: .createdAt)) + ?? (try? c.decodeIfPresent(String.self, forKey: .created_at)) + ?? "" + updatedAt = (try? c.decodeIfPresent(String.self, forKey: .updatedAt)) + ?? (try? c.decodeIfPresent(String.self, forKey: .updated_at)) + ?? createdAt + firstPrompt = (try? c.decodeIfPresent(String.self, forKey: .firstPrompt)) + ?? (try? c.decodeIfPresent(String.self, forKey: .first_prompt)) + isRunning = (try? c.decodeIfPresent(Bool.self, forKey: .isRunning)) + ?? (try? c.decodeIfPresent(Bool.self, forKey: .is_running)) + ?? false + pinnedAt = (try? c.decodeIfPresent(String.self, forKey: .pinnedAt)) + ?? (try? c.decodeIfPresent(String.self, forKey: .pinned_at)) + model = try? c.decodeIfPresent(String.self, forKey: .model) + collaboration = try? c.decodeIfPresent(KanbanSessionCollaboration.self, forKey: .collaboration) + } + + public init(fromConversation item: ConversationListItem) { + self.id = item.id + self.workspaceId = item.workspace_id + self.taskId = nil + self.name = item.title + self.displayName = item.title + self.status = KanbanSessionStatus(rawStatus: item.status) + self.executor = item.agent_id + self.agentId = item.agent_id + self.workspaceName = nil + self.workspaceBranch = nil + self.createdAt = item.updated_at + self.updatedAt = item.updated_at + self.firstPrompt = nil + self.isRunning = item.status?.lowercased() == "running" + self.pinnedAt = nil + self.model = item.model + self.collaboration = nil + } + + public var isPinned: Bool { + guard let pinnedAt else { return false } + return !pinnedAt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + public var isArchived: Bool { status == .archived } + public var isCompleted: Bool { status == .done } + public var completesWhenViewed: Bool { status == .inreview && !isRunning } + + public var resolvedTitle: String { + if let n = name?.trimmingCharacters(in: .whitespacesAndNewlines), !n.isEmpty { + return n + } + if let p = firstPrompt?.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression) + .trimmingCharacters(in: .whitespacesAndNewlines), !p.isEmpty + { + return p + } + if let d = displayName?.trimmingCharacters(in: .whitespacesAndNewlines), !d.isEmpty { + return d + } + return "新会话" + } + + public var effectiveAgentKey: String? { + if let a = agentId?.trimmingCharacters(in: .whitespacesAndNewlines), !a.isEmpty { return a } + if let e = executor?.trimmingCharacters(in: .whitespacesAndNewlines), !e.isEmpty { return e } + return nil + } + + public var agentDisplayName: String { + Self.formatAgentDisplayName(effectiveAgentKey) + } + + public static func formatAgentDisplayName(_ rawKey: String?) -> String { + guard let key = rawKey?.trimmingCharacters(in: .whitespacesAndNewlines), !key.isEmpty else { + return "未设置代理" + } + switch key.lowercased() { + case "claude_code", "claude-code", "claude": return "Claude Code" + case "codex": return "Codex" + case "gemini", "gemini_cli", "gemini-cli": return "Gemini" + case "cursor", "cursor_agent": return "Cursor" + case "grok", "grok_cli": return "Grok" + case "opencode", "open_code": return "OpenCode" + case "kimi", "kimi_code", "kimi-code": return "Kimi" + case "antigravity": return "Antigravity" + case "deepseek_harness", "deepseek-harness", "deepseek": return "DeepSeek" + case "pi": return "Pi" + case "qwen", "qwen_code": return "Qwen" + default: return key + } + } + + public var workspaceDisplayLabel: String { + if let wn = workspaceName?.trimmingCharacters(in: .whitespacesAndNewlines), !wn.isEmpty { + return wn + } + if let wb = workspaceBranch?.trimmingCharacters(in: .whitespacesAndNewlines), !wb.isEmpty { + return wb + } + return "" + } + + public var updatedDate: Date? { + ConversationListItem.parseDate(updatedAt) ?? ConversationListItem.parseDate(createdAt) + } + + public var asConversationListItem: ConversationListItem { + ConversationListItem( + id: id, + workspace_id: workspaceId, + title: resolvedTitle, + status: status.rawValue, + agent_id: effectiveAgentKey, + model: model, + message_count: 0, + updated_at: updatedAt + ) + } + + public var isForkSupported: Bool { + guard let key = effectiveAgentKey?.lowercased() else { return false } + return ["claude_code", "claude-code", "codex", "deepseek_harness", "deepseek-harness"].contains(key) + } + + public var sessionInfoText: String { + let ws = workspaceDisplayLabel.isEmpty ? "-" : workspaceDisplayLabel + return [ + "会话名称: \(resolvedTitle)", + "ID: \(id)", + "Agent: \(agentDisplayName)", + "工作区: \(ws)", + ].joined(separator: "\n") + } +} + +public struct KanbanWorkspaceRecord: Decodable, Identifiable, Equatable, Hashable, Sendable { + public let id: String + public let projectId: String + public let branch: String + public let name: String? + public let useWorktree: Bool + public let archived: Bool + public let pinned: Bool + + private enum CodingKeys: String, CodingKey { + case id + case projectId, project_id + case branch + case name + case useWorktree, use_worktree + case archived + case pinned + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = try c.decode(String.self, forKey: .id) + projectId = (try? c.decode(String.self, forKey: .projectId)) + ?? (try? c.decode(String.self, forKey: .project_id)) + ?? "" + branch = (try? c.decode(String.self, forKey: .branch)) ?? "" + name = try? c.decodeIfPresent(String.self, forKey: .name) + useWorktree = (try? c.decodeIfPresent(Bool.self, forKey: .useWorktree)) + ?? (try? c.decodeIfPresent(Bool.self, forKey: .use_worktree)) + ?? false + archived = (try? c.decodeIfPresent(Bool.self, forKey: .archived)) ?? false + pinned = (try? c.decodeIfPresent(Bool.self, forKey: .pinned)) ?? false + } + + public var displayLabel: String { + if let n = name?.trimmingCharacters(in: .whitespacesAndNewlines), !n.isEmpty { + return n + } + if !branch.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + return branch + } + return "默认工作区" + } +} + +// MARK: - Usage Dashboard Models (`get_project_usage_statistics` & `agent_plan_usage`) + +public enum UsageDateRange: String, CaseIterable, Identifiable, Sendable { + case sevenDays = "7d" + case thirtyDays = "30d" + case all = "all" + + public var id: String { rawValue } + + public var label: String { + switch self { + case .sevenDays: return "7天" + case .thirtyDays: return "30天" + case .all: return "全部" + } + } +} + +public enum UsageDashboardTab: String, CaseIterable, Identifiable, Sendable { + case overview + case folders + case agents + case models + case sessions + case plan + + public var id: String { rawValue } + + public var label: String { + switch self { + case .overview: return "概览" + case .folders: return "目录" + case .agents: return "Agent" + case .models: return "模型" + case .sessions: return "会话" + case .plan: return "套餐" + } + } + + public var icon: String { + switch self { + case .overview: return "chart.line.uptrend.xyaxis" + case .folders: return "folder" + case .agents: return "bolt.fill" + case .models: return "number" + case .sessions: return "list.bullet" + case .plan: return "shippingbox" + } + } +} + +public struct UsageTokenCounts: Decodable, Equatable, Sendable { + public let inputTokens: Int64? + public let outputTokens: Int64? + public let cacheWriteTokens: Int64? + public let cacheReadTokens: Int64? + public let totalTokens: Int64? + + private enum CodingKeys: String, CodingKey { + case inputTokens, input_tokens + case outputTokens, output_tokens + case cacheWriteTokens, cache_write_tokens + case cacheReadTokens, cache_read_tokens + case totalTokens, total_tokens + } + + public init( + inputTokens: Int64? = nil, + outputTokens: Int64? = nil, + cacheWriteTokens: Int64? = nil, + cacheReadTokens: Int64? = nil, + totalTokens: Int64? = nil + ) { + self.inputTokens = inputTokens + self.outputTokens = outputTokens + self.cacheWriteTokens = cacheWriteTokens + self.cacheReadTokens = cacheReadTokens + self.totalTokens = totalTokens + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + inputTokens = (try? c.decodeIfPresent(Int64.self, forKey: .inputTokens)) + ?? (try? c.decodeIfPresent(Int64.self, forKey: .input_tokens)) + outputTokens = (try? c.decodeIfPresent(Int64.self, forKey: .outputTokens)) + ?? (try? c.decodeIfPresent(Int64.self, forKey: .output_tokens)) + cacheWriteTokens = (try? c.decodeIfPresent(Int64.self, forKey: .cacheWriteTokens)) + ?? (try? c.decodeIfPresent(Int64.self, forKey: .cache_write_tokens)) + cacheReadTokens = (try? c.decodeIfPresent(Int64.self, forKey: .cacheReadTokens)) + ?? (try? c.decodeIfPresent(Int64.self, forKey: .cache_read_tokens)) + totalTokens = (try? c.decodeIfPresent(Int64.self, forKey: .totalTokens)) + ?? (try? c.decodeIfPresent(Int64.self, forKey: .total_tokens)) + } + + public var resolvedTotal: Int64 { + if let totalTokens, totalTokens > 0 { return totalTokens } + return (inputTokens ?? 0) + (outputTokens ?? 0) + (cacheWriteTokens ?? 0) + (cacheReadTokens ?? 0) + } +} + +public struct UsageSourcedTokens: Decodable, Equatable, Sendable { + public let protocolTokens: UsageTokenCounts? + public let vendorLog: UsageTokenCounts? + public let sourcesDisagree: Bool + + private enum CodingKeys: String, CodingKey { + case protocolTokens = "protocol" + case vendorLog, vendor_log + case sourcesDisagree, sources_disagree + } + + public init( + protocolTokens: UsageTokenCounts? = nil, + vendorLog: UsageTokenCounts? = nil, + sourcesDisagree: Bool = false + ) { + self.protocolTokens = protocolTokens + self.vendorLog = vendorLog + self.sourcesDisagree = sourcesDisagree + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + protocolTokens = try? c.decodeIfPresent(UsageTokenCounts.self, forKey: .protocolTokens) + vendorLog = (try? c.decodeIfPresent(UsageTokenCounts.self, forKey: .vendorLog)) + ?? (try? c.decodeIfPresent(UsageTokenCounts.self, forKey: .vendor_log)) + sourcesDisagree = (try? c.decodeIfPresent(Bool.self, forKey: .sourcesDisagree)) + ?? (try? c.decodeIfPresent(Bool.self, forKey: .sources_disagree)) + ?? false + } + + public var preferred: UsageTokenCounts { + if let v = vendorLog, v.resolvedTotal > 0 { return v } + if let p = protocolTokens, p.resolvedTotal > 0 { return p } + return vendorLog ?? protocolTokens ?? UsageTokenCounts() + } +} + +public struct UsageDailyItem: Decodable, Identifiable, Equatable, Sendable { + public let date: String + public let sessions: Int + public let tokens: UsageSourcedTokens + public let cost: Double? + public let modelsUsed: [String] + public let turns: Int? + + public var id: String { date } + + private enum CodingKeys: String, CodingKey { + case date, sessions, tokens, cost + case modelsUsed, models_used + case turns + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + date = (try? c.decode(String.self, forKey: .date)) ?? "" + sessions = (try? c.decode(Int.self, forKey: .sessions)) ?? 0 + tokens = (try? c.decode(UsageSourcedTokens.self, forKey: .tokens)) ?? UsageSourcedTokens() + cost = try? c.decodeIfPresent(Double.self, forKey: .cost) + modelsUsed = (try? c.decode([String].self, forKey: .modelsUsed)) + ?? (try? c.decode([String].self, forKey: .models_used)) + ?? [] + turns = try? c.decodeIfPresent(Int.self, forKey: .turns) + } +} + +public struct UsageModelItem: Decodable, Identifiable, Equatable, Sendable { + public let model: String + public let sessionCount: Int + public let tokens: UsageSourcedTokens + public let cost: Double? + + public var id: String { model } + + private enum CodingKeys: String, CodingKey { + case model + case sessionCount, session_count + case tokens, cost + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + model = (try? c.decode(String.self, forKey: .model)) ?? "未提供" + sessionCount = (try? c.decode(Int.self, forKey: .sessionCount)) + ?? (try? c.decode(Int.self, forKey: .session_count)) + ?? 0 + tokens = (try? c.decode(UsageSourcedTokens.self, forKey: .tokens)) ?? UsageSourcedTokens() + cost = try? c.decodeIfPresent(Double.self, forKey: .cost) + } +} + +public struct UsageFolderItem: Decodable, Identifiable, Equatable, Sendable { + public let workspaceId: String + public let folder: String? + public let sessionCount: Int + public let tokens: UsageSourcedTokens + public let cost: Double? + + public var id: String { "\(workspaceId)-\(folder ?? "")" } + + private enum CodingKeys: String, CodingKey { + case workspaceId, workspace_id + case folder + case sessionCount, session_count + case tokens, cost + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + workspaceId = (try? c.decode(String.self, forKey: .workspaceId)) + ?? (try? c.decode(String.self, forKey: .workspace_id)) + ?? "" + folder = try? c.decodeIfPresent(String.self, forKey: .folder) + sessionCount = (try? c.decode(Int.self, forKey: .sessionCount)) + ?? (try? c.decode(Int.self, forKey: .session_count)) + ?? 0 + tokens = (try? c.decode(UsageSourcedTokens.self, forKey: .tokens)) ?? UsageSourcedTokens() + cost = try? c.decodeIfPresent(Double.self, forKey: .cost) + } + + public var displayName: String { + if let folder, !folder.isEmpty { + let name = (folder as NSString).lastPathComponent + if !name.isEmpty && name != "/" { return name } + return folder + } + return workspaceId.isEmpty ? "默认工作区" : String(workspaceId.prefix(8)) + } +} + +public struct UsageAgentItem: Decodable, Identifiable, Equatable, Sendable { + public let agentId: String + public let sessionCount: Int + public let tokens: UsageSourcedTokens + public let cost: Double? + + public var id: String { agentId } + + private enum CodingKeys: String, CodingKey { + case agentId, agent_id + case sessionCount, session_count + case tokens, cost + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + agentId = (try? c.decode(String.self, forKey: .agentId)) + ?? (try? c.decode(String.self, forKey: .agent_id)) + ?? "unprovided" + sessionCount = (try? c.decode(Int.self, forKey: .sessionCount)) + ?? (try? c.decode(Int.self, forKey: .session_count)) + ?? 0 + tokens = (try? c.decode(UsageSourcedTokens.self, forKey: .tokens)) ?? UsageSourcedTokens() + cost = try? c.decodeIfPresent(Double.self, forKey: .cost) + } + + public var displayName: String { + KanbanSessionSummary.formatAgentDisplayName(agentId) + } +} + +public struct UsageSessionItem: Decodable, Identifiable, Equatable, Sendable { + public let sessionId: String + public let workspaceId: String + public let folder: String? + public let agentId: String? + public let timestamp: Int64 + public let model: String? + public let tokens: UsageSourcedTokens + public let cost: Double? + public let summary: String? + public let turns: Int? + + public var id: String { sessionId } + + private enum CodingKeys: String, CodingKey { + case sessionId, session_id + case workspaceId, workspace_id + case folder + case agentId, agent_id + case timestamp, model, tokens, cost, summary, turns + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + sessionId = (try? c.decode(String.self, forKey: .sessionId)) + ?? (try? c.decode(String.self, forKey: .session_id)) + ?? UUID().uuidString + workspaceId = (try? c.decode(String.self, forKey: .workspaceId)) + ?? (try? c.decode(String.self, forKey: .workspace_id)) + ?? "" + folder = try? c.decodeIfPresent(String.self, forKey: .folder) + agentId = (try? c.decodeIfPresent(String.self, forKey: .agentId)) + ?? (try? c.decodeIfPresent(String.self, forKey: .agent_id)) + timestamp = (try? c.decode(Int64.self, forKey: .timestamp)) ?? 0 + model = try? c.decodeIfPresent(String.self, forKey: .model) + tokens = (try? c.decode(UsageSourcedTokens.self, forKey: .tokens)) ?? UsageSourcedTokens() + cost = try? c.decodeIfPresent(Double.self, forKey: .cost) + summary = try? c.decodeIfPresent(String.self, forKey: .summary) + turns = try? c.decodeIfPresent(Int.self, forKey: .turns) + } + + public var displayTitle: String { + if let s = summary?.trimmingCharacters(in: .whitespacesAndNewlines), !s.isEmpty { + return s + } + return "会话 \(sessionId.prefix(8))" + } + + public var date: Date { + let seconds = timestamp > 10_000_000_000 ? Double(timestamp) / 1000.0 : Double(timestamp) + return Date(timeIntervalSince1970: seconds) + } +} + +public struct ProjectUsageStatistics: Decodable, Equatable, Sendable { + public let scope: String + public let projectId: String + public let projectName: String + public let totalSessions: Int + public let totalTokens: UsageSourcedTokens + public let estimatedCost: Double? + public let vendorEstimatedCost: Double? + public let sessions: [UsageSessionItem] + public let dailyUsage: [UsageDailyItem] + public let byModel: [UsageModelItem] + public let byFolder: [UsageFolderItem] + public let byAgent: [UsageAgentItem] + public let unattributedVendorSessions: Int + public let lastUpdated: Int64 + + private enum CodingKeys: String, CodingKey { + case scope + case projectId, project_id + case projectName, project_name + case totalSessions, total_sessions + case totalTokens, total_tokens + case estimatedCost, estimated_cost + case vendorEstimatedCost, vendor_estimated_cost + case sessions + case dailyUsage, daily_usage + case byModel, by_model + case byFolder, by_folder + case byAgent, by_agent + case unattributedVendorSessions, unattributed_vendor_sessions + case lastUpdated, last_updated + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + scope = (try? c.decode(String.self, forKey: .scope)) ?? "global" + projectId = (try? c.decode(String.self, forKey: .projectId)) + ?? (try? c.decode(String.self, forKey: .project_id)) + ?? "" + projectName = (try? c.decode(String.self, forKey: .projectName)) + ?? (try? c.decode(String.self, forKey: .project_name)) + ?? "全局" + totalSessions = (try? c.decode(Int.self, forKey: .totalSessions)) + ?? (try? c.decode(Int.self, forKey: .total_sessions)) + ?? 0 + totalTokens = (try? c.decode(UsageSourcedTokens.self, forKey: .totalTokens)) + ?? (try? c.decode(UsageSourcedTokens.self, forKey: .total_tokens)) + ?? UsageSourcedTokens() + estimatedCost = (try? c.decodeIfPresent(Double.self, forKey: .estimatedCost)) + ?? (try? c.decodeIfPresent(Double.self, forKey: .estimated_cost)) + vendorEstimatedCost = (try? c.decodeIfPresent(Double.self, forKey: .vendorEstimatedCost)) + ?? (try? c.decodeIfPresent(Double.self, forKey: .vendor_estimated_cost)) + sessions = (try? c.decode([UsageSessionItem].self, forKey: .sessions)) ?? [] + dailyUsage = (try? c.decode([UsageDailyItem].self, forKey: .dailyUsage)) + ?? (try? c.decode([UsageDailyItem].self, forKey: .daily_usage)) + ?? [] + byModel = (try? c.decode([UsageModelItem].self, forKey: .byModel)) + ?? (try? c.decode([UsageModelItem].self, forKey: .by_model)) + ?? [] + byFolder = (try? c.decode([UsageFolderItem].self, forKey: .byFolder)) + ?? (try? c.decode([UsageFolderItem].self, forKey: .by_folder)) + ?? [] + byAgent = (try? c.decode([UsageAgentItem].self, forKey: .byAgent)) + ?? (try? c.decode([UsageAgentItem].self, forKey: .by_agent)) + ?? [] + unattributedVendorSessions = (try? c.decode(Int.self, forKey: .unattributedVendorSessions)) + ?? (try? c.decode(Int.self, forKey: .unattributed_vendor_sessions)) + ?? 0 + lastUpdated = (try? c.decode(Int64.self, forKey: .lastUpdated)) + ?? (try? c.decode(Int64.self, forKey: .last_updated)) + ?? 0 + } + + public var resolvedCost: Double? { + if let estimatedCost { return estimatedCost } + if let vendorEstimatedCost { return vendorEstimatedCost } + let sessionSum = sessions.compactMap(\.cost).reduce(0, +) + if sessionSum > 0 { return sessionSum } + let modelSum = byModel.compactMap(\.cost).reduce(0, +) + return modelSum > 0 ? modelSum : nil + } + + public var cacheHitRatePercent: Double? { + let counts = totalTokens.preferred + let cacheRead = Double(counts.cacheReadTokens ?? 0) + let input = Double(counts.inputTokens ?? 0) + let cacheWrite = Double(counts.cacheWriteTokens ?? 0) + let denom = cacheRead + input + cacheWrite + guard denom > 0 else { return nil } + return (cacheRead / denom) * 100.0 + } + + public var activeDaysCount: Int { + dailyUsage.filter { $0.sessions > 0 || $0.tokens.preferred.resolvedTotal > 0 }.count + } + + public var avgTokensPerSession: Int64 { + guard totalSessions > 0 else { return 0 } + return totalTokens.preferred.resolvedTotal / Int64(totalSessions) + } +} + +// MARK: - Plan Usage (`agent_plan_usage`) + +public struct PlanUsageWindow: Decodable, Identifiable, Equatable, Sendable { + public let id: String + public let usedPercent: Double? + public let windowMinutes: Int64? + public let resetsAtMs: Int64? + + private enum CodingKeys: String, CodingKey { + case id + case usedPercent, used_percent + case windowMinutes, window_minutes + case resetsAtMs, resets_at_ms + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = (try? c.decode(String.self, forKey: .id)) ?? UUID().uuidString + usedPercent = (try? c.decodeIfPresent(Double.self, forKey: .usedPercent)) + ?? (try? c.decodeIfPresent(Double.self, forKey: .used_percent)) + windowMinutes = (try? c.decodeIfPresent(Int64.self, forKey: .windowMinutes)) + ?? (try? c.decodeIfPresent(Int64.self, forKey: .window_minutes)) + resetsAtMs = (try? c.decodeIfPresent(Int64.self, forKey: .resetsAtMs)) + ?? (try? c.decodeIfPresent(Int64.self, forKey: .resets_at_ms)) + } + + public var clampedUsedPercent: Int? { + guard let usedPercent else { return nil } + return max(0, min(100, Int(usedPercent.rounded()))) + } + + public var remainingPercent: Int? { + guard let used = clampedUsedPercent else { return nil } + return max(0, 100 - used) + } + + public var localizedTitle: String { + switch id { + case "five_hour": return "5 小时窗口" + case "seven_day": return "每周窗口(全部模型)" + case "seven_day_opus": return "每周窗口(Opus)" + case "seven_day_sonnet": return "每周窗口(Sonnet)" + case "extra_usage": return "额外用量(本月)" + case "primary": return "主限额窗口" + case "secondary": return "次限额窗口" + case "weekly": return "每周窗口" + case "monthly": return "每月窗口" + case "plan_period": return "滚动窗口" + case "cursor_models": return "Cursor 模型" + case "other_models": return "其它模型" + case "gemini_five_hour": return "Gemini 5 小时" + case "gemini_weekly": return "Gemini 每周" + case "claude_gpt_five_hour": return "Claude/GPT 5 小时" + case "claude_gpt_weekly": return "Claude/GPT 每周" + case "argon_five_hour": return "Gemini 4 Argon 5 小时" + case "argon_weekly": return "Gemini 4 Argon 每周" + default: + if let mins = windowMinutes, mins > 0 { + if mins % 1440 == 0 { + return "\(mins / 1440) 天窗口" + } else if mins % 60 == 0 { + return "\(mins / 60) 小时窗口" + } + } + return id + } + } + + public func resetLabel(nowMs: Int64 = Int64(Date().timeIntervalSince1970 * 1000)) -> String? { + guard let resetsAtMs else { return nil } + let diffMs = resetsAtMs - nowMs + if diffMs <= 60_000 { return "即将重置" } + let minutes = Int(ceil(Double(diffMs) / 60_000.0)) + if minutes < 60 { return "\(minutes) 分钟后重置" } + let hours = Int(ceil(Double(minutes) / 60.0)) + if hours < 24 { return "\(hours) 小时后重置" } + let days = Int(ceil(Double(hours) / 24.0)) + return "\(days) 天后重置" + } +} + +public struct PlanCredits: Decodable, Equatable, Sendable { + public let balance: String? + public let unlimited: Bool + + private enum CodingKeys: String, CodingKey { + case balance, unlimited + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + balance = try? c.decodeIfPresent(String.self, forKey: .balance) + unlimited = (try? c.decodeIfPresent(Bool.self, forKey: .unlimited)) ?? false + } +} + +public struct AgentPlanUsage: Decodable, Equatable, Sendable { + public let planType: String? + public let windows: [PlanUsageWindow] + public let credits: PlanCredits? + + private enum CodingKeys: String, CodingKey { + case planType, plan_type + case windows, credits + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + planType = (try? c.decodeIfPresent(String.self, forKey: .planType)) + ?? (try? c.decodeIfPresent(String.self, forKey: .plan_type)) + windows = (try? c.decode([PlanUsageWindow].self, forKey: .windows)) ?? [] + credits = try? c.decodeIfPresent(PlanCredits.self, forKey: .credits) + } +} + +public enum PlanUsageResponse: Decodable, Equatable, Sendable { + case ok(AgentPlanUsage) + case unavailable(reason: String) + case error(message: String) + + private enum CodingKeys: String, CodingKey { + case type, usage, reason, message + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let type = (try? c.decode(String.self, forKey: .type))?.uppercased() ?? "" + switch type { + case "OK": + let usage = try c.decode(AgentPlanUsage.self, forKey: .usage) + self = .ok(usage) + case "UNAVAILABLE": + let reason = (try? c.decode(String.self, forKey: .reason)) ?? "UNSUPPORTED_AGENT" + self = .unavailable(reason: reason) + default: + let message = (try? c.decode(String.self, forKey: .message)) ?? "读取失败" + self = .error(message: message) + } + } + + public var unavailableDescription: String? { + guard case .unavailable(let reason) = self else { return nil } + switch reason.uppercased() { + case "UNSUPPORTED_AGENT": return "该 Agent 不提供套餐额度信息" + case "CLI_NOT_FOUND": return "未找到已安装的程序,请先在设置中安装并登录" + case "NOT_LOGGED_IN": return "未检测到登录凭据,请先在设置中登录" + case "TOKEN_EXPIRED": return "登录凭据已过期,请在设置中重新登录" + default: return reason + } + } +} diff --git a/mobile/ios/Sources/CompanionCore/CollaborationModels.swift b/mobile/ios/Sources/CompanionCore/CollaborationModels.swift new file mode 100644 index 000000000..9bbba8b27 --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/CollaborationModels.swift @@ -0,0 +1,844 @@ +import Foundation + +// MARK: - Bot Avatar & Shape System (Desktop Parity) + +public enum BotAvatarShape: String, CaseIterable, Codable, Equatable, Sendable, Identifiable { + case circle + case cloud + case squircle + case sparkle + case clover + case heart + case pebble + case droplet + case capsule + case triangle + case pentagon + case star + case hexagon + + public var id: String { rawValue } + + public var label: String { + switch self { + case .circle: return "圆形" + case .cloud: return "云朵" + case .squircle: return "超椭圆" + case .sparkle: return "星芒" + case .clover: return "四叶草" + case .heart: return "爱心" + case .pebble: return "鹅卵石" + case .droplet: return "水滴" + case .capsule: return "胶囊" + case .triangle: return "三角形" + case .pentagon: return "五边形" + case .star: return "星章" + case .hexagon: return "六边形" + } + } +} + +public enum BotAvatarExpression: String, CaseIterable, Codable, Equatable, Sendable { + case neutral + case attentive + case happy + case laughing + case excited + case surprised + case confused + case curious + case suspicious + case sleepy + case sad + case scared + case angry + case proud + case shy + case unimpressed +} + +public struct BotAvatarColorPreset: Equatable, Sendable, Identifiable { + public let id: String + public let label: String + public let hex: String + + public init(id: String, label: String, hex: String) { + self.id = id + self.label = label + self.hex = hex + } +} + +public struct CollabBotAvatarConfig: Codable, Equatable, Hashable, Sendable { + public var color: String + public var shape: BotAvatarShape + public var expression: BotAvatarExpression + + public init( + color: String, + shape: BotAvatarShape = .circle, + expression: BotAvatarExpression = .neutral + ) { + self.color = Self.normalizeHexColor(color) + self.shape = shape + self.expression = expression + } + + public static let defaultMaster = CollabBotAvatarConfig( + color: "#000000", + shape: .circle, + expression: .neutral + ) + + public static let colorPresets: [BotAvatarColorPreset] = [ + BotAvatarColorPreset(id: "ink", label: "墨黑", hex: "#000000"), + BotAvatarColorPreset(id: "brown", label: "棕色", hex: "#9a6433"), + BotAvatarColorPreset(id: "red", label: "红色", hex: "#fa2d37"), + BotAvatarColorPreset(id: "orange", label: "橙色", hex: "#ff6b0a"), + BotAvatarColorPreset(id: "amber", label: "琥珀", hex: "#f99408"), + BotAvatarColorPreset(id: "green", label: "绿色", hex: "#09b866"), + BotAvatarColorPreset(id: "turquoise", label: "青绿", hex: "#0db49b"), + BotAvatarColorPreset(id: "blue", label: "蓝色", hex: "#1584ff"), + BotAvatarColorPreset(id: "purple", label: "紫色", hex: "#8b52ff"), + BotAvatarColorPreset(id: "pink", label: "粉色", hex: "#ff2994"), + BotAvatarColorPreset(id: "grey", label: "灰色", hex: "#8c8c8c"), + ] + + public static func normalizeHexColor(_ value: String, fallback: String = "#1584ff") -> String { + let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) + let raw = trimmed.hasPrefix("#") ? String(trimmed.dropFirst()) : trimmed + if raw.count == 6, raw.allSatisfy(\.isHexDigit) { + return "#\(raw.lowercased())" + } + if raw.count == 3, raw.allSatisfy(\.isHexDigit) { + let chars = Array(raw.lowercased()) + return "#\(chars[0])\(chars[0])\(chars[1])\(chars[1])\(chars[2])\(chars[2])" + } + return fallback + } + + public static func hashSeed(_ input: String) -> UInt32 { + var hash: UInt32 = 2_166_136_261 + for scalar in input.utf16 { + hash ^= UInt32(scalar) + hash = hash &* 16_777_619 + } + return hash + } + + public static func derive(seed: String) -> CollabBotAvatarConfig { + let trimmed = seed.trimmingCharacters(in: .whitespacesAndNewlines) + let normalized = trimmed.isEmpty ? "vibex-bot" : trimmed + if normalized.lowercased() == "master" { + return defaultMaster + } + let h1 = Int(hashSeed(normalized)) + let h2 = Int(hashSeed("\(normalized):shape")) + let colors = colorPresets + let shapes = BotAvatarShape.allCases + return CollabBotAvatarConfig( + color: colors[h1 % colors.count].hex, + shape: shapes[h2 % shapes.count], + expression: .neutral + ) + } + + public static func random() -> CollabBotAvatarConfig { + let color = colorPresets.randomElement()?.hex ?? "#1584ff" + let shape = BotAvatarShape.allCases.randomElement() ?? .circle + return CollabBotAvatarConfig(color: color, shape: shape, expression: .neutral) + } + + public static func resolve( + rawAvatar: String?, + rawColor: String?, + fallbackSeed: String + ) -> CollabBotAvatarConfig { + let base = derive(seed: fallbackSeed) + var resolvedColor = base.color + if let rawColor, !rawColor.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + resolvedColor = normalizeHexColor(rawColor, fallback: base.color) + } + var resolvedShape = base.shape + var resolvedExpression: BotAvatarExpression = .neutral + + if let rawAvatar = rawAvatar?.trimmingCharacters(in: .whitespacesAndNewlines), + !rawAvatar.isEmpty + { + if let shapeDirect = BotAvatarShape(rawValue: rawAvatar) { + resolvedShape = shapeDirect + } else if rawAvatar.hasPrefix("{"), + let data = rawAvatar.data(using: .utf8), + let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] + { + if let c = obj["color"] as? String, !c.isEmpty { + resolvedColor = normalizeHexColor(c, fallback: resolvedColor) + } + if let s = obj["shape"] as? String, let shape = BotAvatarShape(rawValue: s) { + resolvedShape = shape + } + if let e = obj["expression"] as? String, let expr = BotAvatarExpression(rawValue: e) { + resolvedExpression = expr + } + } + } + return CollabBotAvatarConfig( + color: resolvedColor, + shape: resolvedShape, + expression: resolvedExpression + ) + } + + public var jsonString: String { + "{\"color\":\"\(Self.normalizeHexColor(color))\",\"shape\":\"\(shape.rawValue)\",\"expression\":\"\(expression.rawValue)\"}" + } +} + +// MARK: - Sidebar & Contact Groups + +public struct CollabSidebarMember: Decodable, Equatable, Sendable { + public let memberId: String + public let identityMemberId: String? + public let name: String + public let avatar: String? + public let color: String? + public let conversationId: String? + public let agent: String? + public let isSupervisor: Bool + + public var resolvedIdentityId: String { + if let id = identityMemberId, !id.isEmpty { return id } + return memberId + } + + public var botAvatar: CollabBotAvatarConfig { + CollabBotAvatarConfig.resolve( + rawAvatar: avatar, + rawColor: color, + fallbackSeed: name.isEmpty ? resolvedIdentityId : name + ) + } + + private enum CodingKeys: String, CodingKey { + case member_id, identity_member_id, name, avatar, color, conversation_id, agent, is_supervisor + } + + public init( + memberId: String, + identityMemberId: String? = nil, + name: String, + avatar: String? = nil, + color: String? = nil, + conversationId: String? = nil, + agent: String? = nil, + isSupervisor: Bool = false + ) { + self.memberId = memberId + self.identityMemberId = identityMemberId + self.name = name + self.avatar = avatar + self.color = color + self.conversationId = conversationId + self.agent = agent + self.isSupervisor = isSupervisor + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + memberId = (try? c.decode(String.self, forKey: .member_id)) ?? "" + identityMemberId = try? c.decodeIfPresent(String.self, forKey: .identity_member_id) + name = (try? c.decode(String.self, forKey: .name)) ?? "助手" + if let s = try? c.decodeIfPresent(String.self, forKey: .avatar) { + avatar = s + } else if let obj = try? c.decodeIfPresent(CollabBotAvatarConfig.self, forKey: .avatar) { + avatar = obj.jsonString + } else { + avatar = nil + } + color = try? c.decodeIfPresent(String.self, forKey: .color) + conversationId = try? c.decodeIfPresent(String.self, forKey: .conversation_id) + agent = try? c.decodeIfPresent(String.self, forKey: .agent) + isSupervisor = (try? c.decode(Bool.self, forKey: .is_supervisor)) ?? false + } +} + +public struct CollabLastMessage: Decodable, Equatable, Sendable { + public let seq: Int? + public let preview: String? + public let origin: String? + public let createdAt: String? + + private enum CodingKeys: String, CodingKey { + case seq, preview, origin, created_at + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + seq = try? c.decodeIfPresent(Int.self, forKey: .seq) + preview = try? c.decodeIfPresent(String.self, forKey: .preview) + origin = try? c.decodeIfPresent(String.self, forKey: .origin) + createdAt = try? c.decodeIfPresent(String.self, forKey: .created_at) + } +} + +public struct CollabSidebarItem: Decodable, Identifiable, Equatable, Hashable, Sendable { + public let kind: String // "group" or "dm" + public let threadId: String + public let spaceId: String? + public let name: String + public let tagColor: String? + public let lastMessage: CollabLastMessage? + public let lastActivityAt: String? + public let unreadCount: Int + public let membersPreview: [CollabSidebarMember] + public let memberCount: Int + public let member: CollabSidebarMember? + public let groupId: String? + + public var id: String { threadId } + public var isGroup: Bool { kind == "group" } + public var isDirect: Bool { kind == "dm" } + + /// The spaceId used by `space.listMessages`, `space.post`, `space.submit`, etc. + public var targetSpaceId: String { + if isDirect { return threadId } + return spaceId ?? threadId + } + + public var displayName: String { + if isDirect, let memberName = member?.name, !memberName.isEmpty { + return memberName + } + return name.isEmpty ? (isGroup ? "未命名群组" : "助手") : name + } + + public var activityDate: Date? { + guard let raw = lastActivityAt ?? lastMessage?.createdAt else { return nil } + return ConversationListItem.parseDate(raw) + } + + public static func == (lhs: CollabSidebarItem, rhs: CollabSidebarItem) -> Bool { + lhs.threadId == rhs.threadId + && lhs.name == rhs.name + && lhs.tagColor == rhs.tagColor + && lhs.unreadCount == rhs.unreadCount + && lhs.lastMessage == rhs.lastMessage + && lhs.memberCount == rhs.memberCount + && lhs.member == rhs.member + && lhs.groupId == rhs.groupId + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(threadId) + } + + private enum CodingKeys: String, CodingKey { + case kind, thread_id, space_id, name, tag_color, last_message, last_activity_at + case unread_count, members_preview, member_count, member, group_id + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + kind = (try? c.decode(String.self, forKey: .kind)) ?? "group" + threadId = (try? c.decode(String.self, forKey: .thread_id)) ?? "" + spaceId = try? c.decodeIfPresent(String.self, forKey: .space_id) + name = (try? c.decode(String.self, forKey: .name)) ?? "" + tagColor = try? c.decodeIfPresent(String.self, forKey: .tag_color) + lastMessage = try? c.decodeIfPresent(CollabLastMessage.self, forKey: .last_message) + lastActivityAt = try? c.decodeIfPresent(String.self, forKey: .last_activity_at) + unreadCount = (try? c.decode(Int.self, forKey: .unread_count)) ?? 0 + membersPreview = (try? c.decode([CollabSidebarMember].self, forKey: .members_preview)) ?? [] + memberCount = (try? c.decode(Int.self, forKey: .member_count)) ?? 0 + member = try? c.decodeIfPresent(CollabSidebarMember.self, forKey: .member) + groupId = try? c.decodeIfPresent(String.self, forKey: .group_id) + } +} + +public struct CollabContactGroup: Decodable, Identifiable, Equatable, Sendable { + public let groupId: String + public let workspaceId: String + public let name: String + public let sortOrder: Int + + public var id: String { groupId } + + private enum CodingKeys: String, CodingKey { + case group_id, workspace_id, name, sort_order + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + groupId = (try? c.decode(String.self, forKey: .group_id)) ?? "" + workspaceId = (try? c.decode(String.self, forKey: .workspace_id)) ?? "" + name = (try? c.decode(String.self, forKey: .name)) ?? "" + sortOrder = (try? c.decode(Int.self, forKey: .sort_order)) ?? 0 + } +} + +// MARK: - Space Members & Roles + +public struct CollabSpaceSummary: Decodable, Identifiable, Equatable, Sendable { + public let spaceId: String + public let name: String + public let leadMemberId: String? + + public var id: String { spaceId } + + private enum CodingKeys: String, CodingKey { + case space_id, name, lead_member_id + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + spaceId = (try? c.decode(String.self, forKey: .space_id)) ?? "" + name = (try? c.decode(String.self, forKey: .name)) ?? "" + leadMemberId = try? c.decodeIfPresent(String.self, forKey: .lead_member_id) + } +} + +public struct CollabSpaceMember: Decodable, Identifiable, Equatable, Sendable { + public let memberId: String + public let identityMemberId: String? + public let nickname: String + public let kind: String + public let avatar: String? + public let color: String? + public let conversationId: String? + public let isSupervisor: Bool + + public var id: String { memberId.isEmpty ? (conversationId ?? nickname) : memberId } + public var isAgent: Bool { kind.isEmpty || kind == "agent" } + public var resolvedIdentityId: String { + if let id = identityMemberId, !id.isEmpty { return id } + return memberId + } + + public var botAvatar: CollabBotAvatarConfig { + CollabBotAvatarConfig.resolve( + rawAvatar: avatar, + rawColor: color, + fallbackSeed: nickname.isEmpty ? resolvedIdentityId : nickname + ) + } + + private enum CodingKeys: String, CodingKey { + case member_id, identity_member_id, nickname, kind, avatar, color, conversation_id, is_supervisor + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + memberId = (try? c.decode(String.self, forKey: .member_id)) ?? "" + identityMemberId = try? c.decodeIfPresent(String.self, forKey: .identity_member_id) + nickname = (try? c.decode(String.self, forKey: .nickname)) ?? "助手" + kind = (try? c.decode(String.self, forKey: .kind)) ?? "agent" + if let s = try? c.decodeIfPresent(String.self, forKey: .avatar) { + avatar = s + } else if let obj = try? c.decodeIfPresent(CollabBotAvatarConfig.self, forKey: .avatar) { + avatar = obj.jsonString + } else { + avatar = nil + } + color = try? c.decodeIfPresent(String.self, forKey: .color) + conversationId = try? c.decodeIfPresent(String.self, forKey: .conversation_id) + isSupervisor = (try? c.decode(Bool.self, forKey: .is_supervisor)) ?? false + } +} + +public struct CollabRole: Decodable, Identifiable, Equatable, Sendable { + public let id: String + public let name: String + public let teamId: String? + public let summary: String + public let personaPrompt: String + public let agentId: String + public let modeId: String? + + private enum CodingKeys: String, CodingKey { + case id, name, team_id, summary, persona_prompt, agent_id, mode_id + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = (try? c.decode(String.self, forKey: .id)) ?? "" + name = (try? c.decode(String.self, forKey: .name)) ?? "" + teamId = try? c.decodeIfPresent(String.self, forKey: .team_id) + summary = (try? c.decode(String.self, forKey: .summary)) ?? "" + personaPrompt = (try? c.decode(String.self, forKey: .persona_prompt)) ?? "" + agentId = (try? c.decode(String.self, forKey: .agent_id)) ?? "" + modeId = try? c.decodeIfPresent(String.self, forKey: .mode_id) + } +} + +public struct CollabTeam: Decodable, Identifiable, Equatable, Sendable { + public let id: String + public let name: String + public let summary: String? + + private enum CodingKeys: String, CodingKey { + case id, name, summary + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = (try? c.decode(String.self, forKey: .id)) ?? "" + name = (try? c.decode(String.self, forKey: .name)) ?? "" + summary = try? c.decodeIfPresent(String.self, forKey: .summary) + } +} + +// MARK: - Messages, Receipts, Reactions, Cards, & Scheduled + +public struct CollabDeliveryReceipt: Decodable, Identifiable, Equatable, Sendable { + public let conversationId: String? + public let nickname: String? + public let delivered: String? + public let state: String? + public let turnId: String? + + public var id: String { "\(conversationId ?? "")-\(nickname ?? "")-\(effectiveState)" } + + public var effectiveState: String { + if let state, !state.isEmpty { return state } + return delivered ?? "queued" + } + + public var stateLabel: String { + switch effectiveState { + case "queued", "dispatched": return "排队中" + case "processing": return "处理中" + case "replied": return "已回复" + case "passed": return "已略过" + case "timed_out": return "超时" + case "cancelled": return "已取消" + case "failed": return "失败" + case "limit_reached": return "达上限" + default: return effectiveState + } + } + + public var isProcessing: Bool { + effectiveState == "processing" || effectiveState == "queued" + } + + private enum CodingKeys: String, CodingKey { + case conversation_id, nickname, delivered, state, turn_id + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + conversationId = try? c.decodeIfPresent(String.self, forKey: .conversation_id) + nickname = try? c.decodeIfPresent(String.self, forKey: .nickname) + delivered = try? c.decodeIfPresent(String.self, forKey: .delivered) + state = try? c.decodeIfPresent(String.self, forKey: .state) + turnId = try? c.decodeIfPresent(String.self, forKey: .turn_id) + } +} + +public struct CollabReaction: Decodable, Equatable, Sendable { + public let emoji: String + public let actor: String +} + +public struct CollabMessageEnvelope: Decodable, Equatable, Sendable { + public let id: String? + public let sender: String + public let content: String + public let summary: String? + public let to: [String] + public let published: String? + public let conversationId: String? + public let reactions: [CollabReaction] + + public var isFromUser: Bool { + let lower = sender.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + return lower == "person" || lower == "user" || sender == "你" || sender == "用户" + } + + public var isSystem: Bool { + sender.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == "system" + } + + public var displaySender: String { + if isFromUser { return "你" } + if isSystem { return "系统" } + return sender.isEmpty ? "助手" : sender + } + + public var recipientLabels: [String] { + to.compactMap { raw in + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { return nil } + let lower = trimmed.lowercased() + if lower == "person" || lower == "user" || trimmed == "你" || trimmed == "用户" { + return nil + } + return trimmed.hasPrefix("@") ? String(trimmed.dropFirst()) : trimmed + } + } + + private enum CodingKeys: String, CodingKey { + case id, sender, content, summary, to, published, conversation_id, conversationId, reactions + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = try? c.decodeIfPresent(String.self, forKey: .id) + sender = (try? c.decode(String.self, forKey: .sender)) ?? "" + content = (try? c.decode(String.self, forKey: .content)) ?? "" + summary = try? c.decodeIfPresent(String.self, forKey: .summary) + to = (try? c.decode([String].self, forKey: .to)) ?? [] + published = try? c.decodeIfPresent(String.self, forKey: .published) + conversationId = (try? c.decodeIfPresent(String.self, forKey: .conversation_id)) + ?? (try? c.decodeIfPresent(String.self, forKey: .conversationId)) + reactions = (try? c.decode([CollabReaction].self, forKey: .reactions)) ?? [] + } +} + +public struct CollabSpaceMessage: Decodable, Identifiable, Equatable, Sendable { + public let rawId: String? + public let seq: Int + public let origin: String? + public let inReplyTo: String? + public let streaming: Bool + public let receipts: [CollabDeliveryReceipt] + public let envelope: CollabMessageEnvelope + + public var id: String { + let candidate = (rawId ?? envelope.id ?? "").replacingOccurrences(of: "vibex://space-message/", with: "") + return candidate.isEmpty ? "seq-\(seq)" : candidate + } + + public var isFromUser: Bool { + origin == "user" || envelope.isFromUser + } + + /// Grouped emoji reactions -> (emoji, count, userReacted). + public var groupedReactions: [(emoji: String, count: Int, byUser: Bool)] { + var order: [String] = [] + var counts: [String: Int] = [:] + var byUser: Set = [] + for r in envelope.reactions { + if counts[r.emoji] == nil { order.append(r.emoji) } + counts[r.emoji, default: 0] += 1 + if r.actor.lowercased() == "person" || r.actor.lowercased() == "user" { + byUser.insert(r.emoji) + } + } + return order.map { ($0, counts[$0] ?? 1, byUser.contains($0)) } + } + + private enum CodingKeys: String, CodingKey { + case id, seq, origin, in_reply_to, inReplyTo, streaming, receipts, envelope + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + rawId = try? c.decodeIfPresent(String.self, forKey: .id) + seq = (try? c.decode(Int.self, forKey: .seq)) ?? 0 + origin = try? c.decodeIfPresent(String.self, forKey: .origin) + inReplyTo = (try? c.decodeIfPresent(String.self, forKey: .in_reply_to)) + ?? (try? c.decodeIfPresent(String.self, forKey: .inReplyTo)) + streaming = (try? c.decode(Bool.self, forKey: .streaming)) ?? false + receipts = (try? c.decode([CollabDeliveryReceipt].self, forKey: .receipts)) ?? [] + envelope = try c.decode(CollabMessageEnvelope.self, forKey: .envelope) + } +} + +public struct CollabScheduledMessage: Decodable, Identifiable, Equatable, Sendable { + public let id: String + public let spaceId: String + public let content: String + public let deliverAt: String + public let status: String? + + private enum CodingKeys: String, CodingKey { + case id, delayed_input_id, space_id, content, deliver_at, status + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = (try? c.decodeIfPresent(String.self, forKey: .id)) + ?? (try? c.decodeIfPresent(String.self, forKey: .delayed_input_id)) + ?? UUID().uuidString + spaceId = (try? c.decode(String.self, forKey: .space_id)) ?? "" + content = (try? c.decode(String.self, forKey: .content)) ?? "" + deliverAt = (try? c.decode(String.self, forKey: .deliver_at)) ?? "" + status = try? c.decodeIfPresent(String.self, forKey: .status) + } +} + +public struct CollabCard: Decodable, Identifiable, Equatable, Sendable { + public let id: String + public let kind: String // "ask" or "approval" + public let status: String // "pending" or "resolved" + public let action: String? + public let command: String? + public let reason: String? + public let question: String? + public let options: [String] + + public var isPending: Bool { status == "pending" } + + private enum CodingKeys: String, CodingKey { + case id, kind, status, payload + } + + private enum PayloadKeys: String, CodingKey { + case action, command, reason, question, options + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = (try? c.decode(String.self, forKey: .id)) ?? "" + kind = (try? c.decode(String.self, forKey: .kind)) ?? "ask" + status = (try? c.decode(String.self, forKey: .status)) ?? "pending" + if let p = try? c.nestedContainer(keyedBy: PayloadKeys.self, forKey: .payload) { + action = try? p.decodeIfPresent(String.self, forKey: .action) + command = try? p.decodeIfPresent(String.self, forKey: .command) + reason = try? p.decodeIfPresent(String.self, forKey: .reason) + question = try? p.decodeIfPresent(String.self, forKey: .question) + options = (try? p.decode([String].self, forKey: .options)) ?? [] + } else { + action = nil + command = nil + reason = nil + question = nil + options = [] + } + } +} + +public struct CollabMessagesPage: Decodable, Equatable, Sendable { + public let messages: [CollabSpaceMessage] + public let scheduled: [CollabScheduledMessage] + public let cards: [CollabCard] + public let conversationId: String? + + private enum CodingKeys: String, CodingKey { + case messages, scheduled, cards, conversationId + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + messages = (try? c.decode([CollabSpaceMessage].self, forKey: .messages)) ?? [] + scheduled = (try? c.decode([CollabScheduledMessage].self, forKey: .scheduled)) ?? [] + cards = (try? c.decode([CollabCard].self, forKey: .cards)) ?? [] + conversationId = try? c.decodeIfPresent(String.self, forKey: .conversationId) + } +} + +// MARK: - Memory & Collection + +public struct CollabMemoryFact: Decodable, Identifiable, Equatable, Sendable { + public let id: Int + public let content: String + public let scope: String + public let origin: String + + public var scopeLabel: String { + if scope == "global" { return "全局" } + if scope == "private" { return "私聊" } + if scope.hasPrefix("thread:") || scope == "thread" { return "本群" } + return scope + } + + private enum CodingKeys: String, CodingKey { + case id, content, scope, origin + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = (try? c.decode(Int.self, forKey: .id)) ?? 0 + content = (try? c.decode(String.self, forKey: .content)) ?? "" + scope = (try? c.decode(String.self, forKey: .scope)) ?? "thread" + origin = (try? c.decode(String.self, forKey: .origin)) ?? "user" + } +} + +public struct CollabMemoryTopic: Decodable, Identifiable, Equatable, Sendable { + public let topic: String + public let title: String + public let preview: String? + public let content: String? + + public var id: String { topic } + + private enum CodingKeys: String, CodingKey { + case topic, title, summary, preview, content + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + topic = (try? c.decode(String.self, forKey: .topic)) ?? "" + title = (try? c.decode(String.self, forKey: .title)) ?? topic + preview = (try? c.decodeIfPresent(String.self, forKey: .preview)) + ?? (try? c.decodeIfPresent(String.self, forKey: .summary)) + content = try? c.decodeIfPresent(String.self, forKey: .content) + } +} + +public struct CollabMemoryView: Decodable, Equatable, Sendable { + public let facts: [CollabMemoryFact] + public let topics: [CollabMemoryTopic] + + private enum CodingKeys: String, CodingKey { + case facts, topics + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + facts = (try? c.decode([CollabMemoryFact].self, forKey: .facts)) ?? [] + topics = (try? c.decode([CollabMemoryTopic].self, forKey: .topics)) ?? [] + } +} + +public struct CollabCollectionItem: Decodable, Identifiable, Equatable, Sendable { + public let id: String + public let spaceId: String + public let creatorNickname: String + public let kind: String + public let name: String + public let note: String + public let textContent: String? + public let createdAt: String + + private enum CodingKeys: String, CodingKey { + case id, space_id, creator_nickname, item_kind, kind, file_name, name, note, text_content, created_at + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = (try? c.decode(String.self, forKey: .id)) ?? "" + spaceId = (try? c.decode(String.self, forKey: .space_id)) ?? "" + creatorNickname = (try? c.decode(String.self, forKey: .creator_nickname)) ?? "User" + kind = (try? c.decodeIfPresent(String.self, forKey: .item_kind)) + ?? (try? c.decodeIfPresent(String.self, forKey: .kind)) + ?? "text" + name = (try? c.decodeIfPresent(String.self, forKey: .name)) + ?? (try? c.decodeIfPresent(String.self, forKey: .file_name)) + ?? "未命名收藏" + note = (try? c.decode(String.self, forKey: .note)) ?? "" + textContent = try? c.decodeIfPresent(String.self, forKey: .text_content) + createdAt = (try? c.decode(String.self, forKey: .created_at)) ?? "" + } +} + +public struct CollabMemberConfig: Decodable, Equatable, Sendable { + public let agentId: String? + public let modeId: String? + public let personaPrompt: String? + + private enum CodingKeys: String, CodingKey { + case agent_id, agentId, mode_id, modeId, persona_prompt, personaPrompt + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + agentId = (try? c.decodeIfPresent(String.self, forKey: .agent_id)) + ?? (try? c.decodeIfPresent(String.self, forKey: .agentId)) + modeId = (try? c.decodeIfPresent(String.self, forKey: .mode_id)) + ?? (try? c.decodeIfPresent(String.self, forKey: .modeId)) + personaPrompt = (try? c.decodeIfPresent(String.self, forKey: .persona_prompt)) + ?? (try? c.decodeIfPresent(String.self, forKey: .personaPrompt)) + } +} diff --git a/mobile/ios/Sources/CompanionCore/CompanionScopes.swift b/mobile/ios/Sources/CompanionCore/CompanionScopes.swift index 91bc2c24c..76da5ae09 100644 --- a/mobile/ios/Sources/CompanionCore/CompanionScopes.swift +++ b/mobile/ios/Sources/CompanionCore/CompanionScopes.swift @@ -9,6 +9,7 @@ public enum CompanionScopes { "conversation.question", "conversation.cancel", "conversation.steer", + "plugin.read", "artifact.read", "workflow.read", "automation.read", diff --git a/mobile/ios/Sources/CompanionCore/HostClient.swift b/mobile/ios/Sources/CompanionCore/HostClient.swift index 0a0e1b717..2a938c09f 100644 --- a/mobile/ios/Sources/CompanionCore/HostClient.swift +++ b/mobile/ios/Sources/CompanionCore/HostClient.swift @@ -185,10 +185,17 @@ public struct HostClient: Sendable { public func respondPermission( conversationID: String, permissionID: String, - optionID: String? + optionID: String?, + persist: Bool = false ) async throws { - let response: [String: Any] = optionID.map { ["kind": "selected", "option_id": $0] } - ?? ["kind": "cancelled"] + let response: [String: Any] + if let optionID { + var dict: [String: Any] = ["kind": "selected", "option_id": optionID] + if persist { dict["persist"] = true } + response = dict + } else { + response = ["kind": "cancelled"] + } try await command("conversation_respond_permission", [ "request": [ "conversationId": conversationID, @@ -214,6 +221,403 @@ public struct HostClient: Sendable { ]) } + public func archiveConversation(conversationID: String) async throws { + try await command("conversation_archive", [ + "conversationId": conversationID, + ]) + } + + public func deleteConversation(conversationID: String) async throws { + try await command("conversation_delete", [ + "conversationId": conversationID, + ]) + } + + // MARK: - Collaboration Space (`collaboration_call`) + + public func collaborationCall( + _ operation: String, + input: [String: Any] = [:], + as type: T.Type = T.self + ) async throws -> T { + try await call( + "collaboration_call", + args: [ + "capability": "collaboration", + "operation": operation, + "input": input, + ], + as: type + ) + } + + public func collaborationCommand(_ operation: String, input: [String: Any] = [:]) async throws { + let _: JSONValue = try await collaborationCall(operation, input: input, as: JSONValue.self) + } + + public func collabSidebar(workspaceID: String) async throws -> [CollabSidebarItem] { + struct Page: Decodable { let items: [CollabSidebarItem]? } + return try await collaborationCall("thread.listSidebar", input: ["workspaceId": workspaceID], as: Page.self).items ?? [] + } + + public func collabContactGroups(workspaceID: String) async throws -> [CollabContactGroup] { + struct Page: Decodable { let groups: [CollabContactGroup]? } + let groups = try await collaborationCall("contactGroup.list", input: ["workspaceId": workspaceID], as: Page.self).groups ?? [] + return groups.sorted { $0.sortOrder < $1.sortOrder } + } + + public func collabSpaces(workspaceID: String) async throws -> [CollabSpaceSummary] { + struct Page: Decodable { let spaces: [CollabSpaceSummary]? } + return try await collaborationCall("space.list", input: ["workspaceId": workspaceID], as: Page.self).spaces ?? [] + } + + public func collabSpaceMembers(spaceID: String) async throws -> [CollabSpaceMember] { + struct Page: Decodable { let members: [CollabSpaceMember]? } + return try await collaborationCall("space.listMembers", input: ["spaceId": spaceID], as: Page.self).members ?? [] + } + + public func collabMessages(spaceID: String, limit: Int = 200) async throws -> CollabMessagesPage { + try await collaborationCall( + "space.listMessages", + input: ["spaceId": spaceID, "latest": true, "limit": limit], + as: CollabMessagesPage.self + ) + } + + public func collabPostMessage( + spaceID: String, + content: String, + to: [String] = [], + inReplyTo: String? = nil, + delaySeconds: Int? = nil + ) async throws { + var input: [String: Any] = [ + "spaceId": spaceID, + "content": content, + "operationId": UUID().uuidString.lowercased(), + ] + if !to.isEmpty { input["to"] = to } + if let inReplyTo, !inReplyTo.isEmpty { input["inReplyTo"] = inReplyTo } + if let delaySeconds, delaySeconds > 0 { + input["delaySeconds"] = delaySeconds + try await collaborationCommand("space.post", input: input) + } else { + try await collaborationCommand("space.submit", input: input) + } + } + + public func collabReact(spaceID: String, messageID: String, emoji: String) async throws { + try await collaborationCommand("space.react", input: [ + "spaceId": spaceID, + "messageId": messageID, + "emoji": emoji, + ]) + } + + public func collabMarkRead(threadID: String, seq: Int? = nil) async throws { + var input: [String: Any] = threadID.hasPrefix("direct:") + ? ["threadId": threadID] + : ["spaceId": threadID] + if let seq { input["seq"] = seq } + try await collaborationCommand("thread.markRead", input: input) + } + + public func collabMarkUnread(threadID: String) async throws { + let input: [String: Any] = threadID.hasPrefix("direct:") + ? ["threadId": threadID] + : ["spaceId": threadID] + try await collaborationCommand("thread.markUnread", input: input) + } + + public func collabCreateSpace(workspaceID: String, name: String) async throws -> CollabSpaceSummary { + try await collaborationCall( + "space.create", + input: [ + "workspaceId": workspaceID, + "name": name, + "operationId": UUID().uuidString.lowercased(), + ], + as: CollabSpaceSummary.self + ) + } + + public func collabCreateMember( + workspaceID: String, + name: String, + agentID: String? = nil, + roleID: String? = nil, + personaPrompt: String? = nil, + avatar: CollabBotAvatarConfig? = nil, + color: String? = nil, + isSupervisor: Bool = false + ) async throws -> JSONValue { + var input: [String: Any] = [ + "workspaceId": workspaceID, + "nickname": name, + "name": name, + "operationId": UUID().uuidString.lowercased(), + "isSupervisor": isSupervisor, + ] + if let agentID, !agentID.isEmpty { input["agentId"] = agentID } + if let roleID, !roleID.isEmpty { input["roleId"] = roleID } + if let personaPrompt, !personaPrompt.isEmpty { input["personaPrompt"] = personaPrompt } + if let avatar { + input["avatar"] = avatar.jsonString + input["color"] = avatar.color + } else if let color, !color.isEmpty { + input["color"] = color + } + return try await collaborationCall("space.createMember", input: input, as: JSONValue.self) + } + + public func collabAddMemberToSpace( + spaceID: String, + conversationID: String, + nickname: String + ) async throws { + try await collaborationCommand("space.addMember", input: [ + "spaceId": spaceID, + "conversationId": conversationID, + "nickname": nickname, + "operationId": UUID().uuidString.lowercased(), + ]) + } + + public func collabResolveSession(memberID: String, threadID: String) async throws -> String? { + struct Page: Decodable { let conversationId: String? } + return try await collaborationCall( + "member.session.resolve", + input: ["memberId": memberID, "threadId": threadID], + as: Page.self + ).conversationId + } + + public func collabResolveCard( + cardID: String, + decision: String? = nil, + answer: String? = nil, + declined: Bool = false + ) async throws { + var input: [String: Any] = [ + "cardId": cardID, + "declined": declined, + ] + if let decision { input["decision"] = decision } + if let answer { input["answer"] = answer } + try await collaborationCommand("card.resolve", input: input) + } + + public func collabCancelSpaceTurn(spaceID: String, memberID: String) async throws { + try await collaborationCommand("space.cancelTurn", input: [ + "spaceId": spaceID, + "memberId": memberID, + ]) + } + + public func collabRoles() async throws -> [CollabRole] { + struct Page: Decodable { let roles: [CollabRole]? } + return try await collaborationCall("role.list", as: Page.self).roles ?? [] + } + + public func collabTeams() async throws -> [CollabTeam] { + struct Page: Decodable { let teams: [CollabTeam]? } + return try await collaborationCall("team.list", as: Page.self).teams ?? [] + } + + public func collabMemoryView(spaceID: String, memberID: String? = nil) async throws -> CollabMemoryView { + var input: [String: Any] = ["spaceId": spaceID] + if let memberID, !memberID.isEmpty { input["memberId"] = memberID } + return try await collaborationCall("space.memory.view", input: input, as: CollabMemoryView.self) + } + + public func collabCollectionItems(spaceID: String) async throws -> [CollabCollectionItem] { + struct Page: Decodable { let items: [CollabCollectionItem]? } + return try await collaborationCall("space.listCollection", input: ["spaceId": spaceID], as: Page.self).items ?? [] + } + + // MARK: - Kanban Board & Usage Dashboard + + public func kanbanWorkspaces(projectID: String) async throws -> [KanbanWorkspaceRecord] { + try await call( + "get_project_workspaces", + args: ["projectId": projectID], + as: [KanbanWorkspaceRecord].self + ) + } + + public func kanbanSessionSummaries(workspaceID: String) async throws -> [KanbanSessionSummary] { + try await call( + "get_session_summaries", + args: ["workspaceId": workspaceID], + as: [KanbanSessionSummary].self + ) + } + + public func kanbanAllSessions(workspaceIDs: [String]) async throws -> [KanbanSessionSummary] { + let uniqueIDs = Array(NSOrderedSet(array: workspaceIDs.filter { !$0.isEmpty })) as? [String] ?? [] + var byID: [String: KanbanSessionSummary] = [:] + for wsID in uniqueIDs { + if let list = try? await kanbanSessionSummaries(workspaceID: wsID) { + for item in list { + byID[item.id] = item + } + } + } + if byID.isEmpty { + let recent: [ConversationListItem] = (try? await call( + "conversation_list_recent", + args: ["limit": 200], + as: [ConversationListItem].self + )) ?? [] + let allowed = Set(uniqueIDs.map { $0.lowercased() }) + for conv in recent where allowed.isEmpty || allowed.contains(conv.workspace_id.lowercased()) { + let summary = KanbanSessionSummary(fromConversation: conv) + byID[summary.id] = summary + } + } + return byID.values.sorted { + ($0.updatedDate ?? .distantPast) > ($1.updatedDate ?? .distantPast) + } + } + + public func updateSessionStatus(sessionID: String, status: KanbanSessionStatus) async throws { + do { + try await command("update_session_status", [ + "sessionId": sessionID, + "status": status.rawValue, + ]) + } catch { + if status == .archived { + try await archiveConversation(conversationID: sessionID) + } else { + try await command("conversation_set_status", [ + "conversationId": sessionID, + "status": status.rawValue, + ]) + } + } + } + + public func renameSession(sessionID: String, name: String?) async throws { + let trimmed = name?.trimmingCharacters(in: .whitespacesAndNewlines) + do { + try await command("rename_session", [ + "sessionId": sessionID, + "name": (trimmed?.isEmpty == false ? trimmed! : NSNull()) as Any, + ]) + } catch { + try await command("conversation_rename", [ + "conversationId": sessionID, + "title": trimmed ?? "", + ]) + } + } + + public func setSessionPinned(sessionID: String, pinned: Bool) async throws { + do { + try await command("set_session_pinned", [ + "sessionId": sessionID, + "pinned": pinned, + ]) + } catch { + try await command("conversation_set_pinned", [ + "conversationId": sessionID, + "pinned": pinned, + ]) + } + } + + public func markSessionViewed(sessionID: String) async throws { + try await command("mark_session_viewed", [ + "sessionId": sessionID, + ]) + } + + public func deleteKanbanSession(sessionID: String) async throws { + do { + try await command("delete_session", [ + "sessionId": sessionID, + ]) + } catch { + try await deleteConversation(conversationID: sessionID) + } + } + + public func forkConversation(conversationID: String) async throws -> String? { + let res: JSONValue = try await call( + "conversation_fork", + args: ["conversationId": conversationID], + as: JSONValue.self + ) + return res["conversationId"]?.stringValue ?? res["conversation_id"]?.stringValue + } + + public func projectUsageStatistics( + scope: String, + projectID: String? = nil, + dateRange: UsageDateRange = .sevenDays + ) async throws -> ProjectUsageStatistics { + var args: [String: Any] = [ + "scope": scope, + "dateRange": dateRange.rawValue, + ] + if let projectID, !projectID.isEmpty { + args["projectId"] = projectID + } else { + args["projectId"] = NSNull() + } + return try await call( + "get_project_usage_statistics", + args: args, + as: ProjectUsageStatistics.self + ) + } + + public func agentPlanUsage(agentID: String) async throws -> PlanUsageResponse { + try await call( + "agent_plan_usage", + args: ["agentId": agentID], + as: PlanUsageResponse.self + ) + } + + // MARK: - Settings / Skills / MCP / Plugins / System Info RPCs + + public func localSkills() async throws -> [LocalSkillItem] { + try await call("scan_local_skills", as: [LocalSkillItem].self) + } + + public func readLocalSkill(skillID: String) async throws -> LocalSkillContentItem { + try await call( + "read_local_skill", + args: ["skillId": skillID], + as: LocalSkillContentItem.self + ) + } + + public func localMcpServers() async throws -> [LocalMcpServerItem] { + try await call("mcp_scan_local", as: [LocalMcpServerItem].self) + } + + public func userSystemInfo() async throws -> HostUserSystemInfo { + try await call("get_user_system_info", as: HostUserSystemInfo.self) + } + + public func pluginCatalog() async throws -> [PluginCatalogItem] { + do { + let res: PluginControlCatalogResponse = try await call( + "plugin_control_catalog", + as: PluginControlCatalogResponse.self + ) + return res.plugins + } catch { + if let info = try? await userSystemInfo(), !info.plugins.isEmpty { + return info.plugins + } + throw error + } + } + private func headers(contentType: Bool) -> [String: String] { var result = [ "authorization": "Bearer \(accessToken)", diff --git a/mobile/ios/Sources/CompanionCore/HostModels.swift b/mobile/ios/Sources/CompanionCore/HostModels.swift index 43b1ea726..3f89b6c5f 100644 --- a/mobile/ios/Sources/CompanionCore/HostModels.swift +++ b/mobile/ios/Sources/CompanionCore/HostModels.swift @@ -16,6 +16,26 @@ public struct ConversationListItem: Decodable, Identifiable, Equatable, Sendable case id, workspace_id, title, status, agent_id, model, message_count, updated_at } + public init( + id: String, + workspace_id: String, + title: String? = nil, + status: String? = nil, + agent_id: String? = nil, + model: String? = nil, + message_count: Int = 0, + updated_at: String = "" + ) { + self.id = id + self.workspace_id = workspace_id + self.title = title + self.status = status + self.agent_id = agent_id + self.model = model + self.message_count = message_count + self.updated_at = updated_at + } + public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = try c.decode(String.self, forKey: .id) @@ -90,11 +110,23 @@ public struct ToolStep: Identifiable, Equatable, Sendable { public let label: String /// The first lines of the tool input, for the expanded row. public let detail: [String] + /// Structured questions when this tool call is `ask_question` / `AskUserQuestion`. + public var questions: [FormQuestion] = [] public var isFinished: Bool { guard let status else { return false } return ["completed", "complete", "success", "done", "failed", "error"].contains(status.lowercased()) } + + public var isAskQuestion: Bool { + if !questions.isEmpty { return true } + let lowered = name.lowercased() + return lowered == "ask_question" + || lowered == "ask_user_question" + || lowered == "askuserquestion" + || lowered.hasSuffix("__ask_user_question") + || lowered.hasSuffix("_ask_question") + } } /// One step of the Agent's plan/todo checklist (`plan` content block). @@ -107,6 +139,19 @@ public struct PlanTask: Identifiable, Equatable, Sendable { public let priority: String? } +public enum TimelineSegment: Identifiable, Equatable, Sendable { + case thinking(id: String, text: String) + case tools(id: String, steps: [ToolStep]) + case text(id: String, text: String) + + public var id: String { + switch self { + case .thinking(let id, _), .tools(let id, _), .text(let id, _): + return id + } + } +} + public struct TimelineItem: Identifiable, Equatable, Sendable { public enum Role: Sendable { case user, assistant } @@ -118,6 +163,8 @@ public struct TimelineItem: Identifiable, Equatable, Sendable { public var tools: [ToolStep] = [] public var plan: [PlanTask] = [] public var changes: [FileChangeItem] = [] + /// Chronological blocks within an assistant turn (thinking, tool call runs, and text segments). + public var segments: [TimelineSegment] = [] public var durationMs: Int? public var hasTrace: Bool { !thinking.isEmpty || !tools.isEmpty || !changes.isEmpty } @@ -163,21 +210,49 @@ public enum TimelineBuilder { for (index, block) in (turn["blocks"]?.arrayValue ?? []).enumerated() { switch block["type"]?.stringValue { case "text": - if let text = block["text"]?.stringValue { texts.append(text) } + if let text = block["text"]?.stringValue { + texts.append(text) + if role == .assistant, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + if case .text(let segID, let prev)? = item.segments.last { + let sep = prev.hasSuffix("\n") || text.hasPrefix("\n") ? "" : "\n\n" + item.segments[item.segments.count - 1] = .text(id: segID, text: prev + sep + text) + } else { + item.segments.append(.text(id: "\(rowID)-seg-\(index)", text: text)) + } + } + } case "thinking": - if role == .assistant, let text = block["text"]?.stringValue { thoughts.append(text) } + if role == .assistant, let text = block["text"]?.stringValue { + thoughts.append(text) + if !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + if case .thinking(let segID, let prev)? = item.segments.last { + item.segments[item.segments.count - 1] = .thinking(id: segID, text: prev + "\n\n" + text) + } else { + item.segments.append(.thinking(id: "\(rowID)-seg-\(index)", text: text)) + } + } + } case "tool_use": guard role == .assistant, let name = block["tool_name"]?.stringValue else { continue } let input = ToolInput(block["input_preview"]?.stringValue) - item.tools.append(ToolStep( - id: block["tool_use_id"]?.stringValue ?? "\(rowID)-\(index)", + let stepID = block["tool_use_id"]?.stringValue ?? "\(rowID)-\(index)" + let step = ToolStep( + id: stepID, name: name, status: block["status"]?.stringValue, preview: input.target, edits: input.edits, label: input.label(for: name), - detail: input.detail - )) + detail: input.detail, + questions: input.questions + ) + item.tools.append(step) + if case .tools(let segID, var existingSteps)? = item.segments.last { + existingSteps.append(step) + item.segments[item.segments.count - 1] = .tools(id: segID, steps: existingSteps) + } else { + item.segments.append(.tools(id: "\(rowID)-tools-\(stepID)", steps: [step])) + } case "plan": guard role == .assistant else { continue } item.plan = (block["entries"]?.arrayValue ?? []).enumerated().compactMap { offset, entry in @@ -266,6 +341,7 @@ struct ToolInput { let target: String? let detail: [String] var edits: [ToolEdit] = [] + var questions: [FormQuestion] = [] private static let targetKeys = ["file_path", "path", "command", "cmd", "pattern", "query", "url", "description"] @@ -282,6 +358,41 @@ struct ToolInput { detail = Self.lines(raw) return } + if let rawQuestions = object["questions"] as? [[String: Any]], !rawQuestions.isEmpty { + questions = rawQuestions.enumerated().compactMap { index, q in + let qText = (q["question"] as? String) ?? (q["header"] as? String) ?? "" + guard !qText.isEmpty else { return nil } + let header = (q["header"] as? String) ?? "问题 \(index + 1)" + let multi = (q["is_multi_select"] as? Bool) ?? (q["multiSelect"] as? Bool) ?? (q["multi_select"] as? Bool) ?? false + var parsedChoices: [QuestionChoice] = [] + if let opts = q["options"] as? [Any] { + parsedChoices = opts.compactMap { opt in + if let str = opt as? String { + return QuestionChoice(value: .string(str), label: str, description: nil) + } + if let dict = opt as? [String: Any], + let label = (dict["label"] as? String) ?? (dict["value"] as? String) + { + let val = (dict["value"] as? String) ?? label + let desc = dict["description"] as? String + let rec = (dict["recommended"] as? Bool) ?? false + return QuestionChoice(value: .string(val), label: label, description: desc, recommended: rec) + } + return nil + } + } + return FormQuestion( + id: (q["id"] as? String) ?? "question-\(index + 1)", + fieldName: nil, + customFieldName: nil, + header: header, + text: qText, + multiSelect: multi, + valueType: .string, + choices: parsedChoices + ) + } + } if let path = (object["file_path"] ?? object["path"]) as? String { if let content = object["content"] as? String { edits = [ToolEdit(path: path, old: nil, new: content)] @@ -298,6 +409,8 @@ struct ToolInput { let value = key.flatMap { object[$0] as? String } if let key, let value { target = Self.clip(key.hasSuffix("path") ? (value as NSString).lastPathComponent : value, 60) + } else if let firstQuestion = questions.first { + target = Self.clip(firstQuestion.text, 60) } else { target = nil } @@ -345,49 +458,137 @@ struct ToolInput { public struct ProjectSummary: Decodable, Identifiable, Equatable, Hashable, Sendable { public let id: String public let name: String + public let rootPath: String + public let parentProjectId: String? + public let isGit: Bool + public let isHome: Bool public let workspaceIds: [String] - public init(id: String, name: String, workspaceIds: [String]) { + public var displayName: String { isHome ? "全局" : name } + + private enum CodingKeys: String, CodingKey { + case id, name, rootPath, parentProjectId, isGit, isHome, workspaceIds + } + + public init( + id: String, + name: String, + rootPath: String = "", + parentProjectId: String? = nil, + isGit: Bool = false, + isHome: Bool = false, + workspaceIds: [String] + ) { self.id = id self.name = name + self.rootPath = rootPath + self.parentProjectId = parentProjectId + self.isGit = isGit + self.isHome = isHome self.workspaceIds = workspaceIds } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + id = try c.decode(String.self, forKey: .id) + name = try c.decode(String.self, forKey: .name) + rootPath = (try? c.decode(String.self, forKey: .rootPath)) ?? "" + parentProjectId = try? c.decodeIfPresent(String.self, forKey: .parentProjectId) + isGit = (try? c.decode(Bool.self, forKey: .isGit)) ?? false + isHome = (try? c.decode(Bool.self, forKey: .isHome)) ?? false + workspaceIds = (try? c.decode([String].self, forKey: .workspaceIds)) ?? [] + } } -/// Conversations bucketed by project, newest activity first. +/// Conversations bucketed by imported project, ordered as a tree (matching the desktop's "已导入项目"). public struct ProjectGroup: Identifiable, Equatable, Sendable { public let id: String public let name: String + public let rootPath: String + public let depth: Int + public let isGit: Bool + public let isHome: Bool + public let workspaceIds: [String] public let conversations: [ConversationListItem] - public init(id: String, name: String, conversations: [ConversationListItem]) { + public init( + id: String, + name: String, + rootPath: String = "", + depth: Int = 0, + isGit: Bool = false, + isHome: Bool = false, + workspaceIds: [String] = [], + conversations: [ConversationListItem] + ) { self.id = id self.name = name + self.rootPath = rootPath + self.depth = depth + self.isGit = isGit + self.isHome = isHome + self.workspaceIds = workspaceIds self.conversations = conversations } public var latest: Date? { conversations.compactMap(\.updatedAt).max() } - /// Projects that have conversations, most recently active first; conversations whose - /// workspace belongs to no known project fall into one trailing "其他" group. + /// Every imported project in tree order (home first, then roots and their children), + /// plus a trailing "其他" group when conversations belong to no known project. public static func make(conversations: [ConversationListItem], projects: [ProjectSummary]) -> [ProjectGroup] { - var owner: [String: ProjectSummary] = [:] + var owner: [String: String] = [:] for project in projects { - for workspace in project.workspaceIds { owner[workspace.lowercased()] = project } + for workspace in project.workspaceIds { owner[workspace.lowercased()] = project.id.lowercased() } } var buckets: [String: [ConversationListItem]] = [:] - var names: [String: String] = [:] for conversation in conversations { - let project = owner[conversation.workspace_id.lowercased()] - let key = project?.id ?? "other" + let key = owner[conversation.workspace_id.lowercased()] ?? "other" buckets[key, default: []].append(conversation) - names[key] = project?.name ?? "其他" } - let groups = buckets.map { ProjectGroup(id: $0.key, name: names[$0.key] ?? "其他", conversations: $0.value) } - return groups.sorted { - if $0.id == "other" { return false } - if $1.id == "other" { return true } - return ($0.latest ?? .distantPast) > ($1.latest ?? .distantPast) + let ordered = flattenTree(projects) + var groups = ordered.map { entry in + ProjectGroup( + id: entry.project.id, + name: entry.project.displayName, + rootPath: entry.project.rootPath, + depth: entry.depth, + isGit: entry.project.isGit, + isHome: entry.project.isHome, + workspaceIds: entry.project.workspaceIds, + conversations: buckets[entry.project.id.lowercased()] ?? [] + ) + } + if let strays = buckets["other"], !strays.isEmpty { + groups.append(ProjectGroup(id: "other", name: "其他", conversations: strays)) + } + return groups + } + + private static func flattenTree(_ projects: [ProjectSummary]) -> [(project: ProjectSummary, depth: Int)] { + let home = projects.filter(\.isHome) + let rest = projects.filter { !$0.isHome } + let ordered = home + rest + let knownIds = Set(ordered.map { $0.id.lowercased() }) + var byParent: [String?: [ProjectSummary]] = [:] + for project in ordered { + let parent = project.parentProjectId?.lowercased() + let key = (parent != nil && knownIds.contains(parent!)) ? parent : nil + byParent[key, default: []].append(project) + } + var result: [(project: ProjectSummary, depth: Int)] = [] + var visited: Set = [] + func walk(_ parentId: String?, _ depth: Int) { + for project in byParent[parentId] ?? [] { + let key = project.id.lowercased() + guard visited.insert(key).inserted else { continue } + result.append((project, depth)) + walk(key, depth + 1) + } + } + walk(nil, 0) + for project in ordered where !visited.contains(project.id.lowercased()) { + result.append((project, 0)) } + return result } } diff --git a/mobile/ios/Sources/CompanionCore/QuestionForm.swift b/mobile/ios/Sources/CompanionCore/QuestionForm.swift index 978e40bef..846ef9770 100644 --- a/mobile/ios/Sources/CompanionCore/QuestionForm.swift +++ b/mobile/ios/Sources/CompanionCore/QuestionForm.swift @@ -4,7 +4,30 @@ public struct QuestionChoice: Equatable, Sendable, Identifiable { public let value: JSONValue public let label: String public let description: String? - public var id: String { label } + public let recommended: Bool + public var id: String { label + (value.displayText ?? "") } + + public init(value: JSONValue, label: String, description: String?, recommended: Bool = false) { + let parsed = Self.extractRecommended(from: label, explicit: recommended) + self.value = value + self.label = parsed.label + self.description = description + self.recommended = parsed.recommended + } + + private static func extractRecommended(from raw: String, explicit: Bool) -> (label: String, recommended: Bool) { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + let prefixes = ["(Recommended)", "(推荐)", "[Recommended]"] + for prefix in prefixes where trimmed.localizedCaseInsensitiveContains(prefix) { + let cleaned = trimmed + .replacingOccurrences(of: prefix, with: "", options: .caseInsensitive) + .trimmingCharacters(in: .whitespacesAndNewlines) + if !cleaned.isEmpty { + return (cleaned, true) + } + } + return (trimmed.isEmpty ? raw : trimmed, explicit) + } } /// One step of a question card. @@ -24,15 +47,25 @@ public struct FormQuestion: Equatable, Sendable, Identifiable { public struct QuestionAnswer: Equatable, Sendable { public var selected: [JSONValue] = [] + public var customActive = false public var customText = "" - public init(selected: [JSONValue] = [], customText: String = "") { + public init(selected: [JSONValue] = [], customActive: Bool = false, customText: String = "") { self.selected = selected + self.customActive = customActive || !customText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty self.customText = customText } - public var trimmedCustom: String { customText.trimmingCharacters(in: .whitespacesAndNewlines) } - public var isEmpty: Bool { selected.isEmpty && trimmedCustom.isEmpty } + public var trimmedCustom: String { + guard customActive || !customText.isEmpty else { return "" } + return customText.trimmingCharacters(in: .whitespacesAndNewlines) + } + public var isEmpty: Bool { + if customActive { + return selected.isEmpty && trimmedCustom.isEmpty + } + return selected.isEmpty && trimmedCustom.isEmpty + } } /// Turns a question request into card steps and the answer back into the `content` the Agent expects. @@ -162,7 +195,8 @@ public enum QuestionForm { return QuestionChoice( value: item["value"] ?? .string(label), label: label, - description: item["description"]?.stringValue + description: item["description"]?.stringValue, + recommended: flag(item["recommended"]) ) } } diff --git a/mobile/ios/Sources/CompanionCore/SessionState.swift b/mobile/ios/Sources/CompanionCore/SessionState.swift index 44dfe3c01..06cdcf319 100644 --- a/mobile/ios/Sources/CompanionCore/SessionState.swift +++ b/mobile/ios/Sources/CompanionCore/SessionState.swift @@ -4,12 +4,161 @@ public struct PermissionOption: Equatable, Sendable, Identifiable { public let id: String public let label: String public let kind: String + + public init(id: String, label: String, kind: String) { + self.id = id + self.label = label + self.kind = kind + } + + public var isAllow: Bool { + kind == "allow_once" || kind == "allow_always" || kind.hasPrefix("allow") + } + + public var isReject: Bool { + kind == "reject_once" || kind == "reject_always" || kind.hasPrefix("reject") || kind.hasPrefix("deny") + } +} + +public enum PermissionAllowScope: String, CaseIterable, Sendable { + case once + case session + case always + + public var label: String { + switch self { + case .once: return "允许一次" + case .session: return "本会话允许" + case .always: return "始终允许" + } + } +} + +public struct PermissionDiffPreview: Equatable, Sendable, Identifiable { + public var id: String { "\(path)-\(oldText.hashValue)-\(newText.hashValue)" } + public let path: String + public let oldText: String + public let newText: String + + public var isNewFile: Bool { oldText.isEmpty } + + public init(path: String, oldText: String, newText: String) { + self.path = path + self.oldText = oldText + self.newText = newText + } +} + +public enum PermissionCategory: String, Equatable, Sendable { + case terminal + case file + case web + case tool + + public var label: String { + switch self { + case .terminal: return "终端命令" + case .file: return "文件读写" + case .web: return "网络访问" + case .tool: return "工具调用" + } + } + + public var systemImage: String { + switch self { + case .terminal: return "terminal" + case .file: return "doc.text" + case .web: return "globe" + case .tool: return "wrench.and.screwdriver" + } + } + + public static func from(kind: String?) -> PermissionCategory { + let normalized = kind?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "" + if ["execute", "command", "terminal", "shell", "bash"].contains(where: { normalized.contains($0) }) { + return .terminal + } + if ["file", "read", "write", "edit", "delete", "move", "copy", "patch"].contains(where: { normalized.contains($0) }) { + return .file + } + if ["web", "browser", "fetch", "http", "url"].contains(where: { normalized.contains($0) }) { + return .web + } + return .tool + } } public struct PermissionPrompt: Equatable, Sendable, Identifiable { public let id: String public let title: String public let options: [PermissionOption] + public let kind: String? + public let heading: String? + public let subtitle: String? + public let command: String? + public let textBlocks: [String] + public let diffs: [PermissionDiffPreview] + public let locations: [String] + + public init( + id: String, + title: String, + options: [PermissionOption], + kind: String? = nil, + heading: String? = nil, + subtitle: String? = nil, + command: String? = nil, + textBlocks: [String] = [], + diffs: [PermissionDiffPreview] = [], + locations: [String] = [] + ) { + self.id = id + self.title = title + self.options = options + self.kind = kind + self.heading = heading + self.subtitle = subtitle + self.command = command + self.textBlocks = textBlocks + self.diffs = diffs + self.locations = locations + } + + public var category: PermissionCategory { + if kind != nil { + return PermissionCategory.from(kind: kind) + } + if command != nil { return .terminal } + if !diffs.isEmpty || !locations.isEmpty { return .file } + return .tool + } + + public var displayHeading: String { + if let heading, !heading.isEmpty { return heading } + return "需要权限确认" + } + + public var displaySubtitle: String? { + if let subtitle, !subtitle.isEmpty { return subtitle } + if heading == nil, !title.isEmpty, title != command { return title } + return nil + } + + public func resolveAllowOption(for scope: PermissionAllowScope) -> PermissionOption? { + let allowOnce = options.first { $0.kind == "allow_once" } + let allowAlways = options.first { $0.kind == "allow_always" } + let anyAllow = options.first { $0.isAllow } + if scope == .once { + return allowOnce ?? anyAllow + } + return allowAlways ?? allowOnce ?? anyAllow + } + + public var rejectOption: PermissionOption? { + options.first { $0.kind == "reject_once" } + ?? options.first { $0.kind == "reject_always" } + ?? options.first { $0.isReject } + } } /// A question the Agent is waiting on (`question_requested`), before it is turned into a form. @@ -136,23 +285,42 @@ public enum SessionStateBuilder { static func option(_ item: JSONValue) -> ConfigOption? { guard let key = item["key"]?.stringValue else { return nil } + let category = item["category"]?.stringValue let choices = (item["choices"]?.arrayValue ?? []).compactMap { choice -> ConfigChoice? in guard let value = choice["value"] else { return nil } + let rawLabel = choice["label"]?.stringValue ?? value.displayText ?? "" return ConfigChoice( value: value, - label: choice["label"]?.stringValue ?? value.displayText ?? "", + label: normalizedChoiceLabel(rawLabel, value: value, key: key, category: category), description: choice["description"]?.stringValue ) } return ConfigOption( key: key, label: item["label"]?.stringValue ?? key, - category: item["category"]?.stringValue, + category: category, value: item["value"], choices: choices ) } + private static func normalizedChoiceLabel( + _ rawLabel: String, + value: JSONValue, + key: String, + category: String? + ) -> String { + let trimmed = rawLabel.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return value.displayText ?? "" } + if category == "model" || key == "model", + let first = trimmed.first, first.isNumber, + let slug = value.stringValue?.lowercased(), slug.hasPrefix("gpt-") + { + return "GPT-\(trimmed)" + } + return trimmed + } + private static func pendingQuestion(_ payload: JSONValue) -> PendingQuestion? { guard let request = payload.eventField("request"), let id = request["question_id"]?.stringValue @@ -171,8 +339,8 @@ public enum SessionStateBuilder { guard let wrapper = payload.eventField("request"), let id = wrapper["permission_id"]?.stringValue else { return nil } - let request = wrapper["request"] - let options = (request?["options"]?.arrayValue ?? []).compactMap { item -> PermissionOption? in + let request = wrapper["request"] ?? wrapper + let options = (request["options"]?.arrayValue ?? []).compactMap { item -> PermissionOption? in guard let optionID = item["id"]?.stringValue else { return nil } return PermissionOption( id: optionID, @@ -180,6 +348,161 @@ public enum SessionStateBuilder { kind: item["kind"]?.stringValue ?? "unknown" ) } - return PermissionPrompt(id: id, title: request?["title"]?.stringValue ?? "权限请求", options: options) + let rawTitle = request["title"]?.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines) + let title = (rawTitle?.isEmpty == false ? rawTitle! : "权限请求") + let details = request["details"] ?? wrapper["details"] + let parsed = parsePermissionDetail(details, requestTitle: rawTitle) + return PermissionPrompt( + id: id, + title: title, + options: options, + kind: parsed.kind, + heading: parsed.heading, + subtitle: parsed.subtitle, + command: parsed.command, + textBlocks: parsed.textBlocks, + diffs: parsed.diffs, + locations: parsed.locations + ) + } + + private struct ParsedPermissionDetail { + var kind: String? + var heading: String? + var subtitle: String? + var command: String? + var textBlocks: [String] = [] + var diffs: [PermissionDiffPreview] = [] + var locations: [String] = [] + } + + private static func parsePermissionDetail(_ details: JSONValue?, requestTitle: String?) -> ParsedPermissionDetail { + let trimmedRequestTitle = (requestTitle?.isEmpty == false) ? requestTitle : nil + guard let record = details, case .object = record else { + return ParsedPermissionDetail(subtitle: trimmedRequestTitle) + } + let fields: JSONValue + if let inner = record["fields"], case .object = inner { + fields = inner + } else { + fields = record + } + let kind = fields["kind"]?.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines) + let rawInput = fields["rawInput"] ?? record["rawInput"] + let command = extractPermissionCommand(from: rawInput) + let (heading, subtitle) = resolvePermissionHeadings( + record: record, + fields: fields, + rawInput: rawInput, + requestTitle: trimmedRequestTitle, + command: command + ) + + var diffs: [PermissionDiffPreview] = [] + var textBlocks: [String] = [] + for block in fields["content"]?.arrayValue ?? [] { + if block["type"]?.stringValue == "diff" { + let path = block["path"]?.stringValue ?? "(file)" + let oldText = block["oldText"]?.stringValue ?? "" + let newText = block["newText"]?.stringValue ?? "" + diffs.append(PermissionDiffPreview(path: path, oldText: oldText, newText: newText)) + continue + } + if let text = (block["text"]?.stringValue ?? block["content"]?["text"]?.stringValue)? + .trimmingCharacters(in: .whitespacesAndNewlines), + !text.isEmpty + { + textBlocks.append(text) + } + } + + let locations = (fields["locations"]?.arrayValue ?? []).compactMap { loc -> String? in + guard let path = loc["path"]?.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines), + !path.isEmpty + else { return nil } + return path + } + + return ParsedPermissionDetail( + kind: kind, + heading: heading, + subtitle: subtitle, + command: (diffs.isEmpty && textBlocks.isEmpty) ? command : nil, + textBlocks: textBlocks, + diffs: diffs, + locations: locations + ) + } + + private static func extractPermissionCommand(from rawInput: JSONValue?) -> String? { + guard let rawInput else { return nil } + for key in ["command", "cmd", "script"] { + if let str = rawInput[key]?.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines), !str.isEmpty { + return str + } + if let arr = rawInput[key]?.arrayValue { + let joined = arr.compactMap(\.stringValue).joined(separator: " ").trimmingCharacters(in: .whitespacesAndNewlines) + if !joined.isEmpty { return joined } + } + } + return nil + } + + private static func extractShellCommandLabel(from rawInput: JSONValue?, command: String?) -> String? { + guard let rawInput else { return nil } + for key in ["description", "title", "summary"] { + if let label = rawInput[key]?.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines), + !label.isEmpty, + label != command + { + return label + } + } + return nil + } + + private static func resolvePermissionHeadings( + record: JSONValue, + fields: JSONValue, + rawInput: JSONValue?, + requestTitle: String?, + command: String? + ) -> (heading: String?, subtitle: String?) { + let meta = record["_meta"] ?? fields["_meta"] + let claudeCode = meta?["claudeCode"] + let air = meta?["jetbrains"]?["air"] + let permission = meta?["permission"] ?? air?["permission"] + + let claudeTitle = nonEmpty(claudeCode?["title"]?.stringValue) ?? nonEmpty(air?["commandTitle"]?.stringValue) + let permissionTitle = nonEmpty(permission?["title"]?.stringValue) + let metaHeadingRaw = claudeTitle ?? permissionTitle + + let metaHeading: String? + if let metaHeadingRaw, let command, metaHeadingRaw == command { + metaHeading = extractShellCommandLabel(from: rawInput, command: command) + } else { + metaHeading = metaHeadingRaw + } + + if let metaHeading { + return (metaHeading, nil) + } + + let toolCallTitle = nonEmpty(fields["title"]?.stringValue) ?? nonEmpty(record["title"]?.stringValue) + let fallbackCandidate = requestTitle ?? toolCallTitle + let subtitle: String? + if let fallbackCandidate, let command, fallbackCandidate == command { + subtitle = extractShellCommandLabel(from: rawInput, command: command) + } else { + subtitle = fallbackCandidate + } + return (nil, subtitle) + } + + private static func nonEmpty(_ text: String?) -> String? { + guard let trimmed = text?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty else { + return nil + } + return trimmed } } diff --git a/mobile/ios/Sources/CompanionCore/SettingsModels.swift b/mobile/ios/Sources/CompanionCore/SettingsModels.swift new file mode 100644 index 000000000..e92110bb5 --- /dev/null +++ b/mobile/ios/Sources/CompanionCore/SettingsModels.swift @@ -0,0 +1,288 @@ +import Foundation + +private struct DynamicCodingKey: CodingKey { + var stringValue: String + var intValue: Int? + + init(_ string: String) { + self.stringValue = string + self.intValue = nil + } + + init?(stringValue: String) { + self.stringValue = stringValue + self.intValue = nil + } + + init?(intValue: Int) { + self.stringValue = "\(intValue)" + self.intValue = intValue + } +} + +private extension KeyedDecodingContainer where Key == DynamicCodingKey { + func decodeString(forKeys keys: [String]) -> String? { + for key in keys { + if let value = try? decodeIfPresent(String.self, forKey: DynamicCodingKey(key)) { + return value + } + } + return nil + } + + func decodeBool(forKeys keys: [String]) -> Bool? { + for key in keys { + if let value = try? decodeIfPresent(Bool.self, forKey: DynamicCodingKey(key)) { + return value + } + } + return nil + } + + func decodeInt(forKeys keys: [String]) -> Int? { + for key in keys { + if let value = try? decodeIfPresent(Int.self, forKey: DynamicCodingKey(key)) { + return value + } + } + return nil + } +} + +// MARK: - Local Skills + +public struct LocalSkillItem: Codable, Equatable, Identifiable, Sendable { + public let id: String + public let name: String + public let description: String? + public let group: String + public let global: Bool + public let apps: [String] + public let path: String + + public init( + id: String, + name: String, + description: String? = nil, + group: String = "", + global: Bool = false, + apps: [String] = [], + path: String = "" + ) { + self.id = id + self.name = name + self.description = description + self.group = group + self.global = global + self.apps = apps + self.path = path + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: DynamicCodingKey.self) + self.id = c.decodeString(forKeys: ["id"]) ?? UUID().uuidString + self.name = c.decodeString(forKeys: ["name"]) ?? self.id + self.description = c.decodeString(forKeys: ["description"]) + self.group = c.decodeString(forKeys: ["group"]) ?? "" + self.global = c.decodeBool(forKeys: ["global"]) ?? false + self.apps = (try? c.decode([String].self, forKey: DynamicCodingKey("apps"))) ?? [] + self.path = c.decodeString(forKeys: ["path"]) ?? "" + } +} + +public struct LocalSkillContentItem: Codable, Equatable, Sendable { + public let id: String + public let path: String + public let content: String + + public init(id: String, path: String, content: String) { + self.id = id + self.path = path + self.content = content + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: DynamicCodingKey.self) + self.id = c.decodeString(forKeys: ["id"]) ?? "" + self.path = c.decodeString(forKeys: ["path"]) ?? "" + self.content = c.decodeString(forKeys: ["content"]) ?? "" + } +} + +// MARK: - Local MCP Servers + +public struct LocalMcpServerItem: Codable, Equatable, Identifiable, Sendable { + public let id: String + public let spec: JSONValue + public let global: Bool + public let apps: [String] + + public init( + id: String, + spec: JSONValue = .object([:]), + global: Bool = false, + apps: [String] = [] + ) { + self.id = id + self.spec = spec + self.global = global + self.apps = apps + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: DynamicCodingKey.self) + self.id = c.decodeString(forKeys: ["id"]) ?? UUID().uuidString + self.spec = (try? c.decode(JSONValue.self, forKey: DynamicCodingKey("spec"))) ?? .object([:]) + self.global = c.decodeBool(forKeys: ["global"]) ?? false + self.apps = (try? c.decode([String].self, forKey: DynamicCodingKey("apps"))) ?? [] + } + + public var transportLabel: String { + if let type = spec["type"]?.stringValue ?? spec["transport"]?.stringValue, !type.isEmpty { + return type.uppercased() + } + if spec["url"]?.stringValue != nil { + return "HTTP/SSE" + } + return "STDIO" + } + + public var commandSummary: String { + if let url = spec["url"]?.stringValue, !url.isEmpty { + return url + } + let cmd = spec["command"]?.stringValue ?? "" + let args = spec["args"]?.arrayValue?.compactMap(\.stringValue) ?? [] + let joined = ([cmd] + args).filter { !$0.isEmpty }.joined(separator: " ") + return joined.isEmpty ? "本地 MCP 服务" : joined + } +} + +// MARK: - Installed Plugins + +public struct PluginCatalogItem: Codable, Equatable, Identifiable, Sendable { + public let id: String + public let publisher: String? + public let name: String + public let version: String + public let description: String? + public let enabled: Bool + public let builtin: Bool + public let sourceKind: String + public let formats: [String] + public let skills: [String] + public let mcpCount: Int + public let mcpServers: [String] + + public init( + id: String, + publisher: String? = nil, + name: String, + version: String = "1.0.0", + description: String? = nil, + enabled: Bool = true, + builtin: Bool = false, + sourceKind: String = "builtin", + formats: [String] = [], + skills: [String] = [], + mcpCount: Int = 0, + mcpServers: [String] = [] + ) { + self.id = id + self.publisher = publisher + self.name = name + self.version = version + self.description = description + self.enabled = enabled + self.builtin = builtin + self.sourceKind = sourceKind + self.formats = formats + self.skills = skills + self.mcpCount = mcpCount + self.mcpServers = mcpServers + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: DynamicCodingKey.self) + self.id = c.decodeString(forKeys: ["id"]) ?? UUID().uuidString + self.publisher = c.decodeString(forKeys: ["publisher"]) + self.name = c.decodeString(forKeys: ["name"]) ?? self.id + self.version = c.decodeString(forKeys: ["version"]) ?? "1.0.0" + self.description = c.decodeString(forKeys: ["description"]) + self.enabled = c.decodeBool(forKeys: ["enabled"]) ?? true + self.builtin = c.decodeBool(forKeys: ["builtin"]) ?? false + self.sourceKind = c.decodeString(forKeys: ["sourceKind", "source_kind"]) ?? "builtin" + self.formats = (try? c.decode([String].self, forKey: DynamicCodingKey("formats"))) ?? [] + self.skills = (try? c.decode([String].self, forKey: DynamicCodingKey("skills"))) ?? [] + self.mcpCount = c.decodeInt(forKeys: ["mcpCount", "mcp_count"]) ?? 0 + self.mcpServers = + (try? c.decode([String].self, forKey: DynamicCodingKey("mcpServers"))) + ?? (try? c.decode([String].self, forKey: DynamicCodingKey("mcp_servers"))) + ?? [] + } +} + +public struct PluginControlCatalogResponse: Codable, Equatable, Sendable { + public let plugins: [PluginCatalogItem] + + public init(plugins: [PluginCatalogItem] = []) { + self.plugins = plugins + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: DynamicCodingKey.self) + self.plugins = (try? c.decode([PluginCatalogItem].self, forKey: DynamicCodingKey("plugins"))) ?? [] + } +} + +// MARK: - Host Environment & User System Info + +public struct HostSystemEnvironmentInfo: Codable, Equatable, Sendable { + public let osType: String + public let osVersion: String + public let osArchitecture: String + public let bitness: String + + public init( + osType: String = "macOS", + osVersion: String = "macOS", + osArchitecture: String = "aarch64", + bitness: String = "64-bit" + ) { + self.osType = osType + self.osVersion = osVersion + self.osArchitecture = osArchitecture + self.bitness = bitness + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: DynamicCodingKey.self) + self.osType = c.decodeString(forKeys: ["os_type", "osType"]) ?? "macOS" + self.osVersion = c.decodeString(forKeys: ["os_version", "osVersion"]) ?? "macOS" + self.osArchitecture = c.decodeString(forKeys: ["os_architecture", "osArchitecture"]) ?? "aarch64" + self.bitness = c.decodeString(forKeys: ["bitness"]) ?? "64-bit" + } +} + +public struct HostUserSystemInfo: Codable, Equatable, Sendable { + public let environment: HostSystemEnvironmentInfo + public let plugins: [PluginCatalogItem] + + public init( + environment: HostSystemEnvironmentInfo = HostSystemEnvironmentInfo(), + plugins: [PluginCatalogItem] = [] + ) { + self.environment = environment + self.plugins = plugins + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: DynamicCodingKey.self) + self.environment = + (try? c.decode(HostSystemEnvironmentInfo.self, forKey: DynamicCodingKey("environment"))) + ?? HostSystemEnvironmentInfo() + self.plugins = + (try? c.decode([PluginCatalogItem].self, forKey: DynamicCodingKey("plugins"))) + ?? [] + } +} diff --git a/mobile/ios/Tests/CompanionCoreTests/HostClientTests.swift b/mobile/ios/Tests/CompanionCoreTests/HostClientTests.swift index f4906e16d..bc2f32b21 100644 --- a/mobile/ios/Tests/CompanionCoreTests/HostClientTests.swift +++ b/mobile/ios/Tests/CompanionCoreTests/HostClientTests.swift @@ -147,19 +147,39 @@ private func client(_ status: Int, _ body: String) throws -> HostClient { } let raw = "[" + [ item("1", "W1", "2026-11-06T10:00:00Z"), - item("2", "W2", "2026-11-06T12:00:00Z"), item("3", "W1", "2026-11-06T11:00:00Z"), item("4", "ZZ", "2026-11-06T13:00:00Z"), ].joined(separator: ",") + "]" let conversations = try JSONDecoder().decode([ConversationListItem].self, from: Data(raw.utf8)) let projects = [ - ProjectSummary(id: "p1", name: "webhub", workspaceIds: ["w1"]), - ProjectSummary(id: "p2", name: "测试 hub", workspaceIds: ["W2"]), + ProjectSummary( + id: "p_parent", + name: "键盘驱动", + rootPath: "/Users/ltf/Desktop/键盘驱动", + workspaceIds: ["w1"] + ), + ProjectSummary( + id: "p_child", + name: "webhub", + rootPath: "/Users/ltf/Desktop/键盘驱动/webhub", + parentProjectId: "p_parent", + isGit: true, + workspaceIds: ["W2"] + ), + ProjectSummary( + id: "p_home", + name: "Global", + rootPath: "/Users/ltf", + isHome: true, + workspaceIds: ["W0"] + ), ] let groups = ProjectGroup.make(conversations: conversations, projects: projects) - #expect(groups.map(\.name) == ["测试 hub", "webhub", "其他"]) + #expect(groups.map(\.name) == ["全局", "键盘驱动", "webhub", "其他"]) + #expect(groups.map(\.depth) == [0, 0, 1, 0]) #expect(groups[1].conversations.map(\.id) == ["1", "3"]) - #expect(groups[2].conversations.map(\.id) == ["4"]) + #expect(groups[2].conversations.isEmpty && groups[2].isGit) + #expect(groups[3].conversations.map(\.id) == ["4"]) } @Test func sessionStateFoldsModesOptionsAndPendingPermission() throws { @@ -242,6 +262,12 @@ private final class RecordingTransport: HttpTransport, @unchecked Sendable { try await host.setSessionConfigOption(conversationID: "c", key: "model", value: .string("b")) #expect((transport.lastBody["args"] as? [String: Any])?["value"] as? String == "b") + + try await host.archiveConversation(conversationID: "c1") + #expect((transport.lastBody["args"] as? [String: Any])?["conversationId"] as? String == "c1") + + try await host.deleteConversation(conversationID: "c2") + #expect((transport.lastBody["args"] as? [String: Any])?["conversationId"] as? String == "c2") } @Test func catalogListsDesktopAgentsWithTheirModels() throws { @@ -415,3 +441,183 @@ private final class RecordingTransport: HttpTransport, @unchecked Sendable { #expect(item.changes.map(\.path) == ["a.rs"] && item.changes[0].additions == 3) #expect(item.tools[0].detail == ["a.rs", "line2", "line3", "line4"]) } + +@Test func collaborationSidebarAndMessagesDecodeCleanly() throws { + let sidebarJson = """ + [{"kind":"group","thread_id":"s1","space_id":"s1","name":"核心研发群","member_count":3,"unread_count":2, + "members_preview":[{"member_id":"m1","name":"架构师","is_supervisor":true}], + "last_message":{"seq":12,"preview":"已评审完成","origin":"agent","created_at":"2026-04-20T10:00:00Z"}}] + """ + let sidebar = try JSONDecoder().decode([CollabSidebarItem].self, from: Data(sidebarJson.utf8)) + #expect(sidebar.count == 1) + #expect(sidebar[0].isGroup == true) + #expect(sidebar[0].displayName == "核心研发群") + #expect(sidebar[0].unreadCount == 2) + #expect(sidebar[0].membersPreview.first?.isSupervisor == true) + #expect(sidebar[0].lastMessage?.preview == "已评审完成") + + let pageJson = """ + {"messages":[ + {"id":"vibex://space-message/m-1","seq":1,"origin":"agent", + "receipts":[{"conversation_id":"conv-1","nickname":"架构师","state":"replied"}], + "envelope":{"id":"m-1","sender":"架构师","content":"请确认部署方案","to":["@全体成员"], + "reactions":[{"emoji":"👍","actor":"Person"}]}} + ], + "cards":[ + {"id":"c1","kind":"approval","status":"pending","payload":{"action":"执行迁移","reason":"更新 schema","options":["批准","拒绝"]}} + ], + "scheduled":[ + {"id":"sch1","space_id":"s1","content":"稍后提醒","deliver_at":"2026-04-20T10:05:00Z"} + ]} + """ + let page = try JSONDecoder().decode(CollabMessagesPage.self, from: Data(pageJson.utf8)) + #expect(page.messages.count == 1) + #expect(page.messages[0].id == "m-1") + #expect(page.messages[0].envelope.displaySender == "架构师") + #expect(page.messages[0].receipts.first?.stateLabel == "已回复") + #expect(page.messages[0].groupedReactions.first?.emoji == "👍") + #expect(page.messages[0].groupedReactions.first?.byUser == true) + #expect(page.cards.first?.isPending == true) + #expect(page.cards.first?.action == "执行迁移") + #expect(page.scheduled.first?.content == "稍后提醒") + + let masterAvatar = CollabBotAvatarConfig.derive(seed: "Master") + #expect(masterAvatar.color == "#000000") + #expect(masterAvatar.shape == .circle) + + let customAvatar = CollabBotAvatarConfig.resolve( + rawAvatar: "{\"color\":\"#9a6433\",\"shape\":\"cloud\",\"expression\":\"happy\"}", + rawColor: nil, + fallbackSeed: "架构师" + ) + #expect(customAvatar.color == "#9a6433") + #expect(customAvatar.shape == .cloud) + #expect(customAvatar.expression == .happy) + #expect(BotAvatarShape.allCases.count == 13) + #expect(CollabBotAvatarConfig.colorPresets.count == 11) +} + +@Test func kanbanSessionSummariesAndUsageStatisticsDecodeCleanly() throws { + let summaryJson = """ + [{"id":"s-1","workspace_id":"ws-1","name":null,"display_name":"新会话1","status":"inreview", + "executor":"claude_code","agent_id":"claude_code","workspace_name":"main","workspace_branch":"main", + "created_at":"2026-04-20T09:00:00Z","updated_at":"2026-04-20T10:00:00Z", + "first_prompt":"实现 iOS 看板功能","is_running":false,"pinned_at":"2026-04-20T09:30:00Z", + "model":"claude-opus-4-7","collaboration":{"member_id":"m1","member_name":"Master"}}] + """ + let summaries = try JSONDecoder().decode([KanbanSessionSummary].self, from: Data(summaryJson.utf8)) + #expect(summaries.count == 1) + let first = summaries[0] + #expect(first.status == .inreview) + #expect(first.isPinned == true) + #expect(first.completesWhenViewed == true) + #expect(first.resolvedTitle == "实现 iOS 看板功能") + #expect(first.agentDisplayName == "Claude Code") + #expect(first.workspaceDisplayLabel == "main") + #expect(first.collaboration?.memberName == "Master") + #expect(first.isForkSupported == true) + + let statsJson = """ + {"scope":"global","project_id":"global","project_name":"全局","total_sessions":4, + "total_tokens":{"protocol":{"input_tokens":1000,"output_tokens":500,"cache_write_tokens":200,"cache_read_tokens":8300,"total_tokens":10000},"vendor_log":null,"sources_disagree":false}, + "estimated_cost":1.25, + "sessions":[{"session_id":"s-1","workspace_id":"ws-1","agent_id":"claude_code","timestamp":1776679200000,"model":"claude-opus-4-7","tokens":{"protocol":{"total_tokens":10000},"sources_disagree":false},"cost":1.25,"summary":"实现看板","turns":3}], + "daily_usage":[{"date":"2026-04-20","sessions":4,"tokens":{"protocol":{"total_tokens":10000},"sources_disagree":false},"cost":1.25,"models_used":["claude-opus-4-7"],"turns":3}], + "by_model":[{"model":"claude-opus-4-7","session_count":4,"tokens":{"protocol":{"total_tokens":10000},"sources_disagree":false},"cost":1.25}], + "by_folder":[{"workspace_id":"ws-1","folder":"/Users/ltf/Desktop/vibex","session_count":4,"tokens":{"protocol":{"total_tokens":10000},"sources_disagree":false},"cost":1.25}], + "by_agent":[{"agent_id":"claude_code","session_count":4,"tokens":{"protocol":{"total_tokens":10000},"sources_disagree":false},"cost":1.25}], + "unattributed_vendor_sessions":0,"last_updated":1776679200000} + """ + let stats = try JSONDecoder().decode(ProjectUsageStatistics.self, from: Data(statsJson.utf8)) + #expect(stats.totalSessions == 4) + #expect(stats.resolvedCost == 1.25) + #expect(stats.totalTokens.preferred.resolvedTotal == 10000) + #expect(stats.activeDaysCount == 1) + #expect(stats.byFolder.first?.displayName == "vibex") + #expect(stats.byAgent.first?.displayName == "Claude Code") + + let planJson = """ + {"type":"OK","usage":{"planType":"max","windows":[{"id":"five_hour","usedPercent":42.4,"windowMinutes":300,"resetsAtMs":1776686400000}],"credits":{"balance":"$20.00","unlimited":false}}} + """ + let plan = try JSONDecoder().decode(PlanUsageResponse.self, from: Data(planJson.utf8)) + if case .ok(let usage) = plan { + #expect(usage.planType == "max") + #expect(usage.windows.first?.localizedTitle == "5 小时窗口") + #expect(usage.windows.first?.clampedUsedPercent == 42) + #expect(usage.windows.first?.remainingPercent == 58) + } else { + Issue.record("Expected .ok PlanUsageResponse") + } +} + +@Test func settingsSkillsMcpAndPluginsModelsDecodeCleanly() throws { + let skillsJson = """ + [{"id":"maiden-skill","name":"maiden-skill","description":"Project-wide engineering principles","group":"maiden","global":true,"apps":["claude_code","codex"],"path":"/Users/ltf/.agents/skills/maiden-skill/SKILL.md"}] + """ + let skills = try JSONDecoder().decode([LocalSkillItem].self, from: Data(skillsJson.utf8)) + #expect(skills.count == 1) + #expect(skills[0].name == "maiden-skill") + #expect(skills[0].global == true) + #expect(skills[0].apps == ["claude_code", "codex"]) + + let mcpJson = """ + [{"id":"vibex-delegation-mcp","spec":{"command":"vibex-mcp","args":["--stdio"],"type":"stdio"},"global":true,"apps":["claude_code"]}] + """ + let mcpServers = try JSONDecoder().decode([LocalMcpServerItem].self, from: Data(mcpJson.utf8)) + #expect(mcpServers.count == 1) + #expect(mcpServers[0].transportLabel == "STDIO") + #expect(mcpServers[0].commandSummary == "vibex-mcp --stdio") + + let catalogJson = """ + {"plugins":[{"id":"vibex.core.multi-agent","name":"Multi-Agent Collaboration","version":"0.4.2","description":"Collaboration Space","enabled":true,"builtin":true,"sourceKind":"builtin","formats":["vibex"],"skills":["collab"],"mcpCount":1,"mcpServers":["delegation"]}]} + """ + let catalog = try JSONDecoder().decode(PluginControlCatalogResponse.self, from: Data(catalogJson.utf8)) + #expect(catalog.plugins.count == 1) + #expect(catalog.plugins[0].name == "Multi-Agent Collaboration") + #expect(catalog.plugins[0].mcpCount == 1) +} + +@Test func permissionDetailsAndQuestionRecommendationsMatchDesktop() throws { + let eventJson = """ + {"sequence":1,"kind":"permission_requested","payload":{"request":{ + "permission_id":"perm-42", + "request":{ + "title":"pnpm test", + "options":[ + {"id":"opt-once","label":"Allow once","kind":"allow_once"}, + {"id":"opt-always","label":"Always allow","kind":"allow_always"}, + {"id":"opt-reject","label":"Reject","kind":"reject_once"} + ], + "details":{ + "kind":"execute", + "_meta":{"claudeCode":{"title":"Run test suite"}}, + "rawInput":{"command":"pnpm test","description":"Execute Vitest unit tests"}, + "locations":[{"path":"frontend/src/App.tsx"}] + } + } + }}} + """ + let event = try JSONDecoder().decode(RemoteEvent.self, from: Data(eventJson.utf8)) + let state = SessionStateBuilder.build(from: [event]) + let prompt = try #require(state.pendingPermissions.first) + #expect(prompt.id == "perm-42") + #expect(prompt.category == .terminal) + #expect(prompt.displayHeading == "Run test suite") + #expect(prompt.command == "pnpm test") + #expect(prompt.locations == ["frontend/src/App.tsx"]) + #expect(prompt.resolveAllowOption(for: .once)?.id == "opt-once") + #expect(prompt.resolveAllowOption(for: .always)?.id == "opt-always") + #expect(prompt.rejectOption?.id == "opt-reject") + + let recommendedChoice = QuestionChoice( + value: .string("vitest"), + label: "(Recommended) Use Vitest runner", + description: "Fast unit test execution" + ) + #expect(recommendedChoice.recommended == true) + #expect(recommendedChoice.label == "Use Vitest runner") +} + + + + diff --git a/mobile/ios/VibeXCompanion.xcodeproj/project.pbxproj b/mobile/ios/VibeXCompanion.xcodeproj/project.pbxproj index 4b3641e52..2ddbe67a6 100644 --- a/mobile/ios/VibeXCompanion.xcodeproj/project.pbxproj +++ b/mobile/ios/VibeXCompanion.xcodeproj/project.pbxproj @@ -257,9 +257,11 @@ A10000000000000000000014 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = DD67H4228U; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = Info.plist; INFOPLIST_KEY_CFBundleDisplayName = VibeX; @@ -279,9 +281,11 @@ A10000000000000000000015 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = DD67H4228U; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = Info.plist; INFOPLIST_KEY_CFBundleDisplayName = VibeX; @@ -304,6 +308,7 @@ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = DD67H4228U; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = TaskWidgetInfo.plist; INFOPLIST_KEY_CFBundleDisplayName = "VibeX 任务"; @@ -328,6 +333,7 @@ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = DD67H4228U; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = TaskWidgetInfo.plist; INFOPLIST_KEY_CFBundleDisplayName = "VibeX 任务"; diff --git a/mobile/ios/VibeXCompanion.xcodeproj/xcshareddata/xcschemes/VibeXCompanion.xcscheme b/mobile/ios/VibeXCompanion.xcodeproj/xcshareddata/xcschemes/VibeXCompanion.xcscheme new file mode 100644 index 000000000..92c1c27bc --- /dev/null +++ b/mobile/ios/VibeXCompanion.xcodeproj/xcshareddata/xcschemes/VibeXCompanion.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/computer-use/native/Cargo.lock b/plugins/computer-use/native/Cargo.lock index 086d7719f..d23f68f10 100644 --- a/plugins/computer-use/native/Cargo.lock +++ b/plugins/computer-use/native/Cargo.lock @@ -159,6 +159,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -1161,8 +1170,39 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags", + "block2", + "libc", "objc2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-foundation", "objc2-core-graphics", + "objc2-core-image", + "objc2-core-text", + "objc2-core-video", + "objc2-foundation", + "objc2-quartz-core", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "bitflags", + "objc2", "objc2-foundation", ] @@ -1190,6 +1230,41 @@ dependencies = [ "objc2-io-surface", ] +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", +] + [[package]] name = "objc2-encode" version = "4.1.0" @@ -1203,6 +1278,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags", + "block2", + "libc", "objc2", "objc2-core-foundation", ] @@ -1218,6 +1295,17 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags", + "objc2", + "objc2-foundation", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -2135,12 +2223,16 @@ dependencies = [ "axum", "base64 0.22.1", "core-foundation", + "core-foundation-sys", "core-graphics", "dirs", "flate2", "futures-util", "image", "libc", + "objc2", + "objc2-app-kit", + "objc2-foundation", "reqwest", "serde", "serde_json", diff --git a/plugins/computer-use/native/Cargo.toml b/plugins/computer-use/native/Cargo.toml index 86d419271..fab53e9ef 100644 --- a/plugins/computer-use/native/Cargo.toml +++ b/plugins/computer-use/native/Cargo.toml @@ -5,6 +5,8 @@ edition = "2021" description = "VibeX Computer Use Helper & Daemon" license = "MIT" +[workspace] + [[bin]] name = "vibex-computer-helper" path = "src/main.rs" @@ -38,7 +40,11 @@ axum = "0.8" [target.'cfg(target_os = "macos")'.dependencies] core-foundation = "0.10" +core-foundation-sys = "0.8" core-graphics = "0.24" +objc2 = "0.6" +objc2-app-kit = { version = "0.3", features = ["NSPasteboard", "NSPasteboardItem"] } +objc2-foundation = { version = "0.3", features = ["NSArray", "NSString"] } [target.'cfg(target_os = "windows")'.dependencies] windows-sys = { version = "0.59", features = [ diff --git a/plugins/computer-use/runtime/daemon-client.mjs b/plugins/computer-use/runtime/daemon-client.mjs index 1a363ed5d..6cc9a10ad 100644 --- a/plugins/computer-use/runtime/daemon-client.mjs +++ b/plugins/computer-use/runtime/daemon-client.mjs @@ -1,4 +1,4 @@ -import { spawn } from 'node:child_process'; +import { spawn, spawnSync } from 'node:child_process'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; @@ -56,12 +56,16 @@ export function resolveHelperBinary(pluginRoot = resolvePluginRoot()) { process.platform === 'win32' ? 'vibex-computer-helper.exe' : 'vibex-computer-helper'; + const repoRootFromSnapshot = path.resolve(pluginRoot, '..', '..', '..', '..', '..'); const candidates = [ path.join(pluginRoot, 'bin', exeName), path.join(pluginRoot, 'native', 'target', 'release', exeName), path.join(pluginRoot, 'native', 'target', 'debug', exeName), path.join(pluginRoot, '.git', 'cargo-target', 'release', exeName), path.join(pluginRoot, '.git', 'cargo-target', 'debug', exeName), + path.join(repoRootFromSnapshot, 'plugins', 'computer-use', 'bin', exeName), + path.join(repoRootFromSnapshot, 'plugins', 'computer-use', 'native', 'target', 'release', exeName), + path.join(repoRootFromSnapshot, 'plugins', 'computer-use', 'native', 'target', 'debug', exeName), path.join( pluginRoot, '..', @@ -171,7 +175,38 @@ export async function ensureDaemon(envOrCtx) { spawningPromise = (async () => { try { - const bin = resolveHelperBinary(pluginRoot); + let bin = resolveHelperBinary(pluginRoot); + if (!fs.existsSync(bin)) { + const repoRootFromSnapshot = path.resolve( + pluginRoot, + '..', + '..', + '..', + '..', + '..' + ); + const manifestCandidates = [ + path.join(pluginRoot, 'native', 'Cargo.toml'), + path.join( + repoRootFromSnapshot, + 'plugins', + 'computer-use', + 'native', + 'Cargo.toml' + ), + ]; + const manifestPath = manifestCandidates.find((candidate) => + fs.existsSync(candidate) + ); + if (manifestPath) { + spawnSync( + 'cargo', + ['build', '--release', '--manifest-path', manifestPath], + { stdio: 'ignore' } + ); + bin = resolveHelperBinary(pluginRoot); + } + } if (!fs.existsSync(bin)) { throw new Error(`Computer helper binary not found at ${bin}`); } diff --git a/plugins/computer-use/src/views/view.tsx b/plugins/computer-use/src/views/view.tsx index 819543151..f4c337ed3 100644 --- a/plugins/computer-use/src/views/view.tsx +++ b/plugins/computer-use/src/views/view.tsx @@ -2955,7 +2955,14 @@ export default function ComputerUseSettingsView({ [savedSettings, draft] ); - const platform: 'macos' | 'windows' | 'linux' = status?.platform ?? 'windows'; + const detectedClientPlatform: 'macos' | 'windows' | 'linux' = + typeof navigator !== 'undefined' && /Mac|iPhone|iPad/i.test(navigator.userAgent || navigator.platform || '') + ? 'macos' + : typeof navigator !== 'undefined' && /Linux/i.test(navigator.userAgent || navigator.platform || '') + ? 'linux' + : 'windows'; + const platform: 'macos' | 'windows' | 'linux' = + status?.platform ?? detectedClientPlatform; // Stop shortcut key recorder (matches StopShortcut::parse canonical spelling) useEffect(() => { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bbceebb8e..24f3d5e99 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -511,25 +511,6 @@ importers: plugins/office: {} - plugins/open-connector: - dependencies: - '@vibex/plugin-sdk': - specifier: ^1.0.0 - version: link:../../packages/plugin-sdk - react: - specifier: ^19.2.8 - version: 19.2.8 - react-dom: - specifier: ^19.2.8 - version: 19.2.8(react@19.2.8) - devDependencies: - '@module-federation/vite': - specifier: ^1.9.0 - version: 1.21.3(typescript@5.9.2)(vite@8.3.6(@types/node@26.1.2)(jiti@2.7.0)(yaml@2.8.0)) - vite: - specifier: '>=6.4.4' - version: 8.3.6(@types/node@26.1.2)(esbuild@0.25.5)(jiti@2.7.0)(yaml@2.8.0) - plugins/plugin-development: {} plugins/prompt-enhancer: @@ -560,6 +541,12 @@ importers: specifier: workspace:* version: link:../../packages/plugin-sdk + plugins/voice-input: + dependencies: + '@vibex/plugin-sdk': + specifier: ^2.0.0 + version: link:../../packages/plugin-sdk + plugins/workflow-creator: dependencies: '@modelcontextprotocol/server': @@ -6276,18 +6263,6 @@ snapshots: - utf-8-validate - vue-tsc - '@module-federation/vite@1.21.3(typescript@5.9.2)(vite@8.3.6(@types/node@26.1.2)(jiti@2.7.0)(yaml@2.8.0))': - dependencies: - '@module-federation/dts-plugin': 2.9.0(typescript@5.9.2) - '@module-federation/runtime': 2.9.0 - '@module-federation/sdk': 2.9.0 - vite: 8.3.6(@types/node@26.1.2)(jiti@2.7.0)(yaml@2.8.0) - transitivePeerDependencies: - - bufferutil - - typescript - - utf-8-validate - - vue-tsc - '@monaco-editor/loader@1.7.0': dependencies: state-local: 1.0.7 @@ -9510,19 +9485,6 @@ snapshots: jiti: 2.7.0 yaml: 2.8.0 - vite@8.3.6(@types/node@26.1.2)(jiti@2.7.0)(yaml@2.8.0): - dependencies: - lightningcss: 1.33.0 - picomatch: 4.0.7 - postcss: 8.5.28 - rolldown: 1.2.16 - tinyglobby: 0.2.17 - optionalDependencies: - '@types/node': 26.1.2 - fsevents: 2.3.3 - jiti: 2.7.0 - yaml: 2.8.0 - vitest@2.1.9(@types/node@22.20.5)(happy-dom@21.0.4)(jsdom@28.1.0)(lightningcss@1.33.0): dependencies: '@vitest/expect': 2.1.9 diff --git a/src-tauri/src/events.rs b/src-tauri/src/events.rs index 07f6c8d1b..a5655efc2 100644 --- a/src-tauri/src/events.rs +++ b/src-tauri/src/events.rs @@ -622,7 +622,11 @@ async fn handle_recorded_conversation_batch( } fn is_local_user_turn_origin(origin: &str) -> bool { - origin == conversations::commit_reminder::LOCAL_USER_ORIGIN + matches!( + origin, + conversations::commit_reminder::LOCAL_USER_ORIGIN + | conversations::commit_reminder::USER_ORIGIN + ) } fn attention_from_event(