Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat: add workspaces, attachments and connector credentials
leepokai4dbe19774ce6
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0cef44b6..0610c727 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -17,7 +17,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess- Clients: iOS app, native Mac window (menu bar app), native Linux app (`apps/linux/`, GTK 4 + libadwaita in Rust), terminal UI (`codync-host tui`, `host/src/tui/`, ratatui; layout and state vocabulary modeled on herdr). All talk to the host API; no web UI.- Shared Swift (`kit/`): `CodyncKit` (models, client, theme, avatars) + `CodyncUI` (`BotStore` + chat screens) used by iOS and macOS. Platform specifics go through `BotStore` hooks or `Platform.swift`.- UI principle: buttons an icon can express are icon-only (with tooltip / accessibility label); text only where an icon would be ambiguous (approval choices).-- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. The macOS menu bar also uses native `MenuBarExtra(.menu)`, menus, pickers and toggles. Keep system authentication and widget containers native. Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.+- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. On iOS, `DropdownMenu`/`ChoicePicker` open the native `Menu` (the custom overlay mis-anchors inside sheets). The macOS menu bar also uses native `MenuBarExtra(.menu)`, menus, pickers and toggles. Keep system authentication and widget containers native. Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.- `host/` — **codync-host** (Rust, macOS + Linux). Detects installed harnesses (`agent/backends.rs`: login-shell PATH + known dirs) and the ACP registry (`agent/registry.rs`, cached in `~/.codync/registry.json`, binaries under `~/.codync/agents`). Drives agents over **ACP** (JSON-RPC on stdio, hand-rolled in `agent/acp.rs`, updates kept as `serde_json::Value` so new adapter variants never break parsing). One actor per bot (`agent/bot.rs`) owns the agent process + session and maps `session/update` onto transcript entries.- **Chat ≠ session**: a bot is one endless transcript (SQLite `entries`, ordered by `seq`); the ACP session underneath is resumed with `session/load` or replaced by *New session*.- **Group chats and threads** are host features every client drives through the same methods (`send` with `threadId`, `thread`, `createBot {kind: group}`); clients never route, parse mentions or count replies themselves. A group is a roster row whose members answer in their own sessions (Grok Bot's room turns); a thread on a bot's message is a forked session: [docs/features/groups-and-threads.md](docs/features/groups-and-threads.md).@@ -31,7 +31,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess- Multiple computers per account are future work, not a current priority: the product targets one computer. The multi-computer structure (`AccountStore`, `BotReference`) stays because relay/accounts/SSH build on it; don't extend or polish multi-computer features unless asked.- Environments: **dev** (`dev-api.codync.dev`, Clerk development instance, Debug builds) and **main** (`api.codync.dev`, Clerk production, Release builds); `apps/shared/Config/<env>.plist` becomes `AccountConfig.plist`. Details: [spec §14.0](docs/reference/remote-relay.md).- Push: iOS registers its APNs token with `relay/` → gets an AES-GCM ticket → gives it (plus its X25519 push key) to the host; the host seals title/body to that key and a Notification Service Extension opens it, so `relay/` sees only generic text. Alert kinds: *needs you*, *done*, and *failed*, suppressed while the iOS app is connected. Delivery and lifecycle: [notification design](docs/design/push-and-live-activity.md).-- Voice call (iPhone): on-device speech in, bot's final replies read aloud; the host sees plain messages. Pro cloud-realtime plan: [docs/features/voice-call.md](docs/features/voice-call.md).+- Voice call (iPhone): on-device speech in, bot's final replies read aloud; the host sees plain messages. Grok-style call bar; bring-your-own-key realtime design: [docs/features/voice-call.md](docs/features/voice-call.md).- Usage: local only — `claude -p /usage --no-session-persistence`, the Claude status line (`codync-host statusline`, wrapping any existing one), Claude ACP `usage_update` rate-limit meta, Codex rollout files. Never call provider APIs with agent credentials.- macOS app is thin: embeds `codync-host` in `Contents/MacOS` (Xcode post-build script runs cargo), installs it as a launchd agent via `codync-host install`; menu bar shows status/pairing/usage and opens the native chat window (NavigationSplitView over `CodyncUI`). Not sandboxed, not Mac App Store (the host must spawn CLIs).diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swiftindex fd8b598a..13de8824 100644--- a/apps/ios/App/CodyncApp.swift+++ b/apps/ios/App/CodyncApp.swift@@ -36,7 +36,9 @@ struct CodyncApp: App {}.onOpenURL { url in app.open(url) }.onChange(of: scenePhase, initial: true) { _, phase in- app.accounts.setActive(phase == .active)+ // Only leaving for the background disconnects; `.inactive` (Control Center,+ // app switcher, system prompts) comes and goes too often to drop the link.+ app.accounts.setActive(phase != .background)// Back in the app: a computer may have joined the account meanwhile.if phase == .active { Task { await app.accounts.refreshCloud() } }}diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swiftindex 5028cdd3..cab6f0c7 100644--- a/apps/ios/Views/BotListView.swift+++ b/apps/ios/Views/BotListView.swift@@ -6,104 +6,69 @@ import SwiftUIstruct BotListView: View {@Environment(AppStore.self) private var app@Environment(AccountStore.self) private var accounts- @State private var connectingComputer: CloudComputer?@State private var editing: EditTarget?@State private var editingGroup: GroupTarget?- @State private var pickingComputer = false@State private var confirmDelete: RosterItem?+ /// The computer section a dragged heading is over.+ @State private var dropTarget: ComputerID?+ @Environment(\.accessibilityReduceMotion) private var reduceMotion/// Computers left out of the list on this device, comma-separated IDs.@AppStorage("hiddenComputers") private var hiddenComputers = ""- private var hidden: Set<ComputerID> { Set(hiddenComputers.split(separator: ",").map(String.init)) }+ private var shownIDs: Set<ComputerID> {+ Set(ComputerSelection(all: accounts.computers.map(\.id), hidden: hiddenComputers).shown)+ }++ private var shownStores: [BotStore] {+ accounts.computers.filter { shownIDs.contains($0.id) }.compactMap { accounts.store(for: $0.id) }+ }- /// More than one computer: the list groups bots under their computer and the header filters.- private var grouped: Bool { accounts.computers.count > 1 }+ /// One computer shows a flat list; more get a heading each.+ private var grouped: Bool { shownStores.count > 1 }- /// The computers the list shows (all of them when the filter would leave none).- private var shownComputers: [Computer] {- let shown = accounts.computers.filter { !hidden.contains($0.id) }- return shown.isEmpty ? accounts.computers : shown+ /// Moves a computer one place up (-1) or down (+1) among the shown ones.+ private func move(_ id: ComputerID, _ offset: Int) {+ let ids = shownStores.map(\.computer.id)+ guard let i = ids.firstIndex(of: id), ids.indices.contains(i + offset) else { return }+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { accounts.move(id, to: ids[i + offset]) }}/// Computers that can take a new bot right now.private var onlineStores: [BotStore] {- accounts.computers.compactMap { accounts.store(for: $0.id) }.filter { $0.connection == .online }+ accounts.computers.compactMap { accounts.store(for: $0.id) }+ .filter { shownIDs.contains($0.computer.id) && $0.connection == .online }}var body: some View {- let roster = accounts.roster+ let roster = accounts.roster.filter { shownIDs.contains($0.ref.computerId) }ScrollView {LazyVStack(spacing: 0) {- // Keep actionable offline warnings; transient connecting state lives in the header.- ForEach(shownComputers) { computer in- // Connecting draws nothing here (the header shows it), so it takes no space either.- if let store = accounts.store(for: computer.id), ![.online, .connecting, .unpaired].contains(store.connection) {- ConnectionBanner()- .environment(store)- .padding(.vertical, 4)- }- }-- if !accountComputers.isEmpty {- VStack(alignment: .leading, spacing: 12) {- Text("Connect from your account")- .font(.title3.weight(.semibold))- .foregroundStyle(Palette.text)- Text("Connect once to see all the bots on your computer. No QR code needed.")- .font(.subheadline)- .foregroundStyle(Palette.secondary)- ForEach(accountComputers) { computer in- Button {- withAnimation(Motion.layout) {- if computer.access == "granted" {- app.showComputers = true- } else {- connectingComputer = computer- }- }- } label: {- HStack(spacing: 12) {- Image(systemName: "desktopcomputer")- .font(.title2)- VStack(alignment: .leading, spacing: 4) {- Text(computer.name).font(.headline)- Text(computer.isOnline ? "Online" : "Offline · Turn on your computer to connect")- .font(.subheadline)- .foregroundStyle(Palette.secondary)- }- Spacer()- Text(computer.access == "granted" ? "Manage" : "Connect")- .font(.subheadline.weight(.semibold))- }- .foregroundStyle(Palette.text)- .padding(16)- .frame(maxWidth: .infinity, alignment: .leading)- .background(Palette.surface, in: RoundedRectangle(cornerRadius: 16))- }- .buttonStyle(PressScale())- }- }- .padding(.vertical, 16)- }-- if roster.isEmpty && accountComputers.isEmpty {+ if roster.isEmpty {EmptyRoster(canCreate: !onlineStores.isEmpty, hasComputer: !accounts.computers.isEmpty,create: newBot, showComputers: { app.showComputers = true })}if grouped {- ForEach(shownComputers) { computer in- if let store = accounts.store(for: computer.id) {- ComputerSection(store: store)- ForEach(roster.filter { $0.ref.computerId == computer.id }) { item in- row(item, store: store, caption: false)- }+ // A light heading per computer, in the order the user dragged them into.+ ForEach(shownStores, id: \.computer.id) { store in+ let id = store.computer.id+ VStack(spacing: 0) {+ ComputerSection(store: store, empty: !roster.contains { $0.ref.computerId == id },+ targeted: dropTarget == id, move: move)+ ForEach(roster.filter { $0.ref.computerId == id }) { row($0, store: store) }+ }+ .dropDestination(for: String.self) { ids, _ in+ guard let dragged = ids.first else { return false }+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { accounts.move(dragged, to: id) }+ return true+ } isTargeted: { on in+ withAnimation(Motion.hover) { dropTarget = on ? id : (dropTarget == id ? nil : dropTarget) }}}} else {ForEach(roster) { item inif let store = accounts.store(for: item.ref.computerId) {- row(item, store: store, caption: true)+ row(item, store: store)}}}@@ -119,25 +84,7 @@ struct BotListView: View {AccountSwitcherButton()}ToolbarItem(placement: .principal) {- if grouped {- VStack(spacing: 0) {- filterButton- ConnectingIndicator(isConnecting: shownComputers.contains {- accounts.store(for: $0.id)?.connection == .connecting- })- }- } else {- // Keep the center empty when connected, while the system owns the bar's layout.- ZStack {- Color.clear.frame(width: 1, height: 1)- ConnectingIndicator(isConnecting: accounts.computers.contains {- accounts.store(for: $0.id)?.connection == .connecting- })- }- }- }- ToolbarItem(placement: .topBarTrailing) {- Button("Computers", systemImage: "desktopcomputer") { app.showComputers = true }+ ComputerFilterHeader(accounts: accounts, hidden: $hiddenComputers) { app.showComputers = true }}ToolbarItem(placement: .topBarTrailing) {// A native menu: the bar hosts toolbar buttons outside SwiftUI's layout,@@ -153,18 +100,21 @@ struct BotListView: View {for computer in accounts.computers { accounts.store(for: computer.id)?.restartStream() }await accounts.refreshCloud()}- .codyncSheet(item: $connectingComputer) { computer in- AccessRequestView(computer: computer, pending: accounts.pendingAccess[computer.id] != nil)- }.codyncSheet(item: $editing) { target in- if let store = accounts.store(for: target.computerId) {- BotEditorView(draft: target.draft)+ // A new bot can move to another computer until it's created.+ let computerId = editing?.computerId ?? target.computerId+ if let store = accounts.store(for: computerId) {+ BotEditorView(draft: target.draft,+ computers: onlineStores.map { ($0.computer.id, $0.hostName) },+ computer: target.draft.id == nil+ ? Binding(get: { computerId }, set: { editing?.computerId = $0 })+ : nil).environment(store).onChange(of: store.selection) { _, botId in// A new bot opens its chat, on the computer it was created on.guard let botId else { return }store.selection = nil- accounts.selection = BotReference(accountId: accounts.accountId, computerId: target.computerId, botId: botId)+ accounts.selection = BotReference(accountId: accounts.accountId, computerId: computerId, botId: botId)}}}@@ -179,15 +129,6 @@ struct BotListView: View {}}}- .codyncSheet(isPresented: $pickingComputer) {- ComputerPicker(stores: onlineStores) { store in- // Let the picker slide away before the editor slides up.- Task {- try? await Task.sleep(for: .milliseconds(450))- editing = EditTarget(computerId: store.computer.id, draft: BotDraft())- }- }- }.codyncDialog("Delete \(confirmDelete?.bot.name ?? "bot")?",isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } }),message: confirmDelete?.bot.isGroup == true ? "Its bots and their own chats stay." : "Files it changed on your computer stay as they are.") {@@ -198,71 +139,15 @@ struct BotListView: View {}}- private var accountComputers: [CloudComputer] {- accounts.cloudComputers.filter { computer in- !accounts.computers.contains { $0.id == computer.id }- }- }-- /// "All computers ⌄" / "MacBook ⌄" / "2 computers ⌄".- private var filterButton: some View {- let shown = shownComputers- let title = shown.count == accounts.computers.count ? "All computers"- : shown.count == 1 ? (accounts.store(for: shown[0].id)?.hostName ?? shown[0].name)- : "\(shown.count) computers"- return Menu {- Button { setHidden([]) } label: {- Label("All computers", systemImage: shown.count == accounts.computers.count ? "checkmark" : "square.stack")- }- Divider()- ForEach(accounts.computers) { computer in- let isShown = shown.contains { $0.id == computer.id }- // A tap toggles one computer; the last one shown stays.- Button {- guard !isShown || shown.count > 1 else { return }- setHidden(isShown ? hidden.union([computer.id]) : hidden.subtracting([computer.id]))- } label: {- Label(accounts.store(for: computer.id)?.hostName ?? computer.name,- systemImage: isShown ? "checkmark" : "desktopcomputer")- }- }- } label: {- HStack(spacing: 6) {- Text(title)- .contentTransition(.opacity)- .lineLimit(1)- Image(systemName: "chevron.down").font(.caption2.weight(.bold)).foregroundStyle(Palette.tertiary)- }- .font(.subheadline.weight(.semibold))- .foregroundStyle(Palette.text)- .padding(.horizontal, 12)- .frame(height: 32)- .contentShape(Rectangle())- .animation(Motion.layout, value: title)- }- .accessibilityLabel("Show computers: \(title)")- }-- private func setHidden(_ ids: Set<ComputerID>) {- withAnimation(Motion.layout) { hiddenComputers = ids.sorted().joined(separator: ",") }- }-- private func row(_ item: RosterItem, store: BotStore, caption: Bool) -> some View {+ private func row(_ item: RosterItem, store: BotStore) -> some View {let bot = item.bot// A plain button instead of a NavigationLink: same push, no chevron.return Button { accounts.selection = item.ref } label: {- VStack(alignment: .leading, spacing: 0) {- BotRow(bot: bot)- if caption {- ComputerCaption(store: store)- .padding(.leading, 58)- .padding(.bottom, 6)- .offset(y: -6)- }- }- .environment(store)+ BotRow(bot: bot)+ .environment(store)}.buttonStyle(.plain)+ .accessibilityLabel(accounts.computers.count > 1 ? "\(bot.name), on \(store.hostName)" : bot.name).contextActions {[MenuItem(bot.pinned ? "Unpin" : "Pin", icon: bot.pinned ? "pin.slash" : "pin") { store.setPinned(bot, !bot.pinned) },@@ -286,41 +171,74 @@ struct BotListView: View {}}- /// A new bot lives on one computer: pick it first when there's a choice.+ /// A new bot starts on the first computer online; the editor's Computer row can move it.private func newBot() {- let stores = onlineStores- if stores.count == 1, let store = stores.first {- editing = EditTarget(computerId: store.computer.id, draft: BotDraft())- } else if stores.count > 1 {- pickingComputer = true- }+ guard let store = onlineStores.first else { return }+ editing = EditTarget(computerId: store.computer.id, draft: BotDraft())}}-/// A computer's heading above its bots: badge, name, and its connection, changing in place.+/// A computer's heading above its bots: badge, name and connection. Long-press and drag it onto+/// another computer's section to reorder.private struct ComputerSection: View {let store: BotStore+ let empty: Bool+ let targeted: Bool+ let move: (ComputerID, Int) -> Voidvar body: some View {- HStack(spacing: 6) {- ComputerBadge(store.computer, size: 18)- Text(store.hostName)- .font(.footnote.weight(.semibold))- .foregroundStyle(Palette.secondary)- .lineLimit(1)- Text(store.statusText)- .font(.footnote)- .foregroundStyle(store.isOffline ? Palette.warning : Palette.tertiary)- .contentTransition(.opacity)- if store.connection == .online {- RouteIcon(route: store.hostRoute).font(.caption2).foregroundStyle(Palette.tertiary)+ VStack(alignment: .leading, spacing: 6) {+ HStack(spacing: 6) {+ ComputerBadge(store.computer, size: 18)+ Text(store.hostName)+ .font(.footnote.weight(.semibold))+ .foregroundStyle(Palette.secondary)+ .lineLimit(1)+ Text(store.statusText)+ .font(.footnote)+ .foregroundStyle(store.isOffline ? Palette.warning : Palette.tertiary)+ .lineLimit(1)+ .contentTransition(.opacity)+ if store.connection == .online {+ RouteIcon(route: store.hostRoute).font(.caption2).foregroundStyle(Palette.tertiary)+ }+ Spacer(minLength: 8)+ Image(systemName: "line.3.horizontal")+ .font(.caption.weight(.semibold))+ .foregroundStyle(Palette.tertiary)+ .accessibilityHidden(true)+ }+ .padding(.vertical, 6)+ .padding(.horizontal, 8)+ .background(targeted ? Palette.bubbleAgent : .clear, in: RoundedRectangle(cornerRadius: 10, style: .continuous))+ .contentShape(Rectangle())+ .draggable(store.computer.id) {+ HStack(spacing: 6) {+ ComputerBadge(store.computer, size: 18)+ Text(store.hostName).font(.footnote.weight(.semibold)).foregroundStyle(Palette.text)+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ .background(Palette.bubbleAgent, in: Capsule())+ }+ if empty {+ Text("No bots yet")+ .font(.footnote)+ .foregroundStyle(Palette.tertiary)+ .padding(.horizontal, 8)+ .padding(.bottom, 4)}- Spacer()}- .padding(.top, 18)- .padding(.bottom, 4)+ .padding(.top, 14)+ .padding(.bottom, 2)+ .padding(.horizontal, -8).accessibilityElement(children: .combine).accessibilityAddTraits(.isHeader)+ .accessibilityHint("Drag to reorder computers")+ .accessibilityActions {+ Button("Move up") { move(store.computer.id, -1) }+ Button("Move down") { move(store.computer.id, 1) }+ }}}@@ -332,48 +250,10 @@ private struct GroupTarget: Identifiable {private struct EditTarget: Identifiable {let id = UUID()- let computerId: ComputerID+ var computerId: ComputerIDlet draft: BotDraft}-/// "Which computer should it run on?" — only computers that are online.-private struct ComputerPicker: View {- let stores: [BotStore]- let pick: (BotStore) -> Void- @Environment(\.dismissModal) private var dismiss-- var body: some View {- VStack(spacing: 0) {- ModalHeader("Run it on")- ScrollView {- VStack(spacing: 4) {- ForEach(stores, id: \.computer.id) { store in- Button {- dismiss()- pick(store)- } label: {- HStack(spacing: 12) {- ComputerBadge(store.computer, size: 36)- VStack(alignment: .leading, spacing: 2) {- Text(store.hostName).font(.body.weight(.semibold)).foregroundStyle(Palette.text)- Text("\(store.roster.count) bot\(store.roster.count == 1 ? "" : "s")")- .font(.subheadline).foregroundStyle(Palette.secondary)- }- Spacer()- RouteIcon(route: store.hostRoute).foregroundStyle(Palette.tertiary)- }- .padding(.horizontal, 20)- .padding(.vertical, 10)- .contentShape(Rectangle())- }- .buttonStyle(PressScale())- }- }- }- }- }-}-private struct EmptyRoster: View {let canCreate: Boollet hasComputer: Booldiff --git a/apps/ios/Views/RootView.swift b/apps/ios/Views/RootView.swiftindex 811aeb7b..1938ddf7 100644--- a/apps/ios/Views/RootView.swift+++ b/apps/ios/Views/RootView.swift@@ -43,7 +43,7 @@ struct RootView: View {// device-level milestone across account changes and unpairing.if !empty { onboardingCompleted = true }}- .codyncDialog("Something went wrong", isPresented: errorShown, message: errorMessage, cancel: "OK") { [] }+ .codyncDialog("Something went wrong", isPresented: errorShown, message: errorMessage, cancel: "OK", inPlace: true) { [] }.codyncOverlay(isPresented: Binding(get: { screenTarget.wrappedValue != nil }, set: { if !$0 { screenTarget.wrappedValue = nil } })) { close inif let target = screenTarget.wrappedValue, let store = accounts.store(for: target.computerId) {ScreenView(watching: target.request.watching, close: close)@@ -55,10 +55,16 @@ struct RootView: View {// Holds the pushes inside the sheet (Widgets, Live Activity); no bar shows.NavigationStack { SettingsView() }}- .codyncSheet(item: Binding(get: { app.marketplace.map(MarketplaceTarget.init) }, set: { app.marketplace = $0?.id })) { target in- if let store = accounts.store(for: target.id) {- MarketplaceView()+ .codyncSheet(item: Binding(get: { app.marketplace.map(MarketplaceTarget.init) }, set: { app.marketplace = $0?.computerId })) { target in+ // Switching computers inside keeps the sheet up and loads that computer's own marketplace.+ let computerId = app.marketplace ?? target.computerId+ if let store = accounts.store(for: computerId) {+ MarketplaceView(computers: accounts.computers.compactMap { accounts.store(for: $0.id) }+ .filter { $0.connection == .online }+ .map { ($0.computer.id, $0.hostName) },+ computer: Binding(get: { computerId }, set: { app.marketplace = $0 })).environment(store)+ .id(computerId)}}}@@ -339,5 +345,6 @@ private struct AccessBanners: View {/// The marketplace sheet's item, so it keeps its computer while sliding away.private struct MarketplaceTarget: Identifiable {- let id: ComputerID+ let computerId: ComputerID+ var id: String { "marketplace" }}diff --git a/apps/ios/Views/SettingsView.swift b/apps/ios/Views/SettingsView.swiftindex 3a1cc257..4d570e86 100644--- a/apps/ios/Views/SettingsView.swift+++ b/apps/ios/Views/SettingsView.swift@@ -30,6 +30,7 @@ struct SettingsView: View {if let store = accounts.store(for: computer.id) {ComputerRow(store: store, inAccount: cloudComputer(computer.id),openScreen: { openScreen(store) },+ openMarketplace: { closeSheets { app.marketplace = store.computer.id } },revoke: cloudComputer(computer.id).flatMap { c in c.access == "granted" ? { confirmRevoke = c } : nil },remove: { confirmForget = computer })}@@ -54,25 +55,6 @@ struct SettingsView: View {.buttonStyle(.plain)}- if !onlineStores.isEmpty {- CardSection {- ForEach(onlineStores, id: \.computer.id) { store in- Button {- let id = store.computer.id- closeSheets { app.marketplace = id }- } label: {- LinkRow {- VStack(alignment: .leading, spacing: 2) {- Text(onlineStores.count > 1 ? "Marketplace on \(store.hostName)" : "Marketplace")- Text("Agents, connectors and skills for your bots").font(.subheadline).foregroundStyle(Palette.secondary)- }- }- }- .buttonStyle(.plain)- }- }- }-CardSection("Notifications", footer: "Get a result summary, a request for input, or a failure notice. Notification previews follow your iOS settings.") {Toggle("Push notifications", isOn: $notificationsEnabled).toggleStyle(.codync)@@ -174,10 +156,6 @@ struct SettingsView: View {accounts.cloudComputers.filter { c in !accounts.computers.contains { $0.id == c.computerId } }}- private var onlineStores: [BotStore] {- accounts.computers.compactMap { accounts.store(for: $0.id) }.filter { $0.connection == .online }- }-private struct HiddenBot: Identifiable {let store: BotStorelet bot: Bot@@ -224,6 +202,8 @@ private struct ComputerRow: View {let store: BotStorelet inAccount: CloudComputer?let openScreen: () -> Void+ /// Agents, connectors and skills installed on this computer.+ let openMarketplace: () -> Void/// Set when this iPhone's access to the computer can be revoked.let revoke: (() -> Void)?let remove: () -> Void@@ -244,6 +224,9 @@ private struct ComputerRow: View {.foregroundStyle(store.isOffline ? Palette.warning : Palette.secondary)}Spacer()+ if store.connection == .online {+ IconButton("Marketplace", systemImage: "storefront", action: openMarketplace)+ }if store.screen != nil, store.connection == .online {IconButton("Screen", systemImage: "display", action: openScreen)}@@ -274,6 +257,9 @@ private struct ComputerRow: View {}},]+ if store.connection == .online {+ items.append(MenuItem("Marketplace", icon: "storefront", action: openMarketplace))+ }if store.screen != nil, store.connection == .online {items.append(MenuItem("Screen", icon: "display", action: openScreen))}diff --git a/apps/linux/src/client.rs b/apps/linux/src/client.rsindex 1293a6eb..28e6bdfb 100644--- a/apps/linux/src/client.rs+++ b/apps/linux/src/client.rs@@ -55,7 +55,7 @@ async fn call_async(method: String, body: Value) -> Result<Value, String> {.post(format!("{}/api/{method}", base())).bearer_auth(token).json(&body)- .timeout(Duration::from_secs(30))+ .timeout(Duration::from_secs(120)).send().await.map_err(|_| "Can't reach the Codync host.".to_owned())?;@@ -82,6 +82,58 @@ pub fn call(method: &str, body: Value, done: impl FnOnce(Result<Value, String>)});}+/// Uploads `files` in 384 KiB chunks (under the channel's message limit, like the apps), then+/// sends `body` with them attached; the result comes back on the main thread.+pub fn send_files(+ mut body: Value,+ files: Vec<PathBuf>,+ done: impl FnOnce(Result<Value, String>) + 'static,+) {+ const CHUNK: usize = 384 * 1024;+ const MAX: usize = 100 * 1024 * 1024;+ let (tx, rx) = async_channel::bounded(1);+ runtime().spawn(async move {+ let r = async {+ let mut ids = Vec::new();+ for path in &files {+ let name = path+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default();+ let data = tokio::fs::read(path)+ .await+ .map_err(|e| format!("Can't read {name}: {e}"))?;+ if data.len() > MAX {+ return Err(format!("{name} is over 100 MB."));+ }+ let id = uuid::Uuid::new_v4().to_string();+ let mut offset = 0;+ loop {+ let end = (offset + CHUNK).min(data.len());+ let chunk = gtk::glib::base64_encode(&data[offset..end]).to_string();+ let done = end == data.len();+ let chunk_body = json!({"botId": body["botId"], "uploadId": id, "name": name,+ "offset": offset, "data": chunk, "done": done});+ call_async("upload".into(), chunk_body).await?;+ if done {+ break;+ }+ offset = end;+ }+ ids.push(id);+ }+ body["attachments"] = ids.into();+ call_async("send".into(), body).await+ };+ let _ = tx.send(r.await).await;+ });+ gtk::glib::spawn_future_local(async move {+ if let Ok(r) = rx.recv().await {+ done(r);+ }+ });+}+pub enum Event {Online(bool),Message(Value),diff --git a/apps/linux/src/compose.rs b/apps/linux/src/compose.rsindex ae7ea7a6..fec9277d 100644--- a/apps/linux/src/compose.rs+++ b/apps/linux/src/compose.rs@@ -368,11 +368,11 @@ fn open_chat(ui: &App, id: &str) {ui.compose_page.previous.borrow_mut().take();ui::select(ui, id);if !text.is_empty() {- ui::send_text(ui, id, &text, None);+ ui::send_text(ui, id, &text, None, vec![]);}}-/// "New Bot" (or the typed name) with sensible defaults: the first available agent, home folder.+/// "New Bot" (or the typed name) with sensible defaults: the first available agent and a personal workspace.fn create(ui: &App) {if ui.compose_page.creating.replace(true) {return;@@ -390,7 +390,7 @@ fn create(ui: &App) {let n = uuid::Uuid::new_v4().as_u128() as usize;json!({"name": name, "description": "", "permission": "ask", "model": null, "command": null,- "cwd": st.hello["home"].as_str().unwrap_or(""),+ "cwd": "","avatarShape": avatar::SHAPES[n % avatar::SHAPES.len()],"avatarColor": avatar::COLORS[(n / 8) % avatar::COLORS.len()].0,"backend": backends.iter().find(|b| b["available"] == true).and_then(|b| b["id"].as_str()).unwrap_or("claude"),diff --git a/apps/linux/src/connections.rs b/apps/linux/src/connections.rsnew file mode 100644index 00000000..9bb42d60--- /dev/null+++ b/apps/linux/src/connections.rs@@ -0,0 +1,636 @@+//! Native connection cards use the same secure host workflow as iOS and macOS.+use crate::{+ client,+ rows::label,+ ui::{App, toast},+};+use adw::prelude::*;+use serde_json::{Value, json};+use std::{cell::RefCell, rc::Rc};++pub fn card(ui: &App, entry: &Value) -> gtk::Widget {+ let request = &entry["data"]["connectionRequest"];+ let body = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(10)+ .css_classes(["perm-card"])+ .build();+ body.append(&label(+ request["title"].as_str().unwrap_or("Connect service"),+ &["headline"],+ ));+ let reason = label(entry["data"]["text"].as_str().unwrap_or(""), &["secondary"]);+ reason.set_wrap(true);+ body.append(&reason);+ if request["status"] != "pending" {+ body.append(&label(+ if request["status"] == "ready" {+ "Connected"+ } else {+ "Cancelled"+ },+ &["secondary"],+ ));+ return body.upcast();+ }+ let input = gtk::PasswordEntry::builder()+ .show_peek_icon(true)+ .placeholder_text("Credential or op:// reference")+ .build();+ let secret = request["kind"] == "secret";+ if secret {+ body.append(&label(+ request["field"].as_str().unwrap_or("Credential"),+ &["secondary"],+ ));+ body.append(&input);+ body.append(&label(+ "Saved securely; never included in the conversation.",+ &["small", "secondary"],+ ));+ }+ let actions = gtk::Box::builder().spacing(8).build();+ let connect = gtk::Button::with_label(if secret {+ "Save and connect"+ } else {+ "Connect"+ });+ let cancel = gtk::Button::with_label("Cancel");+ actions.append(&connect);+ actions.append(&cancel);+ body.append(&actions);+ let (ui2, e) = (ui.clone(), entry.clone());+ connect.connect_clicked(move |button| {+ let r = &e["data"]["connectionRequest"];+ if secret {+ let value = input.text().to_string();+ if value.is_empty() {+ return;+ }+ button.set_sensitive(false);+ let (ui3, button, input) = (ui2.clone(), button.clone(), input.clone());+ client::call(+ "connectorRequestFinish",+ json!({"entryId":e["id"],"value":value}),+ move |result| {+ button.set_sensitive(true);+ match result {+ Ok(_) => input.set_text(""),+ Err(error) => toast(&ui3, &error),+ }+ },+ );+ } else if r["kind"] == "app" {+ hosted_app(+ &ui2,+ e["id"].clone(),+ r["toolkit"].as_str().unwrap_or("").to_owned(),+ );+ } else if let Some(id) = r["connectorId"].as_str() {+ authorize(&ui2, e["id"].clone(), id.to_owned());+ } else {+ let (ui3, e) = (ui2.clone(), e.clone());+ client::call(+ "connectorInfo",+ json!({"registryName":r["registryName"]}),+ move |result| match result {+ Ok(item) => install(&ui3, &item, e["id"].clone()),+ Err(error) => toast(&ui3, &error),+ },+ );+ }+ });+ let (ui2, id) = (ui.clone(), entry["id"].clone());+ cancel.connect_clicked(move |button| {+ button.set_sensitive(false);+ let (ui3, button) = (ui2.clone(), button.clone());+ client::call(+ "connectorRequestFinish",+ json!({"entryId":id,"cancel":true}),+ move |r| {+ button.set_sensitive(true);+ if let Err(e) = r {+ toast(&ui3, &e);+ }+ },+ );+ });+ body.upcast()+}++fn dialog(ui: &App, title: &str) -> (adw::Dialog, gtk::Box) {+ let body = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(12)+ .margin_top(20)+ .margin_bottom(20)+ .margin_start(20)+ .margin_end(20)+ .build();+ let view = adw::ToolbarView::new();+ view.add_top_bar(&adw::HeaderBar::new());+ let scroll = gtk::ScrolledWindow::builder().child(&body).build();+ view.set_content(Some(&scroll));+ let dialog = adw::Dialog::builder()+ .title(title)+ .content_width(480)+ .content_height(440)+ .child(&view)+ .build();+ dialog.present(Some(&ui.window));+ (dialog, body)+}++fn install(ui: &App, item: &Value, entry: Value) {+ if let Some(options) = item["options"].as_array()+ && options.len() == 1+ && options[0]["inputs"].as_array().is_some_and(Vec::is_empty)+ {+ let ui = ui.clone();+ client::call(+ "installConnector",+ json!({"registryName":item["name"],"option":options[0]["id"],"inputs":{}}),+ move |r| match r {+ Ok(v) => added(&ui, entry, &v["connector"]),+ Err(e) => toast(&ui, &e),+ },+ );+ return;+ }++ let (window, body) = dialog(ui, item["title"].as_str().unwrap_or("Connect"));+ let options = item["options"].as_array().cloned().unwrap_or_default();+ for option in options {+ let section = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(8)+ .build();+ section.append(&label(+ option["label"].as_str().unwrap_or("Setup"),+ &["headline"],+ ));+ let mut inputs: Vec<(String, gtk::Entry)> = Vec::new();+ for field in option["inputs"].as_array().into_iter().flatten() {+ let input = gtk::Entry::builder()+ .placeholder_text(field["name"].as_str().unwrap_or("Value"))+ .visibility(field["secret"] != true)+ .text(field["default"].as_str().unwrap_or(""))+ .build();+ section.append(&input);+ inputs.push((field["name"].as_str().unwrap_or("").to_owned(), input));+ }+ let add = gtk::Button::with_label("Add");+ section.append(&add);+ body.append(§ion);+ let (ui, item, entry, window) = (ui.clone(), item.clone(), entry.clone(), window.clone());+ add.connect_clicked(move |button| {+ button.set_sensitive(false);+ let values: serde_json::Map<String, Value> = inputs+ .iter()+ .map(|(k, e)| (k.clone(), e.text().to_string().into()))+ .collect();+ let (ui, entry, window, button, inputs) = (+ ui.clone(),+ entry.clone(),+ window.clone(),+ button.clone(),+ inputs.clone(),+ );+ client::call(+ "installConnector",+ json!({"registryName":item["name"],"option":option["id"],"inputs":values}),+ move |r| {+ button.set_sensitive(true);+ match r {+ Ok(v) => {+ for (_, input) in inputs {+ input.set_text("");+ }+ window.close();+ added(&ui, entry, &v["connector"]);+ }+ Err(e) => toast(&ui, &e),+ }+ },+ );+ });+ }+}++fn added(ui: &App, entry: Value, connector: &Value) {+ let id = connector["id"].as_str().unwrap_or("").to_owned();+ if connector["auth"] == "signedOut" {+ authorize(ui, entry, id);+ return;+ }+ let ui = ui.clone();+ let method = if entry.is_null() {+ "connectorVerify"+ } else {+ "connectorRequestFinish"+ };+ client::call(+ method,+ json!({"id":id,"connectorId":id,"entryId":entry}),+ move |r| match r {+ Ok(_) => toast(&ui, "Connected"),+ Err(e) => toast(&ui, &e),+ },+ );+}++fn authorize(ui: &App, entry: Value, id: String) {+ let (window, body) = dialog(ui, "Connect service");+ body.append(&label(+ "Sign in if needed, then check the connection.",+ &["secondary"],+ ));+ let login = gtk::Button::with_label("Sign in");+ body.append(&login);+ let check = gtk::Button::with_label("Check connection");+ body.append(&check);+ let (ui2, id2) = (ui.clone(), id.clone());+ login.connect_clicked(move |button| {+ button.set_sensitive(false);+ let (ui, button) = (ui2.clone(), button.clone());+ client::call("connectorSignIn", json!({"id":id2}), move |r| {+ button.set_sensitive(true);+ match r {+ Ok(v) => {+ if let Some(url) = v["url"].as_str() {+ let _ = gtk::gio::AppInfo::launch_default_for_uri(+ url,+ None::<>k::gio::AppLaunchContext>,+ );+ }+ }+ Err(e) => toast(&ui, &e),+ }+ });+ });+ let ui = ui.clone();+ check.connect_clicked(move |button| {+ button.set_sensitive(false);+ let (ui, window, button) = (ui.clone(), window.clone(), button.clone());+ let method = if entry.is_null() {+ "connectorVerify"+ } else {+ "connectorRequestFinish"+ };+ client::call(+ method,+ json!({"entryId":entry,"connectorId":id,"id":id}),+ move |r| {+ button.set_sensitive(true);+ match r {+ Ok(_) => {+ window.close();+ }+ Err(e) => toast(&ui, &e),+ }+ },+ );+ });+}++pub fn credentials(ui: &App) {+ let (_window, body) = dialog(ui, "Credentials");+ let status = label("Linux Secret Service · encrypted storage", &["headline"]);+ body.append(&status);+ let help = label(+ "1Password: install the op CLI and use a service account restricted to a dedicated shared vault. Use op://vault/item/field in connector credential fields.",+ &["secondary"],+ );+ help.set_wrap(true);+ body.append(&help);+ let composio = gtk::PasswordEntry::builder()+ .placeholder_text("Composio API key (for hosted apps)")+ .show_peek_icon(true)+ .build();+ body.append(&composio);+ let setup = gtk::Button::with_label("Set up hosted apps");+ body.append(&setup);+ let ui2 = ui.clone();+ setup.connect_clicked(move |button| {+ button.set_sensitive(false);+ let (ui, composio, button) = (ui2.clone(), composio.clone(), button.clone());+ client::call(+ "setComposioKey",+ json!({"key":composio.text().as_str()}),+ move |r| {+ button.set_sensitive(true);+ match r {+ Ok(_) => {+ composio.set_text("");+ toast(&ui, "Hosted apps configured");+ }+ Err(e) => toast(&ui, &e),+ }+ },+ );+ });+ let saved = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(8)+ .build();+ body.append(&saved);+ let ui2 = ui.clone();+ client::call("connectors", json!({}), move |r| {+ if let Ok(v) = r {+ for connector in v["items"].as_array().into_iter().flatten() {+ if connector["keys"].as_array().is_none_or(Vec::is_empty) {+ continue;+ }+ let button = gtk::Button::with_label(+ connector["name"].as_str().unwrap_or("Saved connection"),+ );+ saved.append(&button);+ let (ui, connector) = (ui2.clone(), connector.clone());+ button.connect_clicked(move |_| edit_credentials(&ui, &connector));+ }+ }+ });+ let input = gtk::PasswordEntry::builder()+ .placeholder_text("1Password service account token")+ .show_peek_icon(true)+ .build();+ body.append(&input);+ let connect = gtk::Button::with_label("Connect 1Password");+ body.append(&connect);+ let disconnect = gtk::Button::with_label("Disconnect 1Password");+ body.append(&disconnect);+ let busy = Rc::new(RefCell::new(false));+ for (button, remove) in [(connect, false), (disconnect, true)] {+ let (ui, input, status, busy) = (ui.clone(), input.clone(), status.clone(), busy.clone());+ button.connect_clicked(move |_| {+ if *busy.borrow() {+ return;+ }+ *busy.borrow_mut() = true;+ let token = if remove {+ String::new()+ } else {+ input.text().to_string()+ };+ let (ui, input, status, busy) =+ (ui.clone(), input.clone(), status.clone(), busy.clone());+ client::call(+ "credentialSetOnePassword",+ json!({"token":token}),+ move |r| {+ *busy.borrow_mut() = false;+ match r {+ Ok(v) => {+ input.set_text("");+ status.set_label(if v["onePasswordConnected"] == true {+ "1Password connected"+ } else {+ "1Password disconnected"+ });+ }+ Err(e) => toast(&ui, &e),+ }+ },+ );+ });+ }+ client::call("credentialStatus", json!({}), move |r| match r {+ Ok(v) => status.set_label(if v["onePasswordConnected"] == true {+ "Secret Service · 1Password connected"+ } else {+ "Secret Service"+ }),+ Err(e) => status.set_label(&e),+ });+}++/// Registry browsing is explicit and paged; Add uses the same secure setup form.+pub fn marketplace(ui: &App) {+ let (_window, body) = dialog(ui, "Connectors");+ let search = gtk::SearchEntry::new();+ body.append(&search);+ let results = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(12)+ .build();+ body.append(&results);+ let load = gtk::Button::with_label("Search / load connectors");+ body.append(&load);+ let more = gtk::Button::with_label("Load more");+ more.set_visible(false);+ body.append(&more);+ let cursor = Rc::new(RefCell::new(Value::Null));+ let query = Rc::new(RefCell::new(String::new()));+ let pending = Rc::new(RefCell::new(Vec::<Value>::new()));+ let loading = Rc::new(RefCell::new(false));+ for (button, next) in [(load, false), (more.clone(), true)] {+ let (ui, search, results, more, cursor, query, pending, loading) = (+ ui.clone(),+ search.clone(),+ results.clone(),+ more.clone(),+ cursor.clone(),+ query.clone(),+ pending.clone(),+ loading.clone(),+ );+ button.connect_clicked(move |_| {+ if *loading.borrow() {+ return;+ }+ if !next {+ *query.borrow_mut() = search.text().to_string();+ *cursor.borrow_mut() = Value::Null;+ pending.borrow_mut().clear();+ while let Some(child) = results.first_child() {+ results.remove(&child);+ }+ } else if !pending.borrow().is_empty() {+ reveal(&ui, &results, &pending);+ more.set_visible(!pending.borrow().is_empty() || cursor.borrow().is_string());+ return;+ }+ *loading.borrow_mut() = true;+ let (ui, results, more, cursor, pending, loading) = (+ ui.clone(),+ results.clone(),+ more.clone(),+ cursor.clone(),+ pending.clone(),+ loading.clone(),+ );+ client::call(+ "marketConnectors",+ json!({"search":*query.borrow(),"cursor":*cursor.borrow()}),+ move |r| {+ *loading.borrow_mut() = false;+ match r {+ Ok(v) => {+ *cursor.borrow_mut() = v["nextCursor"].clone();+ *pending.borrow_mut() =+ v["items"].as_array().cloned().unwrap_or_default();+ reveal(&ui, &results, &pending);+ more.set_visible(+ !pending.borrow().is_empty() || cursor.borrow().is_string(),+ );+ }+ Err(e) => toast(&ui, &e),+ }+ },+ );+ });+ }+}++fn reveal(ui: &App, results: >k::Box, pending: &Rc<RefCell<Vec<Value>>>) {+ let count = pending.borrow().len().min(12);+ let page: Vec<_> = pending.borrow_mut().drain(..count).collect();+ for item in page {+ let row = gtk::Box::builder().spacing(8).build();+ let name = label(item["title"].as_str().unwrap_or("Connector"), &["headline"]);+ name.set_hexpand(true);+ row.append(&name);+ let add = gtk::Button::with_label(if item["installed"] == true {+ "Added"+ } else {+ "Add"+ });+ add.set_sensitive(item["installed"] != true);+ row.append(&add);+ results.append(&row);+ let ui = ui.clone();+ add.connect_clicked(move |_| install(&ui, &item, Value::Null));+ }+}++fn hosted_app(ui: &App, entry: Value, toolkit: String) {+ let (window, body) = dialog(ui, "Connect app");+ let ui = ui.clone();+ client::call("composioConnect", json!({"toolkit":toolkit}), move |r| {+ let plan = match r {+ Ok(v) => v,+ Err(e) => {+ toast(&ui, &e);+ return;+ }+ };+ if let Some(url) = plan["url"].as_str() {+ let _ =+ gtk::gio::AppInfo::launch_default_for_uri(url, None::<>k::gio::AppLaunchContext>);+ }+ let mut fields = Vec::new();+ for field in plan["fields"].as_array().into_iter().flatten() {+ let input = gtk::Entry::builder()+ .placeholder_text(field["label"].as_str().unwrap_or("Value"))+ .visibility(field["secret"] != true)+ .build();+ body.append(&input);+ fields.push((field["name"].as_str().unwrap_or("").to_owned(), input));+ }+ let connect = gtk::Button::with_label(if fields.is_empty() {+ "Check connection"+ } else {+ "Connect"+ });+ body.append(&connect);+ connect.connect_clicked(move |button| {+ button.set_sensitive(false);+ let (method, args) = if plan["status"] == "needsFields" {+ let values: serde_json::Map<String, Value> = fields+ .iter()+ .map(|(k, v)| (k.clone(), v.text().to_string().into()))+ .collect();+ (+ "composioConnectFields",+ json!({"toolkit":toolkit,"mode":plan["mode"],"fields":values}),+ )+ } else {+ ("composioConnection", json!({"id":plan["connection"]}))+ };+ let (ui, entry, toolkit, window, button, fields) = (+ ui.clone(),+ entry.clone(),+ toolkit.clone(),+ window.clone(),+ button.clone(),+ fields.clone(),+ );+ client::call(method, args, move |r| {+ button.set_sensitive(true);+ match r {+ Ok(v) if v["status"] == "active" => {+ for (_, input) in fields {+ input.set_text("");+ }+ client::call(+ "connectorRequestFinish",+ json!({"entryId":entry,"connectorId":format!("composio-{toolkit}")}),+ move |r| match r {+ Ok(_) => {+ window.close();+ }+ Err(e) => toast(&ui, &e),+ },+ );+ }+ Ok(_) => toast(&ui, "Finish signing in, then check again."),+ Err(e) => toast(&ui, &e),+ }+ });+ });+ });+}++fn edit_credentials(ui: &App, connector: &Value) {+ let (window, body) = dialog(ui, connector["name"].as_str().unwrap_or("Credentials"));+ body.append(&label(+ "Enter only values to replace, or an op:// reference.",+ &["secondary"],+ ));+ let mut fields = Vec::new();+ for key in connector["keys"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ {+ let input = gtk::PasswordEntry::builder()+ .placeholder_text(key)+ .show_peek_icon(true)+ .build();+ body.append(&input);+ fields.push((key.to_owned(), input));+ }+ let save = gtk::Button::with_label("Save credentials");+ body.append(&save);+ let (ui, id) = (ui.clone(), connector["id"].clone());+ save.connect_clicked(move |button| {+ let values: serde_json::Map<String, Value> = fields+ .iter()+ .filter(|(_, v)| !v.text().is_empty())+ .map(|(k, v)| (k.clone(), v.text().to_string().into()))+ .collect();+ if values.is_empty() {+ return;+ }+ button.set_sensitive(false);+ let (ui, window, button, fields) =+ (ui.clone(), window.clone(), button.clone(), fields.clone());+ client::call(+ "credentialUpdateConnector",+ json!({"id":id,"fields":values}),+ move |r| {+ button.set_sensitive(true);+ match r {+ Ok(_) => {+ for (_, input) in fields {+ input.set_text("");+ }+ window.close();+ }+ Err(e) => toast(&ui, &e),+ }+ },+ );+ });+}diff --git a/apps/linux/src/dialogs.rs b/apps/linux/src/dialogs.rsindex d28abbff..1290ccd8 100644--- a/apps/linux/src/dialogs.rs+++ b/apps/linux/src/dialogs.rs@@ -44,6 +44,9 @@ pub fn editor(ui: &App, bot: Option<Value>) {})})));+ if d.borrow()["managedWorkspace"] == true {+ d.borrow_mut()["cwd"] = "".into();+ }let (dialog, view, header) =header_dialog(if is_new { "New Bot" } else { "Edit Bot" }, 560, 720);let save = gtk::Button::builder()@@ -244,14 +247,14 @@ pub fn editor(ui: &App, bot: Option<Value>) {// Project folder (native folder chooser: the host runs on this computer)let project = adw::PreferencesGroup::builder()- .title("Project folder")+ .title("Workspace (project folder optional)").build();let folder_row = adw::ActionRow::builder().title(d.borrow()["cwd"].as_str().filter(|s| !s.is_empty())- .unwrap_or("Choose a folder…"),+ .unwrap_or("Personal workspace · allocated automatically"),).activatable(true).build();@@ -263,6 +266,20 @@ pub fn editor(ui: &App, bot: Option<Value>) {.build();folder_row.add_suffix(&choose);project.add(&folder_row);+ let personal = gtk::Button::builder()+ .icon_name("edit-undo-symbolic")+ .tooltip_text("Use personal workspace")+ .css_classes(["flat"])+ .valign(gtk::Align::Center)+ .build();+ folder_row.add_suffix(&personal);+ {+ let (draft, row) = (d.clone(), folder_row.clone());+ personal.connect_clicked(move |_| {+ draft.borrow_mut()["cwd"] = "".into();+ row.set_title("Personal workspace · allocated automatically");+ });+ }{let (d2, row, dialog2) = (d.clone(), folder_row.clone(), dialog.clone());let pick = move || {@@ -573,10 +590,7 @@ pub fn group_editor(ui: &App, group: Option<Value>) {.build();let bname = b["name"].as_str().unwrap_or("");text.append(&label(bname, &["body13"]));- text.append(&label(- &ui::folder(b["cwd"].as_str().unwrap_or("")),- &["footnote", "tertiary"],- ));+ text.append(&label(&ui::folder(b), &["footnote", "tertiary"]));row.append(&text);let plus = gtk::Image::from_icon_name("list-add-symbolic");plus.add_css_class("tertiary");@@ -838,11 +852,11 @@ pub fn trace(ui: &App) {let text = entries.iter().find(|x| x["id"] == root)- .and_then(|x| x["data"]["text"].as_str())- .unwrap_or("");+ .map(crate::rows::message_text)+ .unwrap_or_default();list.append(>k::Label::builder()- .label(format!("Thread · {}", short(text, 60)))+ .label(format!("Thread · {}", short(&text, 60))).xalign(0.0).ellipsize(gtk::pango::EllipsizeMode::End).css_classes(["title-4"])@@ -895,8 +909,8 @@ fn trace_lane(list: >k::Box, entries: &[&Value]) {let title = entries.iter().find(|x| x["turn"] == t && x["kind"] == "user")- .and_then(|x| x["data"]["text"].as_str())- .unwrap_or("");+ .map(|x| crate::rows::message_text(x))+ .unwrap_or_default();group = adw::PreferencesGroup::builder().title(gtk::glib::markup_escape_text(&title.chars().take(80).collect::<String>(),@@ -1297,6 +1311,16 @@ fn remote_screen_group() -> adw::PreferencesGroup {pub fn settings(ui: &App) {let (dialog, view, _) = header_dialog("Computers & devices", 520, 720);let page = adw::PreferencesPage::new();+ let credentials = adw::PreferencesGroup::new();+ let button = gtk::Button::with_label("Credentials");+ let ui2 = ui.clone();+ button.connect_clicked(move |_| crate::connections::credentials(&ui2));+ credentials.add(&button);+ let marketplace = gtk::Button::with_label("Connectors");+ let ui2 = ui.clone();+ marketplace.connect_clicked(move |_| crate::connections::marketplace(&ui2));+ credentials.add(&marketplace);+ page.add(&credentials);let pair = adw::PreferencesGroup::builder().title("Pair your iPhone").description("Scan with the Codync app or the iPhone Camera.")diff --git a/apps/linux/src/main.rs b/apps/linux/src/main.rsindex f066d268..bfb93985 100644--- a/apps/linux/src/main.rs+++ b/apps/linux/src/main.rs@@ -3,6 +3,7 @@mod avatar;mod client;mod compose;+mod connections;mod dialogs;mod markup;mod orb;@@ -204,6 +205,7 @@ button.send:disabled { background: @cd_accent_dim; color: @cd_tertiary; }/* Compose page and editors */floating-sheet > sheet, dialog.floating sheet, dialog sheet { outline: none; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.45); border-radius: 18px; }entry.plain, entry.plain:focus-within { background: transparent; box-shadow: none; outline: none; border: none; padding: 0; min-height: 0; }+.file-card { background: @cd_user; border-radius: 14px; padding: 8px 12px; }.chip { background: @cd_agent; border-radius: 999px; padding: 3px 4px 3px 8px; }button.chip-x { min-width: 18px; min-height: 18px; padding: 0; background: transparent; box-shadow: none; border: none; color: @cd_secondary; }.pick-card { background: @cd_surface; border-radius: 18px; padding: 8px; box-shadow: 0 6px 16px rgba(0,0,0,0.08); }diff --git a/apps/linux/src/rows.rs b/apps/linux/src/rows.rsindex 38014265..f41dcd97 100644--- a/apps/linux/src/rows.rs+++ b/apps/linux/src/rows.rs@@ -3,7 +3,7 @@//! the working indicator.use crate::client;-use crate::ui::{self, App, State, folder, toast};+use crate::ui::{self, App, State, folder_name, toast};use crate::{avatar, markup, orb};use adw::prelude::*;use gtk::glib::DateTime;@@ -122,8 +122,13 @@ pub fn user_bubble(r: &Reply, e: &Value, bot_working: bool, start: bool) -> gtk:.margin_top(if start { 12 } else { 4 }).build();let text = e["data"]["text"].as_str().unwrap_or("");- let b = bubble(text, false, "bubble-user");- col.append(&with_menu(r, b.upcast_ref(), true, text, false));+ for a in e["data"]["attachments"].as_array().into_iter().flatten() {+ col.append(&file_card(a));+ }+ if !text.is_empty() {+ let b = bubble(text, false, "bubble-user");+ col.append(&with_menu(r, b.upcast_ref(), true, text, false));+ }let status = match e["data"]["status"].as_str() {Some("sending") => "Sending…".to_owned(),Some("queued") if bot_working => "Waiting to send — it'll read this when it's done".into(),@@ -140,6 +145,53 @@ pub fn user_bubble(r: &Reply, e: &Value, bot_working: bool, start: bool) -> gtk:col.upcast()}+/// A message as one line of text: its text, or else its file names.+pub fn message_text(e: &Value) -> String {+ match e["data"]["text"].as_str().filter(|t| !t.is_empty()) {+ Some(t) => t.to_owned(),+ None => e["data"]["attachments"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|a| a["name"].as_str())+ .collect::<Vec<_>>()+ .join(", "),+ }+}++/// A file sent with a message: its name and size.+fn file_card(a: &Value) -> gtk::Widget {+ let card = gtk::Box::builder()+ .spacing(8)+ .halign(gtk::Align::End)+ .css_classes(["file-card"])+ .build();+ card.append(>k::Image::from_icon_name("text-x-generic-symbolic"));+ let col = gtk::Box::new(gtk::Orientation::Vertical, 0);+ let name = label(a["name"].as_str().unwrap_or("File"), &[]);+ name.set_ellipsize(gtk::pango::EllipsizeMode::Middle);+ name.set_max_width_chars(36);+ name.set_xalign(0.0);+ col.append(&name);+ let size = label(&file_size(a["size"].as_u64().unwrap_or(0)), &["time"]);+ size.set_xalign(0.0);+ col.append(&size);+ card.append(&col);+ card.upcast()+}++fn file_size(bytes: u64) -> String {+ match bytes {+ 0..1024 => format!("{bytes} B"),+ 1024..1_048_576 => format!("{} KB", bytes / 1024),+ _ => format!(+ "{}.{} MB",+ bytes / 1_048_576,+ bytes % 1_048_576 * 10 / 1_048_576+ ),+ }+}+pub fn agent_bubble(r: &Reply, st: &State, e: &Value, group: bool, start: bool) -> gtk::Widget {let col = gtk::Box::builder().orientation(gtk::Orientation::Vertical)@@ -161,7 +213,12 @@ pub fn agent_bubble(r: &Reply, st: &State, e: &Value, group: bool, start: bool)}pub fn notice(e: &Value) -> gtk::Widget {- let text = e["data"]["text"].as_str().unwrap_or("");+ let mut text = e["data"]["text"].as_str().unwrap_or("").to_owned();+ // A voice call from the phone: "Voice chat · 00:16".+ if let Some(s) = e["data"]["callSeconds"].as_u64() {+ text = format!("{text} · {:02}:{:02}", s / 60, s % 60);+ }+ let text = text.as_str();match e["data"]["style"].as_str() {Some("divider") => {let row = gtk::Box::builder()@@ -271,7 +328,7 @@ pub fn permission_card(ui: &App, st: &State, e: &Value, group: bool) -> gtk::Widicon.add_css_class("tertiary");icon.set_pixel_size(12);runs.append(&icon);- let cwd = d["cwd"].as_str().map(folder);+ let cwd = d["cwd"].as_str().map(folder_name);runs.append(&label(&format!("Runs on {host}{}",diff --git a/apps/linux/src/ui.rs b/apps/linux/src/ui.rsindex c95984e1..d0413a7e 100644--- a/apps/linux/src/ui.rs+++ b/apps/linux/src/ui.rs@@ -37,6 +37,11 @@ pub struct State {/// typing `@` suggests its bots.pub struct Composer {view: gtk::TextView,+ attach_btn: gtk::Button,+ /// Files picked or dropped for the next message, shown as chips above the box.+ files: RefCell<Vec<std::path::PathBuf>>,+ files_box: gtk::Box,+ files_rev: gtk::Revealer,placeholder: gtk::Label,send_btn: gtk::Button,stop_btn: gtk::Button,@@ -92,6 +97,14 @@ fn composer() -> Composer {.margin_top(6).margin_bottom(16).build();+ let attach_btn = gtk::Button::builder()+ .icon_name("mail-attachment-symbolic")+ .tooltip_text("Attach files")+ .css_classes(["icon-btn"])+ .valign(gtk::Align::End)+ .margin_bottom(2)+ .build();+ pill.append(&attach_btn);pill.append(&field);pill.append(&stop_btn);pill.append(&send_btn);@@ -110,8 +123,24 @@ fn composer() -> Composer {.build(),).build();+ let files_box = gtk::Box::builder()+ .spacing(6)+ .margin_start(16)+ .margin_end(16)+ .margin_top(6)+ .build();+ let files_rev = gtk::Revealer::builder()+ .transition_type(gtk::RevealerTransitionType::SlideUp)+ .child(+ >k::ScrolledWindow::builder()+ .vscrollbar_policy(gtk::PolicyType::Never)+ .child(&files_box)+ .build(),+ )+ .build();let col = gtk::Box::new(gtk::Orientation::Vertical, 0);col.append(&mentions_rev);+ col.append(&files_rev);col.append(&pill);let root = gtk::Box::new(gtk::Orientation::Vertical, 0);root.append(@@ -123,6 +152,10 @@ fn composer() -> Composer {);Composer {view,+ attach_btn,+ files: RefCell::default(),+ files_box,+ files_rev,placeholder,send_btn,stop_btn,@@ -748,6 +781,99 @@ fn wire_composer(ui: &App, in_thread: bool) {.buffer().connect_changed(move |_| update_composer(&ui2, in_thread));}+ {+ let ui2 = ui.clone();+ c.attach_btn.connect_clicked(move |b| {+ let ui3 = ui2.clone();+ gtk::FileDialog::builder()+ .title("Attach files")+ .build()+ .open_multiple(+ b.root().and_downcast_ref::<gtk::Window>(),+ gtk::gio::Cancellable::NONE,+ move |r| {+ let Ok(list) = r else { return };+ let paths = (0..list.n_items())+ .filter_map(|i| list.item(i).and_downcast::<gtk::gio::File>())+ .filter_map(|f| f.path());+ add_files(&ui3, in_thread, paths);+ },+ );+ });+ }+ {+ // Files dropped on the box.+ let ui2 = ui.clone();+ let drop = gtk::DropTarget::new(+ gtk::gdk::FileList::static_type(),+ gtk::gdk::DragAction::COPY,+ );+ drop.connect_drop(move |_, v, _, _| {+ let Ok(list) = v.get::<gtk::gdk::FileList>() else {+ return false;+ };+ add_files(+ &ui2,+ in_thread,+ list.files().iter().filter_map(|f| f.path()),+ );+ true+ });+ c.root.add_controller(drop);+ }+}++/// Adds files to the next message (not in a group: it has no folder of its own).+fn add_files(ui: &App, in_thread: bool, paths: impl Iterator<Item = std::path::PathBuf>) {+ let group = {+ let st = ui.state.borrow();+ st.current+ .as_ref()+ .and_then(|id| st.bots.get(id))+ .is_some_and(is_group)+ };+ if group {+ toast(ui, "Files can't be sent to a group.");+ return;+ }+ ui.composer(in_thread)+ .files+ .borrow_mut()+ .extend(paths.filter(|p| p.is_file()));+ show_files(ui, in_thread);+}++/// The chips for the picked files; × removes one.+fn show_files(ui: &App, in_thread: bool) {+ let c = ui.composer(in_thread);+ clear(&c.files_box);+ let files = c.files.borrow().clone();+ for (i, path) in files.iter().enumerate() {+ let chip = gtk::Box::builder().spacing(4).css_classes(["chip"]).build();+ chip.append(>k::Image::from_icon_name("text-x-generic-symbolic"));+ let name = path+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default();+ chip.append(&label(&name, &["small"]));+ let x = gtk::Button::builder()+ .icon_name("window-close-symbolic")+ .tooltip_text("Remove")+ .css_classes(["chip-x"])+ .build();+ let ui2 = ui.clone();+ x.connect_clicked(move |_| {+ let c = ui2.composer(in_thread);+ if i < c.files.borrow().len() {+ c.files.borrow_mut().remove(i);+ }+ show_files(&ui2, in_thread);+ });+ chip.append(&x);+ c.files_box.append(&chip);+ }+ c.files_rev.set_reveal_child(!files.is_empty());+ update_composer(ui, in_thread);}fn connect(ui: &App) {@@ -1016,7 +1142,15 @@ pub fn backend_name(st: &State, id: &str) -> String {.to_owned()}-pub fn folder(p: &str) -> String {+/// Where a bot works, short: its project folder's name, or its personal workspace.+pub fn folder(bot: &Value) -> String {+ if bot["managedWorkspace"] == true {+ return "personal workspace".into();+ }+ folder_name(bot["cwd"].as_str().unwrap_or(""))+}++pub fn folder_name(p: &str) -> String {std::path::Path::new(p).file_name().map_or_else(|| p.to_owned(), |s| s.to_string_lossy().into_owned())@@ -1077,7 +1211,7 @@ fn preview(st: &State, b: &Value) -> gtk::Widget {format!("{} · {}",backend_name(st, b["backend"].as_str().unwrap_or("")),- folder(b["cwd"].as_str().unwrap_or(""))+ folder(b))}},@@ -1229,7 +1363,11 @@ fn intro(st: &State, bot: &Value) -> gtk::Box {&format!("{} in {}",backend_name(st, bot["backend"].as_str().unwrap_or("")),- bot["cwd"].as_str().unwrap_or("")+ if bot["managedWorkspace"] == true {+ "its personal workspace"+ } else {+ bot["cwd"].as_str().unwrap_or("")+ }),&["footnote", "mono", "tertiary"],));@@ -1346,7 +1484,7 @@ fn render_details(ui: &App, st: &State, bot: &Value) {.unwrap_or("Working…").to_owned()} else {- folder(m["cwd"].as_str().unwrap_or(""))+ folder(m)};let s = label(&sub, &["small", "tertiary"]);s.set_ellipsize(gtk::pango::EllipsizeMode::End);@@ -1531,6 +1669,9 @@ fn append_entries("user" => list.append(&user_bubble(&r, e, working(chat), start)),"agent" => list.append(&agent_bubble(&r, st, e, group, start)),"permission" => list.append(&permission_card(ui, st, e, group)),+ _ if e["data"]["connectionRequest"].is_object() => {+ list.append(&crate::connections::card(ui, e))+ }_ => list.append(¬ice(e)),}let indent = if group && kind == "agent" { 34 } else { 0 };@@ -1579,7 +1720,7 @@ fn update_composer_for(ui: &App, st: &State, chat: &Value, in_thread: bool) {let text = buf.text(&buf.start_iter(), &buf.end_iter(), false).to_string();- let has_text = !text.trim().is_empty();+ let has_text = !text.trim().is_empty() || !c.files.borrow().is_empty();let lane = if in_thread {st.open_thread.as_deref()} else {@@ -1597,8 +1738,9 @@ fn update_composer_for(ui: &App, st: &State, chat: &Value, in_thread: bool) {format!("Message {name}")});c.placeholder.set_visible(text.is_empty());- c.stop_btn.set_visible(busy && text.is_empty());- c.send_btn.set_visible(!(busy && text.is_empty()));+ c.attach_btn.set_visible(!is_group(chat));+ c.stop_btn.set_visible(busy && !has_text);+ c.send_btn.set_visible(!busy || has_text);c.send_btn.set_sensitive(has_text);// `@` suggests the group's bots.@@ -1654,20 +1796,37 @@ fn send(ui: &App, in_thread: bool) {let Some(bot) = bot else {return;};- if text.is_empty() || (in_thread && thread.is_none()) {+ let c = ui.composer(in_thread);+ if (text.is_empty() && c.files.borrow().is_empty()) || (in_thread && thread.is_none()) {return;}+ let files = c.files.take();buf.set_text("");- send_text(ui, &bot, &text, thread);+ show_files(ui, in_thread);+ send_text(ui, &bot, &text, thread, files);}/// Sends a message with a local echo that the host's copy replaces.-pub fn send_text(ui: &App, bot: &str, text: &str, thread: Option<String>) {+pub fn send_text(+ ui: &App,+ bot: &str,+ text: &str,+ thread: Option<String>,+ files: Vec<std::path::PathBuf>,+) {let nonce = uuid::Uuid::new_v4().to_string();+ let attachments: Vec<Value> = files+ .iter()+ .map(|p| {+ let size = std::fs::metadata(p).map_or(0, |m| m.len());+ json!({"name": p.file_name().map(|n| n.to_string_lossy()), "size": size})+ })+ .collect();upsert(&mut ui.state.borrow_mut(),json!({"id": format!("local-{nonce}"), "seq": i64::MAX, "botId": bot, "threadId": thread, "rev": 0, "kind": "user", "turn": 0,- "data": {"text": text, "status": "sending", "clientNonce": nonce}, "createdAt": now_ms(), "updatedAt": 0}),+ "data": {"text": text, "status": "sending", "clientNonce": nonce, "attachments": attachments},+ "createdAt": now_ms(), "updatedAt": 0}),);schedule(ui);let mut body = json!({"botId": bot, "text": text, "clientNonce": nonce});@@ -1675,7 +1834,10 @@ pub fn send_text(ui: &App, bot: &str, text: &str, thread: Option<String>) {body["threadId"] = t.into();}let (ui2, bot) = (ui.clone(), bot.to_owned());- client::call("send", body, move |r| {+ let done = move |r: Result<Value, String>| {+ if let Err(err) = &r {+ toast(&ui2, err);+ }let mut st = ui2.state.borrow_mut();match r {Ok(v) => upsert(&mut st, v["entry"].clone()),@@ -1691,7 +1853,12 @@ pub fn send_text(ui: &App, bot: &str, text: &str, thread: Option<String>) {}drop(st);schedule(&ui2);- });+ };+ if files.is_empty() {+ client::call("send", body, done);+ } else {+ client::send_files(body, files, done);+ }}pub fn now_ms() -> i64 {diff --git a/apps/macos/Views/ChatWindow.swift b/apps/macos/Views/ChatWindow.swiftindex a5c79045..647ab5bb 100644--- a/apps/macos/Views/ChatWindow.swift+++ b/apps/macos/Views/ChatWindow.swift@@ -119,6 +119,7 @@ private struct ChatSplitView: View {@State private var hoveredFooter: String?@FocusState private var searchFocused: Bool@FocusState private var profileFocused: Bool+ @AppStorage("hiddenComputers") private var hiddenComputers = ""@AppStorage("sidebarCompact") private var compact = false@AppStorage("desktopSidebarWidth") private var sidebarWidth = 296.0@State private var dragStartWidth: Double?@@ -131,10 +132,20 @@ private struct ChatSplitView: View {private var accounts: AccountStore { host.accounts }/// Every computer with a store, in the account's order.private var stores: [BotStore] { accounts.computers.compactMap { accounts.store(for: $0.id) } }- private var onlineStores: [BotStore] { stores.filter { $0.connection == .online } }+ private var onlineStores: [BotStore] { stores.filter { shownIDs.contains($0.computer.id) && $0.connection == .online } }private var selectedStore: BotStore? { accounts.selection.flatMap { accounts.store(for: $0.computerId) } }private var composeStore: BotStore? { composeComputer.flatMap { accounts.store(for: $0) } }- private var showsComputers: Bool { stores.count > 1 && !compact }+ private var shownIDs: Set<ComputerID> {+ Set(ComputerSelection(all: accounts.computers.map(\.id), hidden: hiddenComputers).shown)+ }+ private var visibleRoster: [RosterItem] {+ let query = search.trimmingCharacters(in: .whitespacesAndNewlines)+ return accounts.roster.filter { item in+ shownIDs.contains(item.ref.computerId) && (compact || query.isEmpty+ || item.bot.name.localizedCaseInsensitiveContains(query)+ || (item.bot.lastMessage?.localizedCaseInsensitiveContains(query) ?? false))+ }+ }private func ref(_ bot: Bot, _ store: BotStore) -> BotReference {BotReference(accountId: accounts.accountId, computerId: store.computer.id, botId: bot.id)@@ -148,8 +159,9 @@ private struct ChatSplitView: View {var body: some View {HStack(spacing: 0) {VStack(spacing: 0) {- HStack {- Spacer()+ HStack(spacing: 6) {+ ComputerFilterHeader(accounts: accounts, hidden: $hiddenComputers) { showComputers = true }+ Spacer(minLength: 0)IconButton("New chat", systemImage: "plus", action: compose).keyboardShortcut("n").disabled(onlineStores.isEmpty)@@ -160,21 +172,23 @@ private struct ChatSplitView: View {.opacity(compact ? 0 : 1).allowsHitTesting(!compact).accessibilityHidden(compact)+ if compact {+ ComputerFilterHeader(accounts: accounts, hidden: $hiddenComputers, compact: true) { showComputers = true }+ .frame(width: 70)+ }ScrollView {LazyVStack(spacing: 2) {- ForEach(stores, id: \.computer.id) { store in- let bots = filteredBots(store)- if showsComputers && !(bots.isEmpty && !search.isEmpty) {- ComputerHeader(store: store, ssh: host.isSSH(store.computer.id))+ ForEach(visibleRoster) { item in+ if let store = accounts.store(for: item.ref.computerId) {+ row(item.bot, store)}- ForEach(bots) { bot in row(bot, store) }}}.padding(.horizontal, 12).padding(.top, 4)}.onMoveCommand { direction in- let refs = stores.flatMap { store in filteredBots(store).map { ref($0, store) } }+ let refs = visibleRoster.map(\.ref)guard direction == .up || direction == .down, !refs.isEmpty else { return }let current = refs.firstIndex { $0 == accounts.selection } ?? -1let next = direction == .down ? min(current + 1, refs.count - 1) : max(current - 1, 0)@@ -186,16 +200,13 @@ private struct ChatSplitView: View {if !compact {VStack(spacing: 4) {searchField- ForEach(stores, id: \.computer.id) { store in- ConnectionBanner().environment(store).padding(.horizontal, 12)- }}.frame(width: sidebarWidth).transition(.opacity)}}.overlay {- if stores.allSatisfy({ filteredBots($0).isEmpty }) && !compact {+ if visibleRoster.isEmpty && !compact {VStack(spacing: 8) {Text(search.isEmpty ? "No bots yet" : "No matching bots").font(.system(size: 13, weight: .medium))@@ -338,8 +349,10 @@ private struct ChatSplitView: View {}.codyncSheet(isPresented: Binding(get: { marketplace != nil }, set: { if !$0 { marketplace = nil } })) {if let store = marketplace.flatMap(accounts.store(for:)) {- MarketplaceView()+ MarketplaceView(computers: onlineStores.map { ($0.computer.id, $0.hostName) },+ computer: Binding(get: { store.computer.id }, set: { marketplace = $0 })).environment(store)+ .id(store.computer.id).frame(width: min(920, windowSize.width - 80), height: sheetHeight)}}@@ -447,15 +460,6 @@ extension ChatSplitView {}}- fileprivate func filteredBots(_ store: BotStore) -> [Bot] {- let query = search.trimmingCharacters(in: .whitespacesAndNewlines)- if compact { return store.roster }- return store.roster.filter {- query.isEmpty || $0.name.localizedCaseInsensitiveContains(query)- || ($0.lastMessage?.localizedCaseInsensitiveContains(query) ?? false)- }- }-fileprivate var searchField: some View {HStack(spacing: 6) {Image(systemName: "magnifyingglass").foregroundStyle(Palette.secondary)@@ -620,7 +624,7 @@ extension ChatSplitView {fileprivate func compose() {// The selected bot's computer if it's online, else this Mac, else any online one.- let target = [selectedStore, host.store].compactMap { $0 }.first { $0.connection == .online } ?? onlineStores.first+ let target = [selectedStore, host.store].compactMap { $0 }.first { shownIDs.contains($0.computer.id) && $0.connection == .online } ?? onlineStores.firstguard let target else { return }if !composing { previousSelection = accounts.selection }composeComputer = target.computer.id@@ -657,11 +661,6 @@ extension ChatSplitView {.buttonStyle(IconButtonStyle(size: 36))Button { showAccount.toggle() } label: {profileAvatar- .overlay(alignment: .bottomTrailing) {- Circle().fill(host.store?.connection == .online ? Palette.switchOn : Palette.tertiary)- .frame(width: 7, height: 7)- .overlay(Circle().stroke(Palette.surface, lineWidth: 1.5))- }.frame(width: 44, height: 44).background(showAccount ? Palette.bubbleAgent : .clear, in: RoundedRectangle(cornerRadius: 12)).contentShape(Rectangle())diff --git a/apps/macos/Views/ComputersView.swift b/apps/macos/Views/ComputersView.swiftindex e201afda..bec333d8 100644--- a/apps/macos/Views/ComputersView.swift+++ b/apps/macos/Views/ComputersView.swift@@ -4,30 +4,6 @@ import CodyncUIimport SwiftUIimport UniformTypeIdentifiers-/// A computer's name over its bots in the sidebar, with how it's reached.-struct ComputerHeader: View {- let store: BotStore- let ssh: Bool-- var body: some View {- HStack(spacing: 6) {- ComputerBadge(store.computer, size: 16)- Text(store.hostName).font(.system(size: 11, weight: .semibold)).lineLimit(1)- RouteLabel(store: store, ssh: ssh)- Spacer()- if store.connection != .online {- Text(store.statusText).font(.system(size: 11)).foregroundStyle(store.isOffline ? Palette.warning : Palette.tertiary)- }- }- .foregroundStyle(Palette.secondary)- .padding(.horizontal, 8)- .padding(.top, 10)- .padding(.bottom, 2)- .accessibilityElement(children: .combine)- .accessibilityAddTraits(.isHeader)- }-}-/// How this Mac reaches a computer: itself, an SSH tunnel, direct LAN or the encrypted relay.struct RouteLabel: View {let store: BotStorediff --git a/apps/shared/ComputerStatus.swift b/apps/shared/ComputerStatus.swiftindex d11fc1cd..b247a75d 100644--- a/apps/shared/ComputerStatus.swift+++ b/apps/shared/ComputerStatus.swift@@ -31,23 +31,3 @@ struct RouteIcon: View {}}}--/// "MacBook · Online ☁︎": which computer a bot lives on and how that computer is doing.-struct ComputerCaption: View {- let store: BotStore-- var body: some View {- HStack(spacing: 4) {- ComputerBadge(store.computer, size: 14)- Text(store.hostName).lineLimit(1)- if store.connection != .online {- Text("·")- Text(store.statusText).foregroundStyle(store.isOffline ? Palette.warning : Palette.tertiary)- }- if store.connection == .online { RouteIcon(route: store.hostRoute).imageScale(.small) }- }- .font(.caption2)- .foregroundStyle(Palette.tertiary)- .accessibilityElement(children: .combine)- }-}diff --git a/docs/README.md b/docs/README.mdindex 11d42c52..6e500c73 100644--- a/docs/README.md+++ b/docs/README.md@@ -22,9 +22,12 @@ Source review, a passing build, local integration tests and production acceptanc- [Group chats and reply threads](features/groups-and-threads.md)- [Bot-to-bot collaboration](features/bot-collaboration.md)- [Context and memory](features/context-and-memory.md)+- [Bot workspaces](features/bot-workspaces.md)- [Voice calls](features/voice-call.md)+- [File attachments](features/file-attachments.md)- [Remote screen](features/remote-screen.md)- [Marketplace and agent setup](features/marketplace.md)+- [Connector setup and credentials](features/connector-credentials.md)- [Widgets, Live Activities and onboarding](design/mobile-widgets.md)- [Notifications and background Live Activity updates](design/push-and-live-activity.md)diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex b0596f0c..417cafda 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -2,13 +2,15 @@## iPhone navigation-The bot list and conversation use the system `NavigationStack` toolbar. `ToolbarItem` owns the account, computer, new-chat, call and more buttons; menus opened from these toolbar buttons (New, the computer filter) are native `Menu`s, because the bar hosts its items outside SwiftUI's layout and `.codyncMenu` can't anchor to them; the conversation uses the system back button. iOS supplies Liquid Glass, control sizing, grouping and interaction feedback.+The bot list and conversation use the system `NavigationStack` toolbar. `ToolbarItem` owns the account button, centered computer status/filter menu, and new-chat button. Computer management is inside the centered menu. The conversation copies Grok Bot: the title pill is a native `Menu` (details and the bot's actions), the only trailing button is the computer (remote screen; it pulses while this bot operates the screen), and the call button sits in the composer as a filled waveform capsule while the box is empty. Menus opened from toolbar buttons (New, the computer filter, the title) are native `Menu`s, because the bar hosts its items outside SwiftUI's layout and `.codyncMenu` can't anchor to them; the conversation uses the system back button. iOS supplies Liquid Glass, control sizing, grouping and interaction feedback.++The conversation hides the navigation bar background and the top scroll-edge effect, keeping the native glass buttons over the chat. Root error dialogs use an in-place, full-screen scrim so presenting them does not change the underlying glass controls' appearance.Do not wrap those toolbar controls in `IconButtonStyle`, hand-sized rounded backgrounds or another glass effect. The account avatar is toolbar content, with the system supplying the enclosing surface. This is the explicit exception to the custom-chrome rule below.-`ConnectingIndicator` is in the toolbar center and remains visible for at least 0.7 seconds after appearing. Transient connecting state is omitted from `ConnectionBanner`, so it does not insert/remove loading content above the bot rows or composer. Actionable offline/authorization warnings remain separate. This does not remove the normal pull-to-refresh interaction.+Connecting and reconnecting are background work. `BotStore` gives initial offline reports 1 second to recover and holds drops from online (including relay "computer offline" reports) for 5 seconds. "No access" shows immediately. Automatic read acknowledgements never open an error dialog and visible conversations are acknowledged again after reconnecting. The iOS app disconnects only in `.background`, not `.inactive`. Connection status lives only in headers and their menus. The roster header shows a small summary (`1 connected`, `1/2 connected`, `2 offline`, or `Connecting…`). Its computer menu supports multiple selections, Show only, All computers, reconnect, and management. At least one available computer stays selected; if saved exclusions would hide every computer, the list falls back to all. Filters persist on the device. Bots sort pinned first, then by recency. On iPhone, when more than one computer is shown, each computer gets a light heading (badge, name, connection, and "No bots yet" when empty) above its own bots; with one computer the list stays flat. Long-press a heading and drag it onto another computer's section to reorder computers (VoiceOver: Move up / Move down); the order is saved on the device (`AccountStore.move`). The Mac shows a flat roster. There are no connection banners. The compact Mac rail uses a computer icon for the same menu. Conversation headers show a small connection label, with the computer name available in the header menu or help text. Pull-to-refresh remains available on iPhone. Computer setup and access requests live under Manage computers.-Sources: `apps/ios/Views/BotListView.swift`, `AccountSwitcherView.swift`, `kit/Sources/CodyncUI/Thread/ThreadView.swift`, `Chrome.swift`, `Bots/BotRow.swift`.+Sources: `apps/ios/Views/BotListView.swift`, `AccountSwitcherView.swift`, `kit/Sources/CodyncUI/Thread/ThreadView.swift`, `Bots/ComputerFilterHeader.swift`, `Store/ComputerSelection.swift`, `Bots/BotRow.swift`.## macOS menu bar@@ -46,10 +48,20 @@ Provider identity and activity presentation are shared in `CodyncKit/Design`; usThe [2026-09-25 audit](../archive/ui-audit-2026-09-25.md) is historical. Its old line numbers and recommendations are not the current UI policy or a list of confirmed open bugs.-Model discovery keeps loading and refresh in one fixed-size slot beside the Model picker. Refresh retains the current catalog while loading, and loading does not add a separate row to the settings card.+Model discovery keeps loading and refresh in one fixed-size slot beside the Model picker. Refresh retains the current catalog while loading, and loading does not add a separate row to the settings card. The Model label keeps its intrinsic width; the model picker takes the remaining width and truncates long names, with the full name available in its tooltip and menu.## macOS conversation detailsThe details inspector uses a compact device summary instead of an empty screen preview. Keep the computer name, remote-screen state, and iPhone hint together; show the hint only when screen capture is ready. Use 16-point horizontal insets, 28-point section gaps, and 12-point corner radii on flat surfaces, without borders.-Routines use a short empty state with one setup action and an icon action for asking in chat. Populated lists move the add action into the section header. Agent metadata uses explicit Runtime and Working folder labels; paths remain selectable and wrap. Keep status and section headings readable in both appearances through `Palette`.+Routines use a short empty state with one setup action and an icon action for asking in chat. Populated lists move the add action into the section header. Agent metadata uses Runtime and Workspace labels for personal bots, or Project folder for explicitly configured projects; project paths remain selectable and wrap. Personal workspace paths stay out of the default details UI. Keep status and section headings readable in both appearances through `Palette`.++New bots use automatically allocated personal workspaces. Settings offer Personal or an optional project folder; see [bot workspaces](../features/bot-workspaces.md).++Shared `.codyncMenu` lists scroll vertically when their content exceeds 420 points or the available space beside the trigger. Menus open toward the side with more vertical room; short lists keep their content height. Menu width is capped at 320 points and constrained to the window, and long option titles remain available through help text. This applies to Agent, Model, and other shared choice menus on macOS. On iOS, `DropdownMenu` and `ChoicePicker` present the native `Menu` instead (choices as checkmarked toggles), because an overlay anchored by global frame lands in the wrong place inside `.codyncSheet` and scroll views. Each computer has its own marketplace; its header names the computer and, with several online, switches between them. A new bot's editor on iPhone has a Computer dropdown listing every online computer, even when there is only one; switching it resets the folder, model and connectors that belonged to the old computer.++## Reading conversations++A visible conversation registers its own read scope while its scene is active. New chat-visible entries (including final updates to an existing message ID) and later roster unread updates acknowledge that scope through the host. Opening the view, returning to the foreground, and reconnecting also acknowledge it. Never gate a receipt on the cached unread count: entry and roster events can arrive separately. Replies acknowledge only their own thread; leaving a view or backgrounding the scene unregisters it. The host remains authoritative and broadcasts the resulting unread state to all clients.++The iPhone conversation navigation title includes a compact second line with the connection label and the current connection route icon: cloud for Cloudflare, Wi-Fi for direct Wi-Fi/Tailscale. It follows the live route, not the preferred route setting; offline and reconnecting states replace the route icon. VoiceOver also reads the connection description.diff --git a/docs/features/bot-workspaces.md b/docs/features/bot-workspaces.mdnew file mode 100644index 00000000..ca7183d6--- /dev/null+++ b/docs/features/bot-workspaces.md@@ -0,0 +1,23 @@+# Bot workspaces++New agent bots get a personal, persistent workspace automatically. Creating a bot does not require choosing a project. An omitted or empty `cwd` in `createBot` allocates `<CODYNC_HOME>/bots/<bot-id>/workspace` (normally `~/.codync/bots/<bot-id>/workspace`). Groups do not allocate folders.++The host persists the resolved absolute directory in `cwd` and exposes `managedWorkspace` in bot responses. Empty `cwd` in `updateBot` selects the same bot's personal workspace again. Existing explicit project directories remain unchanged, must already exist, and can still be selected in settings. Templates for personal bots send an empty cwd so a new bot gets its own directory.++## Task execution++The configured directory is the agent process and ACP session's starting directory. The bot's instructions explain that it can use explicit paths or change directory for an individual command when a task concerns another folder. This does not modify bot configuration or reset the conversation. Access remains subject to the harness's permissions; a personal folder is not a sandbox and does not grant additional access.++Routines, threads, and group contributions use their owner's configured starting directory. Task-specific paths should be explicit in routine instructions. The host does not infer a task directory from the last chat message. Harness-specific restrictions can still require user approval for other paths.++Changing the default project in settings deliberately reconfigures the agent session, as before. This is separate from executing a task in another directory.++## Lifecycle++- Renaming a bot or changing its model does not move or erase workspace files.+- Restarting the host or starting a new conversation context preserves the directory.+- Switching to a project and back reuses the personal workspace.+- Deleting a bot leaves its workspace files on disk. There is no automatic cleanup.+- Existing bots are not silently moved out of their configured project directories.++Swift settings offer Personal or Choose project folder; desktop quick creation and the terminal's new-bot flow default to Personal. Directory selection is optional. Separate workspaces do not prevent conflicts when multiple bots edit the same external project; automatic Git worktrees are not implemented here.diff --git a/docs/features/connector-credentials.md b/docs/features/connector-credentials.mdnew file mode 100644index 00000000..fe3c8633--- /dev/null+++ b/docs/features/connector-credentials.md@@ -0,0 +1,89 @@+# Connector setup and credentials++Codync uses one host-owned connection workflow on iOS, macOS and Linux. A+Marketplace installation and a bot's connection request use the same installation,+OAuth and verification endpoints. The clients never implement a separate password+store. A phone submits credentials through its authenticated encrypted channel to+its selected host.++## Storage++`market/vault.rs` encrypts sensitive records with XChaCha20-Poly1305, a random+24-byte nonce and the record key as authenticated associated data. A random+256-bit key belongs to this host database's random vault ID. It is held by the OS:++- macOS: Keychain, via the native keyring backend.+- Linux: freedesktop Secret Service over the user's session D-Bus, with encrypted+ transport and a vendored D-Bus client. GNOME Keyring or another compatible+ unlocked Secret Service is required. Run the host in that user's session.+- Headless Linux: provide a session D-Bus and unlocked Secret Service for the+ service user. An unavailable keyring gives an actionable error. There is no+ plaintext, kernel-keyring-only or automatic ephemeral fallback.++Unlocking runs on a blocking worker. The key is cached in zeroizing memory until+host exit. Locking the desktop keyring after unlock does not evict that cache;+stop the host to remove it. The implementation does not claim to isolate secrets+from arbitrary code running as the same OS user.++Encrypted records include connector environment, headers, command arguments and+OAuth tokens, the Composio config, agent API-key environment, and the optional+1Password service-account token. Existing records migrate on their first read+with an available key. Missing keys and corrupt ciphertext are errors, never an+empty replacement configuration. SQLite secure deletion is enabled; historical+backups and preexisting WAL/filesystem snapshots can still contain older data.+Back up the OS credential store together with the database. A database copied to+another machine without its key cannot decrypt credentials. There is no automatic+cross-host or cloud-account credential sharing.++## Execution boundary++ACP receives local connector proxy commands with an empty environment, rather+than credential values. The proxy gets its configuration through authenticated,+loopback-only `connectorRuntime` and injects values into the connector process.+Remote connectors use the existing host OAuth proxy. General listings omit secret+values and command arguments. The local API token and same-user host access are+trusted capabilities; this is not a sandbox against the agent's own shell tools.++A readiness check starts the connector, performs MCP initialize and tools/list,+and stops the check process. It never invokes a business tool. Failures and a+90-second timeout remain visible and retryable. Package acquisition is performed+by the configured runtime (npx, uvx, Docker, etc.), so that runtime must be present.++## Conversation requests++The built-in `connectors` MCP offers search_connectors, list_connectors,+request_connection, request_app (Composio), and request_secret. Requests become+notice entries with structured connectionRequest data. They identify the requesting+bot, service, destination field, purpose and status; they contain no credentials.++Clients submit values through connectorRequestFinish. The host validates the+request, destination, requesting bot and 24-hour expiry, stores credentials,+verifies availability, enables the connector for that bot, and queues a non-secret+acknowledgement in the original conversation/thread. Repeated completed submissions+return the completed entry. Cancelled requests reject submissions. Verification+failures remain pending so the user can correct credentials and retry.++MCP connection requests and runtime secret retrieval are loopback-only. Authorized+Control devices may submit or cancel requests. No endpoint exposes a generic+credential getter to a device. Existing local-process trust boundaries still apply.++## Optional 1Password++Credentials settings accepts a service-account token and checks it using the+installed `op` CLI. Use a dedicated vault and grant the service account access only+to that vault. Codync does not create a 1Password account or vault automatically.++Use an `op://vault/item/field` reference as an environment value or complete header+value. The host resolves it when verifying/launching a local connector or preparing+a remote request. The token goes in the child environment, not command arguments;+output is consumed by the host and errors do not echo provider secret values.+Disconnecting removes the active token; connectors using references then require+reconnection. OAuth remains the preferred flow for services that support it.++## Validation++Host tests cover authenticated encryption, record substitution, plaintext migration,+locked storage, secure request completion, retry idempotency, cancellation and+failed verification. The ignored platform_keyring_roundtrip test is for an actual+unlocked OS credential store. Run it explicitly in a disposable Secret Service+session on Linux or the macOS login keychain.diff --git a/docs/features/file-attachments.md b/docs/features/file-attachments.mdnew file mode 100644index 00000000..3663c3d4--- /dev/null+++ b/docs/features/file-attachments.md@@ -0,0 +1,31 @@+# File attachments++Photos and files sent with a message, from the iPhone and the Mac.++- Composer: the **+** button left of the message box. iPhone: a menu with Photos (sent as JPEG) and+ Files (plus Paste when the clipboard has an image); Mac: an open panel. Files and images can+ also be dropped on the box or pasted: ⌘V on the Mac takes a copied image or file, and on the+ iPhone a "Paste image" chip appears above the box while typing after an image was copied.+ HEIC/TIFF/BMP become JPEG (`OutgoingFile.prepared`, `Thread/Attachments.swift`). Picked files show as chips above+ the text and can be removed; a message can be files only. Not in group chats (a group has no+ folder of its own). Up to 100 MB per file.+- Upload: `upload {botId, uploadId, name, offset, data (base64), done}`, 384 KiB per call so each+ stays under the channel's 1 MiB message limit. A repeated chunk is accepted (retry); anything out+ of order is refused. Then `send {…, attachments: [uploadId]}`; the text may be empty.+- Storage (`host/src/chat/uploads.rs`): `<workspace>/uploads/<uploadId>/<name>` for a personal+ workspace (so reading needs no extra approval), otherwise+ `~/.codync/bots/<bot>/uploads/<uploadId>/<name>`. Only UUID ids and plain file names are accepted.+- The agent gets the message text plus an "Attached files" list of absolute paths and reads them with+ its own tools (Claude and Codex read images too). The entry keeps `attachments: [{id, name, size}]`+ for display.+- Files don't go through the relay mailbox: while the computer is offline, a message with files+ waits in the composer's send button (disabled) instead. A failed send keeps its files on the device+ for Resend until the app quits.+- Chat: images show as pictures (tap for full size), other files as cards. Other devices fetch a+ sent file with `readUpload {botId, uploadId, offset}` (384 KiB chunks) and cache it; the sender+ caches its own copy at upload.+- Linux app: the paperclip in the composer (file chooser) or files dropped on the box; sent files+ show as name/size cards (no image previews yet). Terminal UI: dragging a file onto the terminal+ pastes its path, which becomes an attachment (⌫ on an empty draft removes the last one); sent+ files show as `▤ name size` lines. Both upload with the same `upload` chunks.+- A files-only message previews in the roster as its file names.diff --git a/docs/features/marketplace.md b/docs/features/marketplace.mdindex 1810f7fd..61c01470 100644--- a/docs/features/marketplace.md+++ b/docs/features/marketplace.md@@ -9,7 +9,11 @@ The Plugins screen configures capabilities installed on the selected computer. A| Connected apps | `host/src/market/composio.rs` | Expose connected Composio apps as connectors || Skills | `host/src/market/mod.rs` | Instruction folders containing `SKILL.md`, stored under `~/.codync/skills/<id>` |-An enabled connector is passed to the agent as an MCP server when its session starts or resumes. Local connectors are spawned by the agent; remote ones always go through the host's stdio proxy (`codync-host mcp remote`, `host/src/mcp.rs`), so they work with agents that only speak stdio and always carry a fresh token.+The Connectors shelf opens with a short featured list, then pages through the whole MCP Registry (`marketConnectors {search, cursor}` → `{items, nextCursor}`, 60 metadata records per API page; the UI initially shows 12 and reveals another 12 only when *Load more connectors* is pressed). Apps through Composio use the same 12-at-a-time display with *Load more apps*. Searching resets the visible batch; late responses from an older search are ignored. Scrolling never triggers another catalog fetch. Listed: stdio npm/PyPI/OCI/NuGet packages (the registry's runtime and package arguments become inputs) and streamable-HTTP or SSE remotes (URL `{variables}` become inputs). Not listed: MCPB bundles and packages that serve HTTP locally; add those as a custom connector.++A custom connector is a command line (split like a shell), a URL, or a pasted MCP config (`importConnectors {config}`: the `mcpServers` / `servers` JSON from READMEs, Claude, Cursor or VS Code, or one server's entry); every server in a config is added.++An enabled connector is passed to the agent as an MCP server when its session starts or resumes. Local connectors are spawned by the agent; remote ones always go through the host's stdio proxy (`codync-host mcp remote`, `host/src/mcp.rs`), so they work with agents that only speak stdio and always carry a fresh token. The proxy speaks streamable HTTP and falls back to the older HTTP+SSE transport when the first POST fails with 400/404/405, as the MCP spec suggests.## Sign-in for remote connectors (`host/src/market/oauth.rs`)@@ -37,3 +41,10 @@ The shared bot editor requests `agentModels {backend}` from the selected computeDiscovery prefers ACP `configOptions` with category `model` (including grouped options), with conventional `model`/`models` IDs as a compatibility fallback. Older agents may expose `models.availableModels`. Model names and IDs come from the agent; Codync does not bundle a provider catalog. See the [ACP config option contract](https://agentclientprotocol.com/protocol/v1/session-config-options).The editor keeps Default, shows available models in a dropdown, and resets the selected model when changing agents. Errors are visible and retryable. Custom commands and agents without model discovery retain manual ID entry; an existing unlisted ID is preserved. The probe uses an isolated directory, so project-specific agent configuration can differ from the real bot session. Changing the model restarts the bot's agent sessions with fresh model context and preserves the stored chat history. The agent remains responsible for validating availability when a session starts.++## Secure connection setup++See [Connector setup and credentials](connector-credentials.md) for the shared+macOS/Linux vault, optional 1Password references, in-chat connection requests and+MCP readiness checks. Single-option connectors without setup fields start adding+immediately; setup failures remain visible for retry.diff --git a/docs/features/routines.md b/docs/features/routines.mdindex 39012057..ee70da49 100644--- a/docs/features/routines.md+++ b/docs/features/routines.md@@ -13,8 +13,9 @@ open the routine.The editor keeps task fields first, followed by trigger choices and their settings.Trigger choices use adaptive columns, selected checkmarks and short descriptions.-Inputs use the shared palette with a visible filled surface. Interval input also-shows its duration in words. Run timeout is under an animated Run settings+Inputs use the shared palette with a visible filled surface. New recurring schedules+default to cron; the frequency controls send form values to the host, which returns a five-field+expression and an explicit IANA time zone. Run timeout is under an animated Run settingsexpansion. A fixed footer keeps Create routine / Save changes and inline errorsvisible while the form scrolls; it explains the local execution requirement.The layout uses the same light/dark tokens, type family and custom controls as the@@ -119,7 +120,8 @@ All normal methods use the existing authenticated host API / authorized E2E chan| Method | Body ||---|---|| `routines` | `botId` |-| `saveRoutine` | `botId`, optional `id`, `name`, `instruction`, `triggers`, optional `enabled`, `timeoutSeconds` |+| `routineSchedule` | `triggers` + preferred `timeZone` to load, or `draft` to preview; returns hydrated form, validated triggers, summary, warning, next run |+| `saveRoutine` | `botId`, optional `id`, `name`, `instruction`, `schedule` form or `triggers`, optional `enabled`, `timeoutSeconds` || `setRoutineEnabled` | `botId`, `id`, `enabled` || `deleteRoutine` | `botId`, `id` || `runRoutine` | `botId`, `id` |@@ -193,9 +195,13 @@ the routine by name. No reference routine was run, paused or deleted during thiscomparison.Codync retains that compact sidebar and the chat-based setup path, while providing-a direct editor. Common calendar schedules use Daily / Weekdays / Weekly with a-time control; Custom retains raw cron. Intervals use seconds, minutes, hours or-days. Editing hydrates the original schedule, timezone and interval exactly;+a direct editor. Calendar schedules offer minute frequencies, hourly, daily, weekdays, weekly,+selected weekdays, monthly and custom cron. The clock uses separate hour/minute+controls with every minute available and quick 09:00 / 12:00 / 18:00 choices.+Selected weekdays support multiple days. The summary shows the clock time and+zone, with the generated expression available on expansion. Switching to Custom+starts from that expression. Monthly days 29–31 explain that shorter months are+skipped. Existing duration intervals keep their cadence until explicitly replaced. Editing hydrates the original schedule, timezone and interval exactly;compound and provider-event triggers retain a lossless Keep existing triggersfallback. Expired one-shot timestamps are preserved when editing other fields.@@ -215,3 +221,59 @@ confirmed one updated routine with `0 9 * * 1-5` and `enabled: false`. Edit withbot populated an unsent draft with the routine ID. The test bot and workingdirectory were removed. Screenshots are in `build/routine-usability-calendar.jpeg`and `build/routine-usability-details.jpeg`.++## Cron scheduling contract++All newly configured recurring schedules in the Apple editor use `cron` and run+through the host's existing Croner scheduler. Minute presets divide an hour evenly+(1, 5, 10, 15, 20, 30); hourly schedules choose an exact minute. Cron generation, parsing, validation, timezone checks, descriptions and next-run+calculation all live in `host/src/routines/editor.rs` and `schedule.rs`. The Swift+draft is only a Codable form DTO. The editor debounces preview requests, discards+stale responses, shows host errors and disables Save until the current draft is+validated. Save sends the form to the host, which independently compiles and+validates it again. Both direct trigger API calls and Bot MCP calls use the same+host scheduler. Run timeout text is also parsed and validated by the host.+The built-in agent instructions also select cron for recurring clock schedules.++Existing elapsed-duration intervals remain readable/editable without silently+changing their execution times. An interval anchored to creation time cannot be+converted to a wall-clock cron without changing its cadence. One-time schedules+retain their absolute timestamp: five-field cron has no year or run-count guard.+Webhook/event triggers remain event-driven. These paths are intentionally not+misrepresented as cron. The host must still be running and awake.++Rust regression tests cover default cron creation, preset round trips, arbitrary+minute selection, timezone validation, custom expression preservation, existing+interval and expired one-shot preservation, and next occurrences across month+boundaries. An isolated HTTP integration test previews, saves and reloads the same+form and verifies direct saves reject invalid drafts. Swift tests cover wire DTO+decoding and millisecond date binding; there is no Swift cron implementation.+++### macOS selection checks++The calendar editor uses shared choice menus. Nested menus become the active+accessibility surface above the editor; Escape dismisses the top overlay through+its own close binding. This keeps menu interaction separate from closing the+routine editor. Schedule rules remain on the host; these are presentation rules.+++Verified on the installed Mac build through Computer Use on 2026-09-27:++- Opened a saved Monday/Wednesday/Friday schedule at 14:47 in Asia/Taipei.+- Switched to Custom and observed the host-generated `47 14 * * 1,3,5`.+- Entered minute 61; the server error appeared and Save was disabled.+- Selected minute 23 through the scrollable menu, saved, and reopened. Both the+ UI and API retained `23 14 * * 1,3,5` and the paused state.+- Selected monthly day 31; the warning and October 31 next occurrence appeared.+- Selected every 15 minutes and hourly at minute 23; both displayed host previews.+- Verified Escape closes the top menu and preserves the editor and form values.+- Verified the minute menu opens scrolled to the current selection. Its selection+ stays visible instead of starting at 00.++The temporary bot and paused routine were removed after checking. Screenshots:+`build/cron-verification/calendar-fields.png` and `minute-selection.png`.+Validation: 52 Swift tests, 12 Rust routine unit tests, the isolated HTTP editor+integration test, Rust Clippy with warnings denied, and signed macOS/iOS Debug+builds passed. iPhone received the updated build; its final relaunch was blocked+by the device lock. This GUI acceptance used macOS.diff --git a/docs/features/voice-call.md b/docs/features/voice-call.mdindex 016e7e82..91b45fb9 100644--- a/docs/features/voice-call.md+++ b/docs/features/voice-call.md@@ -1,32 +1,91 @@# Voice call-A hands-free call with one bot from the iPhone chat (phone icon in the header). The bot is the-same agent on the computer; the call only changes how you talk to it.+A hands-free call with one bot from the iPhone chat (the waveform button in an empty composer).+The bot is the same agent on the computer; the call only changes how you talk to it.## Implemented: on the phone-- `kit/Sources/CodyncUI/Call/`: `CallSession` (audio loop) + `CallView` (full-screen layer).-- Speech → text with `SFSpeechRecognizer` (on-device when the language supports it). A 1.5 s pause- ends an utterance and sends it as an ordinary message (`BotStore.send`), so it takes the normal- path: queued while the bot works, folded into its next turn.+- `kit/Sources/CodyncUI/Call/`: `CallSession` (audio loop) + `CallView` (the call bar).+- UI follows Grok Bot: a floating capsule over the top of the chat (`ThreadView` overlay), and the+ chat stays readable and usable underneath. Left to right: the bot's avatar (pulses while+ speaking; tap it to interrupt), a dotted level line (your voice while listening, a ripple while+ the bot speaks, a slow breath while it works), gear (call settings), mic (mute), red ✕ (end).+- Speech → text with `SFSpeechRecognizer` (on-device when the language supports it). A pause ends an+ utterance and sends it as an ordinary message (`BotStore.send`), so it takes the normal path:+ queued while the bot works, folded into its next turn. What you said appears in the chat as your+ message; the bot's reply appears as its message.- Each new final reply (`data.final`) is read aloud with `AVSpeechSynthesizer` in the reply's own- language; markdown and code blocks are dropped (`SpokenText`). The mic pauses while it speaks;- tapping the avatar interrupts. An approval request is announced, answered in the chat.-- The host receives recognized text; the Cloudflare transport sees encrypted channel frames. Codync does not forward microphone audio to the host. Speech recognition may use Apple services when on-device recognition is unavailable. `UIBackgroundModes: audio` keeps the call- alive with the screen locked.--## Proposal: cloud realtime voice (not implemented)--For better recognition (mixed Chinese/English, code terms) and a real conversation (barge-in,-"what are you doing?" answered from the transcript):--- A realtime speech model (OpenAI Realtime or Gemini Live) acts as the operator in front of the bot.- Its tools: send a message to the bot, read the bot's status and recent transcript. The coding is- still done by the bot's own agent.-- The phone connects to the provider directly (WebRTC). Our server only mints a short-lived client- token after checking the account's Pro entitlement and remaining minutes; audio never passes- through it, and the provider key never ships in the app.-- Bot traffic stays on the encrypted channel; only the voice part goes to the provider, which the- call screen states.-- Billing: App Store subscription (RevenueCat entitlement), a monthly minute cap enforced when- minting tokens.+ language; markdown and code blocks are dropped (`SpokenText`). The mic pauses while it speaks.+ An approval request is announced, answered in the chat.+- Gear: pause length before sending (1 / 1.5 / 2.5 s) and reading speed; kept on the phone.+- Ending the call calls `logCall {botId, seconds}`; the host adds a notice (`callSeconds`) that+ every client shows as "Voice chat · 00:16".+- The host receives recognized text; the Cloudflare transport sees encrypted channel frames.+ Codync does not forward microphone audio to the host. Speech recognition may use Apple services+ when on-device recognition is unavailable. `UIBackgroundModes: audio` keeps the call alive with+ the screen locked.++## Design: realtime voice with your own key (not implemented)++Better recognition (mixed Chinese/English, code terms) and a real conversation (barge-in, "what are+you doing?" answered from the transcript) need a realtime speech model. Users bring their own+provider key; Codync never resells minutes for it.++### Engines++The gear's first section becomes **Voice engine**:++| Engine | Needs | Transport |+| --- | --- | --- |+| On device (default) | nothing | what ships today |+| OpenAI Realtime | OpenAI API key | WebRTC, phone ↔ OpenAI |+| Gemini Live | Google AI Studio key | WebSocket, phone ↔ Google |++Picking a cloud engine without a key opens its key form: a secure field, a link to the provider's+key page, **Test** (one cheap authenticated call; shows "Key works" or the provider's error), and a+voice picker. The call bar shows the provider's small wordmark-free label ("OpenAI") next to the+dots whenever audio leaves the phone.++### Where the key lives++- On the iPhone only, in the Keychain (`kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`, not+ synced). It is never sent to the host, the relay or our cloud, and never written to logs.+- The long-lived key is used for one thing: minting a short-lived client credential at call start+ (OpenAI `POST /v1/realtime/client_secrets`, Gemini ephemeral auth tokens). The audio session only+ ever sees that credential.+- Rejected: key on the host with audio proxied through it. Audio would cross the encrypted channel+ and the relay (latency, relay bandwidth), and a Linux server host has no microphone reason to+ hold it.++### How the call works++The realtime model is an operator in front of the bot, not a replacement for it:++- Session instructions: who the bot is (name, description), that coding is done by the bot, reply+ in the user's language, keep spoken answers short.+- Tools the phone implements locally against `BotStore`: `send_to_bot(text)` (an ordinary message,+ same path as today), `bot_status()` (idle/working, activity line, pending approval),+ `recent_messages(count)` (chat-visible entries only), `answer_approval(option)` (only after the+ user said which).+- Each new final reply is pushed into the realtime conversation as a context item; the model speaks+ it (shortened for speech). Barge-in is the provider's own voice activity detection.+- The chat stays the record: only `send_to_bot` messages and the bot's replies are entries. The+ operator's small talk isn't saved; the call still ends with the "Voice chat" notice.++### Failure and cost++- Invalid key, quota or network failure at start → the call falls back to On device with a one-line+ notice under the bar; mid-call failure does the same without dropping the call.+- Usage is billed by the provider to the user. The gear shows minutes used this month (counted on+ the phone) next to the engine, as an estimate, not a bill.++### Code layout++- `kit/Sources/CodyncUI/Call/VoiceEngine.swift`: `protocol VoiceEngine` (start, end, mute,+ interrupt, `phase`, `level`, `onUserMessage`, `speak(reply:)`); `OnDeviceEngine` is today's+ `CallSession`; `OpenAIRealtimeEngine` (WebRTC, the app already links WebRTC for Remote screen)+ and `GeminiLiveEngine` (URLSessionWebSocketTask).+- `kit/Sources/CodyncKit/Client/VoiceKeys.swift`: Keychain storage + credential minting.+- `CallView` only talks to `VoiceEngine`; nothing on the host changes.+- A later Codync Pro plan can add a second credential source (our server mints the client token after+ checking the entitlement) behind the same engines.diff --git a/host/Cargo.lock b/host/Cargo.lockindex 5a0f001c..1e5d4d36 100644--- a/host/Cargo.lock+++ b/host/Cargo.lock@@ -9,7 +9,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"dependencies = ["crypto-common 0.2.2",- "inout",+ "inout 0.2.2",+]++[[package]]+name = "aes"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"+dependencies = [+ "cfg-if",+ "cipher 0.4.4",+ "cpufeatures 0.2.17",][[package]]@@ -101,6 +112,123 @@ dependencies = ["num-traits",]+[[package]]+name = "async-broadcast"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"+dependencies = [+ "event-listener",+ "event-listener-strategy",+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "async-channel"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"+dependencies = [+ "concurrent-queue",+ "event-listener-strategy",+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "async-io"+version = "2.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"+dependencies = [+ "autocfg",+ "cfg-if",+ "concurrent-queue",+ "futures-io",+ "futures-lite",+ "parking",+ "polling",+ "rustix",+ "slab",+ "windows-sys 0.61.2",+]++[[package]]+name = "async-lock"+version = "3.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"+dependencies = [+ "event-listener",+ "event-listener-strategy",+ "pin-project-lite",+]++[[package]]+name = "async-process"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"+dependencies = [+ "async-channel",+ "async-io",+ "async-lock",+ "async-signal",+ "async-task",+ "blocking",+ "cfg-if",+ "event-listener",+ "futures-lite",+ "rustix",+]++[[package]]+name = "async-recursion"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "async-signal"+version = "0.2.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"+dependencies = [+ "async-io",+ "async-lock",+ "atomic-waker",+ "cfg-if",+ "futures-core",+ "futures-io",+ "rustix",+ "signal-hook-registry",+ "slab",+ "windows-sys 0.61.2",+]++[[package]]+name = "async-task"+version = "4.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"++[[package]]+name = "async-trait"+version = "0.1.92"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "atomic-waker"version = "1.1.2"@@ -227,6 +355,28 @@ dependencies = ["hybrid-array",]+[[package]]+name = "block-padding"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"+dependencies = [+ "generic-array",+]++[[package]]+name = "blocking"+version = "1.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa"+dependencies = [+ "async-channel",+ "async-task",+ "futures-io",+ "futures-lite",+ "piper",+]+[[package]]name = "bumpalo"version = "3.20.3"@@ -254,6 +404,15 @@ dependencies = ["rustversion",]+[[package]]+name = "cbc"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"+dependencies = [+ "cipher 0.4.4",+]+[[package]]name = "cc"version = "1.4.7"@@ -285,7 +444,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"dependencies = ["cfg-if",- "cipher",+ "cipher 0.5.2","cpufeatures 0.3.1","rand_core 0.10.1",]@@ -298,7 +457,7 @@ checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"dependencies = ["aead","chacha20",- "cipher",+ "cipher 0.5.2","poly1305",]@@ -325,6 +484,16 @@ dependencies = ["phf",]+[[package]]+name = "cipher"+version = "0.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"+dependencies = [+ "crypto-common 0.1.7",+ "inout 0.1.4",+]+[[package]]name = "cipher"version = "0.5.2"@@ -333,7 +502,7 @@ checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"dependencies = ["block-buffer 0.12.1","crypto-common 0.2.2",- "inout",+ "inout 0.2.2",][[package]]@@ -410,8 +579,9 @@ dependencies = ["futures","gethostname","getrandom 0.4.3",- "hkdf",+ "hkdf 0.13.0","if-addrs",+ "keyring","pty-process","qrcode","ratatui",@@ -419,7 +589,8 @@ dependencies = ["rusqlite","serde","serde_json",- "sha2",+ "sha2 0.11.0",+ "shlex","tokio","tokio-stream","tokio-tungstenite",@@ -428,6 +599,7 @@ dependencies = ["unicode-width","uuid","x25519-dalek",+ "zeroize",][[package]]@@ -460,6 +632,15 @@ dependencies = ["static_assertions",]+[[package]]+name = "concurrent-queue"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"+dependencies = [+ "crossbeam-utils",+]+[[package]]name = "const-oid"version = "0.10.2"@@ -475,6 +656,16 @@ dependencies = ["unicode-segmentation",]+[[package]]+name = "core-foundation"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"+dependencies = [+ "core-foundation-sys",+ "libc",+]+[[package]]name = "core-foundation"version = "0.10.1"@@ -520,6 +711,12 @@ dependencies = ["strum 0.27.2",]+[[package]]+name = "crossbeam-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"+[[package]]name = "crossterm"version = "0.29.0"@@ -680,6 +877,36 @@ version = "2.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"+[[package]]+name = "dbus"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e"+dependencies = [+ "libc",+ "libdbus-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "dbus-secret-service"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6"+dependencies = [+ "aes",+ "block-padding",+ "cbc",+ "dbus",+ "fastrand",+ "hkdf 0.12.4",+ "num",+ "once_cell",+ "openssl",+ "sha2 0.10.9",+ "zeroize",+]+[[package]]name = "deranged"version = "0.5.8"@@ -747,6 +974,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = ["block-buffer 0.10.4","crypto-common 0.1.7",+ "subtle",][[package]]@@ -825,7 +1053,7 @@ checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"dependencies = ["curve25519-dalek","ed25519",- "sha2",+ "sha2 0.11.0","subtle","zeroize",]@@ -836,6 +1064,33 @@ version = "1.18.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"+[[package]]+name = "endi"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"++[[package]]+name = "enumflags2"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"+dependencies = [+ "enumflags2_derive",+ "serde",+]++[[package]]+name = "enumflags2_derive"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "equivalent"version = "1.0.2"@@ -852,6 +1107,26 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "event-listener"+version = "5.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"+dependencies = [+ "parking",+ "pin-project-lite",+]++[[package]]+name = "event-listener-strategy"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"+dependencies = [+ "event-listener",+ "pin-project-lite",+]+[[package]]name = "fallible-iterator"version = "0.3.0"@@ -864,6 +1139,12 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"+[[package]]+name = "fastrand"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"+[[package]]name = "fiat-crypto"version = "0.3.0"@@ -888,6 +1169,21 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"+[[package]]+name = "foreign-types"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"+dependencies = [+ "foreign-types-shared",+]++[[package]]+name = "foreign-types-shared"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"+[[package]]name = "form_urlencoded"version = "1.2.2"@@ -961,6 +1257,19 @@ version = "0.3.34"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"+[[package]]+name = "futures-lite"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"+dependencies = [+ "fastrand",+ "futures-core",+ "futures-io",+ "parking",+ "pin-project-lite",+]+[[package]]name = "futures-macro"version = "0.3.34"@@ -1097,13 +1406,43 @@ version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"+[[package]]+name = "hermit-abi"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"++[[package]]+name = "hex"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"++[[package]]+name = "hkdf"+version = "0.12.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"+dependencies = [+ "hmac 0.12.1",+]+[[package]]name = "hkdf"version = "0.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"dependencies = [- "hmac",+ "hmac 0.13.0",+]++[[package]]+name = "hmac"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"+dependencies = [+ "digest 0.10.7",][[package]]@@ -1392,6 +1731,16 @@ dependencies = ["rustversion",]+[[package]]+name = "inout"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"+dependencies = [+ "block-padding",+ "generic-array",+]+[[package]]name = "inout"version = "0.2.2"@@ -1522,6 +1871,21 @@ dependencies = ["thiserror",]+[[package]]+name = "keyring"+version = "3.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"+dependencies = [+ "dbus-secret-service",+ "log",+ "openssl",+ "secret-service",+ "security-framework 2.11.1",+ "security-framework 3.7.0",+ "zeroize",+]+[[package]]name = "lazy_static"version = "1.5.0"@@ -1534,6 +1898,16 @@ version = "0.2.189"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"+[[package]]+name = "libdbus-sys"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"+dependencies = [+ "cc",+ "pkg-config",+]+[[package]]name = "libm"version = "0.2.16"@@ -1638,6 +2012,15 @@ version = "2.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"+[[package]]+name = "memoffset"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"+dependencies = [+ "autocfg",+]+[[package]]name = "mime"version = "0.3.17"@@ -1657,19 +2040,95 @@ dependencies = [][[package]]-name = "nu-ansi-term"-version = "0.50.3"+name = "nix"+version = "0.29.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"+dependencies = [+ "bitflags",+ "cfg-if",+ "cfg_aliases",+ "libc",+ "memoffset",+]++[[package]]+name = "nu-ansi-term"+version = "0.50.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "num"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"+dependencies = [+ "num-bigint",+ "num-complex",+ "num-integer",+ "num-iter",+ "num-rational",+ "num-traits",+]++[[package]]+name = "num-bigint"+version = "0.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"+dependencies = [+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-complex"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"+dependencies = [+ "num-traits",+]++[[package]]+name = "num-conv"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"++[[package]]+name = "num-integer"+version = "0.1.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"+dependencies = [+ "num-traits",+]++[[package]]+name = "num-iter"+version = "0.1.46"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"dependencies = [- "windows-sys 0.61.2",+ "num-integer",+ "num-traits",][[package]]-name = "num-conv"-version = "0.2.2"+name = "num-rational"+version = "0.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"+dependencies = [+ "num-bigint",+ "num-integer",+ "num-traits",+][[package]]name = "num-traits"@@ -1701,18 +2160,75 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"+[[package]]+name = "openssl"+version = "0.10.81"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"+dependencies = [+ "bitflags",+ "cfg-if",+ "foreign-types",+ "libc",+ "openssl-macros",+ "openssl-sys",+]++[[package]]+name = "openssl-macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "openssl-probe"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"+[[package]]+name = "openssl-src"+version = "300.6.1+3.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846"+dependencies = [+ "cc",+]++[[package]]+name = "openssl-sys"+version = "0.9.117"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"+dependencies = [+ "cc",+ "libc",+ "openssl-src",+ "pkg-config",+ "vcpkg",+]+[[package]]name = "option-ext"version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"+[[package]]+name = "ordered-stream"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"+dependencies = [+ "futures-core",+ "pin-project-lite",+]+[[package]]name = "palette"version = "0.7.7"@@ -1746,6 +2262,12 @@ dependencies = ["libm",]+[[package]]+name = "parking"+version = "2.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"+[[package]]name = "parking_lot"version = "0.12.5"@@ -1799,12 +2321,37 @@ version = "0.2.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"+[[package]]+name = "piper"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"+dependencies = [+ "atomic-waker",+ "fastrand",+ "futures-io",+]+[[package]]name = "pkg-config"version = "0.3.34"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"+[[package]]+name = "polling"+version = "3.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"+dependencies = [+ "cfg-if",+ "concurrent-queue",+ "hermit-abi",+ "pin-project-lite",+ "rustix",+ "windows-sys 0.61.2",+]+[[package]]name = "poly1305"version = "0.9.1"@@ -1845,6 +2392,15 @@ dependencies = ["zerocopy",]+[[package]]+name = "proc-macro-crate"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"+dependencies = [+ "toml_edit",+]+[[package]]name = "proc-macro2"version = "1.0.107"@@ -1948,13 +2504,24 @@ version = "6.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"+[[package]]+name = "rand"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"+dependencies = [+ "libc",+ "rand_chacha 0.3.1",+ "rand_core 0.6.4",+]+[[package]]name = "rand"version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"dependencies = [- "rand_chacha",+ "rand_chacha 0.9.0","rand_core 0.9.5",]@@ -1969,6 +2536,16 @@ dependencies = ["rand_core 0.10.1",]+[[package]]+name = "rand_chacha"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"+dependencies = [+ "ppv-lite86",+ "rand_core 0.6.4",+]+[[package]]name = "rand_chacha"version = "0.9.0"@@ -1979,6 +2556,15 @@ dependencies = ["rand_core 0.9.5",]+[[package]]+name = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+dependencies = [+ "getrandom 0.2.17",+]+[[package]]name = "rand_core"version = "0.9.5"@@ -2235,7 +2821,7 @@ dependencies = ["openssl-probe","rustls-pki-types","schannel",- "security-framework",+ "security-framework 3.7.0",][[package]]@@ -2254,7 +2840,7 @@ version = "0.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0"dependencies = [- "core-foundation",+ "core-foundation 0.10.1","core-foundation-sys","jni","log",@@ -2263,7 +2849,7 @@ dependencies = ["rustls-native-certs","rustls-platform-verifier-android","rustls-webpki",- "security-framework",+ "security-framework 3.7.0","security-framework-sys","webpki-root-certs","windows-sys 0.61.2",@@ -2323,6 +2909,38 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"+[[package]]+name = "secret-service"+version = "4.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4"+dependencies = [+ "aes",+ "cbc",+ "futures-util",+ "generic-array",+ "hkdf 0.12.4",+ "num",+ "once_cell",+ "rand 0.8.8",+ "serde",+ "sha2 0.10.9",+ "zbus",+]++[[package]]+name = "security-framework"+version = "2.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"+dependencies = [+ "bitflags",+ "core-foundation 0.9.4",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]+[[package]]name = "security-framework"version = "3.7.0"@@ -2330,7 +2948,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"dependencies = ["bitflags",- "core-foundation",+ "core-foundation 0.10.1","core-foundation-sys","libc","security-framework-sys",@@ -2407,6 +3025,17 @@ dependencies = ["serde_core",]+[[package]]+name = "serde_repr"+version = "0.1.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "serde_urlencoded"version = "0.7.1"@@ -2430,6 +3059,17 @@ dependencies = ["digest 0.10.7",]+[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "digest 0.10.7",+]+[[package]]name = "sha2"version = "0.11.0"@@ -2657,6 +3297,19 @@ dependencies = ["syn 3.0.6",]+[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom 0.4.3",+ "once_cell",+ "rustix",+ "windows-sys 0.61.2",+]+[[package]]name = "thiserror"version = "2.0.21"@@ -2802,6 +3455,36 @@ dependencies = ["tokio",]+[[package]]+name = "toml_datetime"+version = "1.1.1+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_edit"+version = "0.25.15+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614"+dependencies = [+ "indexmap",+ "toml_datetime",+ "toml_parser",+ "winnow",+]++[[package]]+name = "toml_parser"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"+dependencies = [+ "winnow",+]+[[package]]name = "tower"version = "0.5.3"@@ -2940,6 +3623,17 @@ version = "1.20.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"+[[package]]+name = "uds_windows"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"+dependencies = [+ "memoffset",+ "tempfile",+ "windows-sys 0.61.2",+]+[[package]]name = "unicode-ident"version = "1.0.26"@@ -3286,6 +3980,15 @@ dependencies = ["windows-targets",]+[[package]]+name = "windows-sys"+version = "0.59.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"+dependencies = [+ "windows-targets",+]+[[package]]name = "windows-sys"version = "0.61.2"@@ -3359,6 +4062,15 @@ version = "0.52.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"+[[package]]+name = "winnow"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"+dependencies = [+ "memchr",+]+[[package]]name = "wit-bindgen"version = "0.57.1"@@ -3382,6 +4094,16 @@ dependencies = ["zeroize",]+[[package]]+name = "xdg-home"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6"+dependencies = [+ "libc",+ "windows-sys 0.59.0",+]+[[package]]name = "yoke"version = "0.8.3"@@ -3405,6 +4127,62 @@ dependencies = ["synstructure",]+[[package]]+name = "zbus"+version = "4.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725"+dependencies = [+ "async-broadcast",+ "async-process",+ "async-recursion",+ "async-trait",+ "enumflags2",+ "event-listener",+ "futures-core",+ "futures-sink",+ "futures-util",+ "hex",+ "nix",+ "ordered-stream",+ "rand 0.8.8",+ "serde",+ "serde_repr",+ "sha1",+ "static_assertions",+ "tracing",+ "uds_windows",+ "windows-sys 0.52.0",+ "xdg-home",+ "zbus_macros",+ "zbus_names",+ "zvariant",+]++[[package]]+name = "zbus_macros"+version = "4.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "zvariant_utils",+]++[[package]]+name = "zbus_names"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c"+dependencies = [+ "serde",+ "static_assertions",+ "zvariant",+]+[[package]]name = "zerocopy"version = "0.8.57"@@ -3451,6 +4229,20 @@ name = "zeroize"version = "1.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"+dependencies = [+ "zeroize_derive",+]++[[package]]+name = "zeroize_derive"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+][[package]]name = "zerotrie"@@ -3490,3 +4282,40 @@ name = "zmij"version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"++[[package]]+name = "zvariant"+version = "4.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe"+dependencies = [+ "endi",+ "enumflags2",+ "serde",+ "static_assertions",+ "zvariant_derive",+]++[[package]]+name = "zvariant_derive"+version = "4.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "zvariant_utils",+]++[[package]]+name = "zvariant_utils"+version = "2.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]diff --git a/host/Cargo.toml b/host/Cargo.tomlindex 7d10fbb5..5425dafe 100644--- a/host/Cargo.toml+++ b/host/Cargo.toml@@ -34,6 +34,7 @@ rusqlite = { version = "0.40.2", features = ["bundled"] }serde = { version = "1.0.229", features = ["derive"] }serde_json = { version = "1.0.151", features = ["preserve_order"] }sha2 = "0.11.0"+shlex = "2.0.1"tokio = { version = "1.53.1", features = ["full"] }tokio-stream = { version = "0.1.19", features = ["sync"] }tokio-tungstenite = { version = "0.29", features = ["rustls-tls-webpki-roots"] }@@ -43,6 +44,14 @@ unicode-width = "0.2"uuid = { version = "1.26.1", features = ["v4"] }x25519-dalek = { version = "3.0.0", features = ["static_secrets"] }+zeroize = "1"++[target.'cfg(target_os = "macos")'.dependencies]+keyring = { version = "3.6.3", features = ["apple-native"] }++[target.'cfg(target_os = "linux")'.dependencies]+keyring = { version = "3.6.3", features = ["sync-secret-service", "crypto-rust", "vendored"] }+# rust-skills lint-* rules: all default groups plus pedantic, with the# library-oriented pedantic lints turned off for this binary crate.[lints.rust]diff --git a/host/src/agent/auth.rs b/host/src/agent/auth.rsindex 1ff35187..f45f0e6a 100644--- a/host/src/agent/auth.rs+++ b/host/src/agent/auth.rs@@ -80,17 +80,17 @@ fn env_slot(backend: &str) -> String {}/// Keys saved for `backend`, as environment for its process.-pub fn env(store: &Store, backend: &str) -> Vec<(String, String)> {- store- .kv_get(&env_slot(backend))- .and_then(|s| serde_json::from_str::<BTreeMap<String, String>>(&s).ok())- .map(|m| m.into_iter().collect())- .unwrap_or_default()+pub fn env(store: &Store, backend: &str) -> Result<Vec<(String, String)>> {+ let Some(raw) = crate::market::vault::read(store, &env_slot(backend))? else {+ return Ok(Vec::new());+ };+ let values: BTreeMap<String, String> = serde_json::from_str(&raw)?;+ Ok(values.into_iter().collect())}/// Names of the saved keys (values never leave the host).-fn saved_env(store: &Store, backend: &str) -> Vec<String> {- env(store, backend).into_iter().map(|(k, _)| k).collect()+fn saved_env(store: &Store, backend: &str) -> Result<Vec<String>> {+ Ok(env(store, backend)?.into_iter().map(|(k, _)| k).collect())}/// Runs a check and returns `{signedIn, detail, methods, savedEnv}`.@@ -99,7 +99,7 @@ pub async fn check(store: &Store, backend: &str) -> Result<Value> {backends::set_signed_in(backend, status.signed_in);CHECKED.locked().insert(backend.to_owned(), status.clone());let mut v = serde_json::to_value(&status)?;- v["savedEnv"] = json!(saved_env(store, backend));+ v["savedEnv"] = json!(saved_env(store, backend)?);// Codync's own sign-in command (phone-friendly device flows where the CLI has one).v["login"] = json!(backends::login_available(backend));Ok(v)@@ -205,7 +205,7 @@ async fn start(store: &Store, backend: &str) -> Result<Started> {Some(local) => vec![local],None => backends::launch_candidates(backend, |_| {}).await?,};- let env = env(store, backend);+ let env = env(store, backend)?;let dir = probe_dir();tokio::fs::create_dir_all(&dir).await?;let mut last = None;@@ -349,7 +349,7 @@ pub async fn authenticate(store: &Store, backend: &str, method: &str) -> Result</// Saves the keys for an env-var method (empty values remove them), then re-checks.pub async fn set_env(store: &Store, backend: &str, vars: &Map<String, Value>) -> Result<Value> {- let mut saved: BTreeMap<String, String> = env(store, backend).into_iter().collect();+ let mut saved: BTreeMap<String, String> = env(store, backend)?.into_iter().collect();for (k, v) in vars {if !k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') || k.is_empty() {bail!("`{k}` isn't an environment variable name");@@ -359,7 +359,7 @@ pub async fn set_env(store: &Store, backend: &str, vars: &Map<String, Value>) ->None => saved.remove(k),};}- store.kv_set(&env_slot(backend), &serde_json::to_string(&saved)?)?;+ crate::market::vault::write(store, &env_slot(backend), &serde_json::to_string(&saved)?)?;check(store, backend).await}diff --git a/host/src/agent/bot.rs b/host/src/agent/bot.rsindex be1f116b..0d4ef0ff 100644--- a/host/src/agent/bot.rs+++ b/host/src/agent/bot.rs@@ -40,6 +40,7 @@ pub enum NoticeStyle {}pub enum Cmd {+ RefreshTools,Routine(String),/// The user wrote in the bot's chat or one of its threads.Send {@@ -280,6 +281,9 @@ impl Actor {async fn on_cmd(&mut self, cmd: Cmd, done_tx: &mpsc::UnboundedSender<Done>) -> bool {match cmd {+ Cmd::RefreshTools => {+ self.tools_changed = true;+ }Cmd::Routine(id) => {self.queue.push_back(Queued::Routine(id));if self.turn.is_none() {@@ -806,20 +810,26 @@ impl Actor {}/// ACP connectors, team collaboration, and optional computer control.- fn mcp_servers(&self) -> Value {+ fn mcp_servers(&self) -> Result<Value> {let Ok(exe) = std::env::current_exe() else {tracing::warn!("can't locate codync-host for MCP servers");- return json!([]);+ return Ok(json!([]));};let port = self.hub.port;- let mut servers: Vec<Value> = crate::market::connectors(&self.hub.store)- .iter()- .filter(|c| self.cfg.connectors.contains(&c.id))- .filter_map(|c| c.acp(&exe, port))- .collect();- let composio = crate::market::composio::enabled_for(&self.hub.store, &self.cfg.connectors);- let builtin =- [Some("team"), Some("routines"), self.cfg.computer.then_some("computer"), composio.then_some("composio")];+ let mut servers: Vec<Value> =+ (if self.cfg.connectors.is_empty() { Vec::new() } else { crate::market::connectors(&self.hub.store)? })+ .iter()+ .filter(|c| self.cfg.connectors.contains(&c.id))+ .filter_map(|c| c.acp(&exe, port))+ .collect();+ let composio = crate::market::composio::enabled_for(&self.hub.store, &self.cfg.connectors)?;+ let builtin = [+ Some("connectors"),+ Some("team"),+ Some("routines"),+ self.cfg.computer.then_some("computer"),+ composio.then_some("composio"),+ ];for name in builtin.into_iter().flatten() {servers.push(json!({"name": name, "command": exe,@@ -827,12 +837,17 @@ impl Actor {"env": [],}));}- Value::Array(servers)+ Ok(Value::Array(servers))}/// Makes sure the agent runs and `slot`'s session (main, or a thread's) is live;/// sets `turn_session`. A thread without one forks the main session when it can.async fn ensure_session(&mut self, slot: Option<&str>) -> Result<()> {+ if !self.cfg.connectors.is_empty()+ || self.hub.store.kv_read(&format!("agent-env:{}", self.cfg.backend))?.is_some()+ {+ crate::market::vault::unlock(self.hub.clone()).await?;+ }if self.tools_changed && self.turn.is_none() {self.tools_changed = false;if let Some(c) = self.conn.take() {@@ -848,7 +863,7 @@ impl Actor {.await?;self.hub.set_runtime(&self.id(), |r| r.activity = "Starting agent…".into());// Keys saved from an "environment variable" sign-in.- let env = crate::agent::auth::env(&self.hub.store, &self.cfg.backend);+ let env = crate::agent::auth::env(&self.hub.store, &self.cfg.backend)?;let mut last_err = None;for (i, command) in candidates.iter().enumerate() {let fallback_left = i + 1 < candidates.len();@@ -869,7 +884,7 @@ impl Actor {return Err(last_err.unwrap_or_else(|| anyhow!("agent failed to start")));}}- let servers = self.mcp_servers();+ let servers = self.mcp_servers()?;let claude = self.conn.as_ref().is_some_and(|c| c.claude);let mut forked = false;if let Some(root) = slotdiff --git a/host/src/agent/mod.rs b/host/src/agent/mod.rsindex 3549315a..b1c0b500 100644--- a/host/src/agent/mod.rs+++ b/host/src/agent/mod.rs@@ -7,3 +7,4 @@ pub mod backends;pub mod bot;pub mod registry;pub mod term;+pub mod workspace;diff --git a/host/src/agent/workspace.rs b/host/src/agent/workspace.rsnew file mode 100644index 00000000..8550fb6c--- /dev/null+++ b/host/src/agent/workspace.rs@@ -0,0 +1,29 @@+//! Persistent, automatically allocated bot workspaces. A cwd is an execution+//! default, not an access boundary; explicit project folders remain opt-in.++use crate::service;+use crate::store::BotConfig;+use anyhow::{Context as _, Result};+use std::path::PathBuf;++pub fn path(id: &str) -> PathBuf {+ service::data_dir().join("bots").join(id).join("workspace")+}++pub fn is_managed(cfg: &BotConfig) -> bool {+ !cfg.is_group() && std::path::Path::new(&cfg.cwd) == path(&cfg.id)+}++/// Called on a blocking thread before persisting a bot configuration.+/// Empty cwd opts into automatic allocation, including when editing a bot.+pub fn prepare(cfg: &mut BotConfig) -> Result<()> {+ if cfg.is_group() || !cfg.cwd.is_empty() {+ return Ok(());+ }+ // Only host-issued IDs may become directory components.+ uuid::Uuid::parse_str(&cfg.id).context("invalid bot workspace id")?;+ let dir = path(&cfg.id);+ std::fs::create_dir_all(&dir).context("creating bot workspace")?;+ cfg.cwd = dir.to_string_lossy().into_owned();+ Ok(())+}diff --git a/host/src/api/devices.rs b/host/src/api/devices.rsindex 70040483..f0fdb83c 100644--- a/host/src/api/devices.rs+++ b/host/src/api/devices.rs@@ -37,6 +37,8 @@ const LOCAL_ONLY: &[&str] = &["routineCall","composioCall","connectorTarget",+ "connectorRuntime",+ "connectorCall","claimSign","unclaim","devices",diff --git a/host/src/api/mod.rs b/host/src/api/mod.rsindex 3ee5c1d9..aeabaf95 100644--- a/host/src/api/mod.rs+++ b/host/src/api/mod.rs@@ -210,11 +210,66 @@ fn str_arg<'a>(b: &'a Value, k: &str) -> Result<&'a str> {/// Runs one API method for `caller` (permissions per spec §6.6).pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -> Result<Value> {devices::permit(caller, method)?;+ if method.contains("onnector")+ || method.starts_with("composio")+ || method == "setComposioKey"+ || method.starts_with("credential")+ || matches!(method, "agentAuth" | "agentAuthenticate" | "setAgentEnv")+ {+ market::vault::unlock(hub.clone()).await?;+ }Ok(match method {+ "credentialUpdateConnector" => {+ let id = str_arg(&b, "id")?;+ let fields = b["fields"].as_object().ok_or_else(|| anyhow!("Credential fields are required"))?;+ market::update_connectors(&hub.store, |all| {+ let c = all.iter_mut().find(|c| c.id == id).ok_or_else(|| anyhow!("Unknown connector"))?;+ let values = if c.command.is_some() { &mut c.env } else { &mut c.headers };+ for (key, value) in fields {+ if !values.contains_key(key) {+ bail!("Unknown credential field");+ }+ let value = value+ .as_str()+ .filter(|s| !s.is_empty() && s.len() <= 64 * 1024)+ .ok_or_else(|| anyhow!("Invalid credential value"))?;+ values.insert(key.clone(), value.to_owned());+ }+ Ok(())+ })?;+ let ready = market::verify::verify(&hub.store, id, hub.port).await?;+ for row in hub.store.bots()? {+ if !row.deleted && !row.config.is_group() && row.config.connectors.iter().any(|c| c == id) {+ hub.send_cmd(&row.config.id, Cmd::RefreshTools)?;+ }+ }+ ready+ }+ "credentialStatus" => market::passwords::status(&hub.store)?,+ "credentialSetOnePassword" => {+ market::passwords::set_token(&hub.store, b["token"].as_str().unwrap_or_default()).await?+ }+ "connectorRuntime" => {+ let c = market::connectors(&hub.store)?+ .into_iter()+ .find(|c| Some(c.id.as_str()) == b["id"].as_str())+ .ok_or_else(|| anyhow!("Unknown connector"))?;+ let mut env = serde_json::Map::new();+ for (k, v) in &c.env {+ env.insert(k.clone(), market::passwords::resolve(&hub.store, v).await?.into());+ }+ json!({"command":c.command,"args":c.args,"env":env})+ }+ "connectorCall" => {+ market::requests::call(hub, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"]).await?+ }+ "connectorInfo" => market::connector_info(&hub.store, str_arg(&b, "registryName")?).await?,+ "connectorRequestFinish" => market::requests::finish(hub, &b).await?,+ "connectorVerify" => market::verify::verify(&hub.store, str_arg(&b, "id")?, hub.port).await?,"composioCall" => {json!({"result": market::composio::call(&hub.store, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"]).await?})}- "composioStatus" => market::composio::status(&hub.store),+ "composioStatus" => market::composio::status(&hub.store)?,"setComposioKey" => market::composio::set_key(&hub.store, b["key"].as_str().unwrap_or_default()).await?,"composioToolkits" => {market::composio::toolkits(@@ -231,6 +286,7 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -.await?}"composioConnection" => market::composio::connection(&hub.store, str_arg(&b, "id")?).await?,+ "routineSchedule" => crate::routines::schedule_preview(&b, crate::store::now_ms())?,"routines" => hub.routines.list(str_arg(&b, "botId")?),"saveRoutine" => hub.routines.save(hub, str_arg(&b, "botId")?, &b)?,"setRoutineEnabled" => hub.routines.set_enabled(@@ -296,9 +352,13 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -let mut b = b;b["id"] = "".into();let cfg: BotConfig = serde_json::from_value(b).context("invalid bot")?;- json!({"bot": hub.create_bot(cfg)?})+ let hub = hub.clone();+ json!({"bot": tokio::task::spawn_blocking(move || hub.create_bot(cfg)).await??})+ }+ "updateBot" => {+ let hub = hub.clone();+ json!({"bot": tokio::task::spawn_blocking(move || hub.update_bot(&b)).await??})}- "updateBot" => json!({"bot": hub.update_bot(&b)?}),"deleteBot" => {hub.delete_bot(str_arg(&b, "botId")?)?;json!({})@@ -313,10 +373,39 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -hub.mark_read(str_arg(&b, "botId")?, scope)?;json!({})}+ // One chunk of a file for a later `send` (`attachments`); base64 `data` at `offset`.+ "upload" => {+ use base64::Engine as _;+ let row = hub.store.bot(str_arg(&b, "botId")?)?.filter(|r| !r.deleted && !r.config.is_group());+ let root = crate::chat::uploads::root(&row.ok_or_else(|| anyhow!("unknown bot"))?.config);+ let (id, name) = (str_arg(&b, "uploadId")?.to_owned(), str_arg(&b, "name")?.to_owned());+ let data =+ base64::engine::general_purpose::STANDARD.decode(str_arg(&b, "data")?).context("invalid data")?;+ let (offset, done) = (b["offset"].as_u64().unwrap_or(0), b["done"] == true);+ let attachment = tokio::task::spawn_blocking(move || {+ crate::chat::uploads::append(&root, &id, &name, offset, &data, done)+ })+ .await??;+ json!({"attachment": attachment})+ }+ // A sent file, back in chunks (chat previews on other devices).+ "readUpload" => {+ use base64::Engine as _;+ let row = hub.store.bot(str_arg(&b, "botId")?)?.filter(|r| !r.deleted && !r.config.is_group());+ let root = crate::chat::uploads::root(&row.ok_or_else(|| anyhow!("unknown bot"))?.config);+ let id = str_arg(&b, "uploadId")?.to_owned();+ let offset = b["offset"].as_u64().unwrap_or(0);+ let (data, size) =+ tokio::task::spawn_blocking(move || crate::chat::uploads::read(&root, &id, offset, 384 * 1024))+ .await??;+ json!({"data": base64::engine::general_purpose::STANDARD.encode(data), "size": size})+ }"send" => {let bot = str_arg(&b, "botId")?;- let text = str_arg(&b, "text")?.trim();- if text.is_empty() {+ let text = b["text"].as_str().unwrap_or_default().trim();+ let uploads: Vec<&str> =+ b["attachments"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();+ if text.is_empty() && uploads.is_empty() {bail!("empty message");}let nonce = b["clientNonce"].as_str().unwrap_or_default();@@ -338,11 +427,33 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -None => None,};let lane = Lane { chat: bot.to_owned(), thread };+ let (mut paths, mut attachments) = (Vec::new(), Vec::new());+ if !uploads.is_empty() {+ if row.config.is_group() {+ bail!("files can't be sent to a group");+ }+ let root = crate::chat::uploads::root(&row.config);+ for id in uploads {+ let (path, meta) = crate::chat::uploads::resolve(&root, id)?;+ paths.push(path);+ attachments.push(meta);+ }+ }+ let prompt = if paths.is_empty() {+ text.to_owned()+ } else {+ format!("{text}{}", crate::chat::uploads::prompt_suffix(&paths))+ };let turn = hub.store.max_turn(bot) + 1;// A group has no agent of its own to queue behind: its message is simply sent.let status = if row.config.is_group() { "sent" } else { "queued" };let e = hub- .add_entry(&lane, EntryKind::User, turn, &json!({"text": text, "clientNonce": nonce, "status": status}))+ .add_entry(+ &lane,+ EntryKind::User,+ turn,+ &json!({"text": text, "clientNonce": nonce, "status": status, "attachments": attachments}),+ ).ok_or_else(|| anyhow!("couldn't save the message"))?;// Before the turn starts, so its reply lands unread.let scope = lane.thread.as_deref().map_or(ReadScope::Chat, ReadScope::Thread);@@ -352,10 +463,19 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -if row.config.is_group() {crate::chat::group::start(hub, &row.config, lane);} else {- hub.send_cmd(bot, Cmd::Send { lane, entry_id: e.id.clone(), text: text.to_owned() })?;+ hub.send_cmd(bot, Cmd::Send { lane, entry_id: e.id.clone(), text: prompt })?;}json!({"entry": e})}+ // A finished voice call, as a line in the chat ("Voice chat · 0:16").+ "logCall" => {+ let bot = str_arg(&b, "botId")?;+ hub.store.bot(bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?;+ let seconds = b["seconds"].as_u64().unwrap_or(0);+ let data = json!({"text": "Voice chat", "callSeconds": seconds});+ let e = hub.add_entry(&Lane::main(bot), EntryKind::Notice, hub.store.max_turn(bot), &data);+ json!({"entry": e})+ }"stop" => {let bot = str_arg(&b, "botId")?;match hub.store.bot(bot)? {@@ -502,9 +622,17 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -serde_json::to_value(crate::remote::cloud::set_approval(hub, approval)?)?}"claimSign" => claim_sign(hub, &b).await?,- "marketConnectors" => market::browse_connectors(&hub.store, b["search"].as_str().unwrap_or_default()).await?,+ "marketConnectors" => {+ market::browse_connectors(+ &hub.store,+ b["search"].as_str().unwrap_or_default(),+ b["cursor"].as_str().unwrap_or_default(),+ )+ .await?+ }"marketSkills" => market::browse_skills(&hub.store).await?,- "connectors" => market::list_connectors(&hub.store),+ "connectors" => market::list_connectors(&hub.store)?,+ "importConnectors" => market::import_connectors(&hub.store, str_arg(&b, "config")?).await?,"installConnector" => {let c = if b["registryName"].is_string() {market::install_connector(diff --git a/host/src/chat/context.rs b/host/src/chat/context.rsindex 83461640..25752953 100644--- a/host/src/chat/context.rs+++ b/host/src/chat/context.rs@@ -130,6 +130,7 @@ pub fn render(store: &Store, cfg: &BotConfig) -> String {"You are a persistent agent the user delegates work to from their phone through Codync. They see only your final reply of each turn, so keep it short and phone-friendly: say what you did and what needs the user.".to_owned(),);+ lines.push(format!("Your default execution directory is {}. {} Use this space for your own task files and outputs. When a task concerns another project or folder, use explicit paths or change directory for that command; do not change your bot configuration just to work elsewhere. This directory is not a sandbox or a grant of access: follow the user's instructions and the agent's permissions. Do not assume other bots' files belong to you.", cfg.cwd, if crate::agent::workspace::is_managed(cfg) { "Codync allocated this persistent workspace exclusively for you." } else { "The user selected this project folder." }));lines.push(crate::chat::team::INSTRUCTIONS.to_owned());lines.push(crate::routines::INSTRUCTIONS.to_owned());lines.push(diff --git a/host/src/chat/memory.rs b/host/src/chat/memory.rsindex 60d34b4b..05361853 100644--- a/host/src/chat/memory.rs+++ b/host/src/chat/memory.rs@@ -643,7 +643,10 @@ async fn one_shot(hub: &Arc<Hub>, cfg: &BotConfig, system: &str, user: &str) ->let cwd = crate::service::data_dir().join("memory-keeper");tokio::fs::create_dir_all(&cwd).await?;let cwd = cwd.to_string_lossy().into_owned();- let env = crate::agent::auth::env(&hub.store, &cfg.backend);+ if hub.store.kv_read(&format!("agent-env:{}", cfg.backend))?.is_some() {+ crate::market::vault::unlock(hub.clone()).await?;+ }+ let env = crate::agent::auth::env(&hub.store, &cfg.backend)?;let mut conn = None;let mut last_err = None;for command in crate::agent::bot::launch_commands(cfg, |_| {}).await? {diff --git a/host/src/chat/mod.rs b/host/src/chat/mod.rsindex a972b3b3..704f81e7 100644--- a/host/src/chat/mod.rs+++ b/host/src/chat/mod.rs@@ -5,3 +5,4 @@ pub mod context;pub mod group;pub mod memory;pub mod team;+pub mod uploads;diff --git a/host/src/chat/uploads.rs b/host/src/chat/uploads.rsnew file mode 100644index 00000000..bbcaea06--- /dev/null+++ b/host/src/chat/uploads.rs@@ -0,0 +1,122 @@+//! Files sent with a message. A client uploads each file in chunks (the channel caps a+//! message at 1 MiB), then names the uploads in `send`; the agent gets their paths.++use crate::agent::workspace;+use crate::service;+use crate::store::BotConfig;+use anyhow::{Context as _, Result, bail};+use serde_json::{Value, json};+use std::io::Write as _;+use std::path::{Path, PathBuf};++/// Largest file accepted.+pub const MAX_FILE: u64 = 100 * 1024 * 1024;++/// Inside a personal workspace, so reading an upload needs no extra approval.+pub fn root(cfg: &BotConfig) -> PathBuf {+ if workspace::is_managed(cfg) {+ Path::new(&cfg.cwd).join("uploads")+ } else {+ service::data_dir().join("bots").join(&cfg.id).join("uploads")+ }+}++/// `uploads/<upload id>/`, the id checked so it can't leave the folder.+fn dir(root: &Path, upload: &str) -> Result<PathBuf> {+ uuid::Uuid::parse_str(upload).context("invalid upload id")?;+ Ok(root.join(upload.to_ascii_lowercase()))+}++/// The file's own name only: no folders, no hidden or empty names.+fn clean_name(name: &str) -> Result<String> {+ let name = name.rsplit(['/', '\\']).next().unwrap_or_default().trim();+ if name.is_empty() || name.starts_with('.') || name.len() > 200 {+ bail!("invalid file name");+ }+ Ok(name.to_owned())+}++/// Appends one chunk at `offset`. A repeated chunk (a retry) is accepted as is.+/// Returns the attachment once `done`.+pub fn append(root: &Path, upload: &str, name: &str, offset: u64, data: &[u8], done: bool) -> Result<Option<Value>> {+ let dir = dir(root, upload)?;+ let path = dir.join(clean_name(name)?);+ std::fs::create_dir_all(&dir).context("creating the upload folder")?;+ let len = std::fs::metadata(&path).map_or(0, |m| m.len());+ let end = offset + data.len() as u64;+ if end > MAX_FILE {+ bail!("file is larger than {} MB", MAX_FILE / 1024 / 1024);+ }+ if offset == len {+ let mut file =+ std::fs::OpenOptions::new().create(true).append(true).open(&path).context("opening the upload")?;+ file.write_all(data).context("writing the upload")?;+ } else if end != len {+ bail!("upload out of order: at {len}, got {offset}");+ }+ Ok(done.then(|| json!({"id": upload, "name": path.file_name().map(|n| n.to_string_lossy()), "size": end})))+}++/// A finished upload: its path and chat metadata.+pub fn resolve(root: &Path, upload: &str) -> Result<(PathBuf, Value)> {+ let dir = dir(root, upload)?;+ let file = std::fs::read_dir(&dir)+ .context("unknown upload")?+ .filter_map(Result::ok)+ .find(|e| e.file_type().is_ok_and(|t| t.is_file()))+ .context("empty upload")?;+ let size = file.metadata().map_or(0, |m| m.len());+ let name = file.file_name().to_string_lossy().into_owned();+ Ok((file.path(), json!({"id": upload, "name": name, "size": size})))+}++/// Up to `len` bytes of a finished upload from `offset`, and its full size.+pub fn read(root: &Path, upload: &str, offset: u64, len: usize) -> Result<(Vec<u8>, u64)> {+ use std::io::{Read as _, Seek as _, SeekFrom};+ let (path, _) = resolve(root, upload)?;+ let mut file = std::fs::File::open(&path).context("opening the upload")?;+ let size = file.metadata().context("reading the upload")?.len();+ file.seek(SeekFrom::Start(offset)).context("reading the upload")?;+ let mut data = Vec::with_capacity(len);+ file.take(len as u64).read_to_end(&mut data).context("reading the upload")?;+ Ok((data, size))+}++/// What the agent reads after the message text.+pub fn prompt_suffix(paths: &[PathBuf]) -> String {+ let list: Vec<String> = paths.iter().map(|p| format!("- {}", p.display())).collect();+ format!("\n\n[Attached files — read them from these paths]\n{}", list.join("\n"))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn names_stay_inside_the_folder() {+ assert_eq!(clean_name("../../etc/passwd").expect("last component"), "passwd");+ assert_eq!(clean_name("C:\\x\\photo.jpg").expect("last component"), "photo.jpg");+ assert!(clean_name("..").is_err());+ assert!(clean_name(".ssh").is_err());+ assert!(clean_name("dir/").is_err());+ }++ #[test]+ fn chunks_append_and_retries_are_idempotent() {+ let root = std::env::temp_dir().join(format!("codync-uploads-{}", uuid::Uuid::new_v4()));+ let root = root.as_path();+ let id = uuid::Uuid::new_v4().to_string();+ assert!(dir(root, "../x").is_err());+ assert!(append(root, &id, "a.txt", 0, b"hello ", false).expect("first").is_none());+ assert!(append(root, &id, "a.txt", 0, b"hello ", false).is_ok(), "retry of the first chunk");+ assert!(append(root, &id, "a.txt", 3, b"xx", false).is_err(), "out of order");+ let done = append(root, &id, "a.txt", 6, b"world", true).expect("last").expect("done");+ assert_eq!(done["size"], 11);+ let (path, meta) = resolve(root, &id).expect("resolve");+ assert_eq!(std::fs::read_to_string(&path).expect("read"), "hello world");+ assert_eq!(meta["name"], "a.txt");+ assert_eq!(read(root, &id, 6, 100).expect("read"), (b"world".to_vec(), 11));+ assert!(path.starts_with(root));+ let _ = std::fs::remove_dir_all(root);+ }+}diff --git a/host/src/hub.rs b/host/src/hub.rsindex b8cebd04..a508dce3 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -154,6 +154,7 @@ impl Hub {pub fn bot_json(&self, row: &BotRow) -> Value {let cfg = &row.config;let mut v = serde_json::to_value(cfg).expect("BotConfig is plain data and always serializes");+ v["managedWorkspace"] = crate::agent::workspace::is_managed(cfg).into();let rt = if cfg.is_group() {self.group_runtime(cfg)} else {@@ -220,6 +221,7 @@ impl Hub {}}validate(&cfg)?;+ crate::agent::workspace::prepare(&mut cfg)?;{let _g = self.emit_lock.locked();self.store.save_bot(&cfg)?;@@ -248,6 +250,7 @@ impl Hub {cfg.members = crate::chat::group::valid_members(&self.store, &cfg.id, &cfg.members)?;}validate(&cfg)?;+ crate::agent::workspace::prepare(&mut cfg)?;{let _g = self.emit_lock.locked();self.store.save_bot(&cfg)?;@@ -534,7 +537,7 @@ fn validate(cfg: &BotConfig) -> Result<()> {if cfg.is_group() {return Ok(());}- if !std::path::Path::new(&cfg.cwd).is_dir() {+ if !cfg.cwd.is_empty() && !std::path::Path::new(&cfg.cwd).is_dir() {bail!("workspace folder does not exist: {}", cfg.cwd);}if cfg.command.as_deref().map(str::trim).unwrap_or_default().is_empty()diff --git a/host/src/main.rs b/host/src/main.rsindex 6384d424..49b06e38 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -176,6 +176,20 @@ enum AccessAction {#[derive(Subcommand)]enum McpServer {+ /// Launch a local connector without exposing its credentials in ACP config.+ Local {+ #[arg(long)]+ connector: String,+ #[arg(long, default_value_t = service::DEFAULT_PORT)]+ port: u16,+ },+ /// Invite the user to connect services securely.+ Connectors {+ #[arg(long)]+ bot: String,+ #[arg(long, default_value_t = service::DEFAULT_PORT)]+ port: u16,+ },/// Scheduled and event-triggered bot routines.Routines {#[arg(long)]@@ -353,10 +367,14 @@ async fn main() -> Result<()> {println!("Token rotated. Restart the host so local helpers pick it up.");Ok(())}+ Sub::Mcp { server: McpServer::Connectors { bot, port } } => {+ mcp::serve(bot, port, mcp::Server::Connectors).await+ }Sub::Mcp { server: McpServer::Computer { bot, port } } => mcp::serve(bot, port, mcp::Server::Computer).await,Sub::Mcp { server: McpServer::Routines { bot, port } } => mcp::serve(bot, port, mcp::Server::Routines).await,Sub::Mcp { server: McpServer::Team { bot, port } } => mcp::serve(bot, port, mcp::Server::Team).await,Sub::Mcp { server: McpServer::Composio { bot, port } } => mcp::serve(bot, port, mcp::Server::Composio).await,+ Sub::Mcp { server: McpServer::Local { connector, port } } => mcp::serve_local(connector, port).await,Sub::Mcp { server: McpServer::Remote { connector, port } } => mcp::serve_remote(connector, port).await,Sub::Tui { url, token, port } => {tui::run(url.unwrap_or_else(|| format!("http://127.0.0.1:{port}")), token).awaitdiff --git a/host/src/market/composio.rs b/host/src/market/composio.rsindex aab974aa..78125ded 100644--- a/host/src/market/composio.rs+++ b/host/src/market/composio.rs@@ -56,21 +56,25 @@ impl Connection {}}-fn load(store: &Store) -> Option<Config> {- store.kv_get(SLOT).and_then(|s| serde_json::from_str::<Config>(&s).ok()).filter(|c| !c.key.is_empty())+fn load(store: &Store) -> Result<Option<Config>> {+ let Some(raw) = super::vault::read(store, SLOT)?.filter(|s| !s.is_empty()) else {+ return Ok(None);+ };+ let c: Config = serde_json::from_str(&raw)?;+ Ok((!c.key.is_empty()).then_some(c))}fn save(store: &Store, c: &Config) -> Result<()> {- store.kv_set(SLOT, &serde_json::to_string(c)?)+ super::vault::write(store, SLOT, &serde_json::to_string(c)?)}fn config(store: &Store) -> Result<Config> {- load(store).ok_or_else(|| anyhow!("Set up Composio in Marketplace first."))+ load(store)?.ok_or_else(|| anyhow!("Set up Composio in Marketplace first."))}/// Cached connected apps (possibly stale; `refresh` updates them).-pub fn connections(store: &Store) -> Vec<Connection> {- load(store).map(|c| c.connections).unwrap_or_default()+pub fn connections(store: &Store) -> Result<Vec<Connection>> {+ Ok(load(store)?.map(|c| c.connections).unwrap_or_default())}async fn request(@@ -90,14 +94,10 @@ async fn request(let text = res.text().await.unwrap_or_default();let v: Value = serde_json::from_str(&text).unwrap_or(Value::Null);if !status.is_success() {- let msg = v["error"]["message"]- .as_str()- .or(v["message"].as_str())- .map_or_else(|| text.chars().take(300).collect(), str::to_owned);if status.as_u16() == 401 {- bail!("Composio didn't accept the API key: {msg}");+ bail!("Composio did not accept the API key. Reconnect in Marketplace.");}- bail!("Composio: {msg} ({status})");+ bail!("Composio request failed ({status}). Check the connection and try again.");}Ok(v)}@@ -134,26 +134,30 @@ fn title_case(s: &str) -> String {// MARK: setup-pub fn status(store: &Store) -> Value {- json!({"configured": load(store).is_some(), "keyUrl": KEY_URL})+pub fn status(store: &Store) -> Result<Value> {+ Ok(json!({"configured": load(store)?.is_some(), "keyUrl": KEY_URL}))}/// Checks the key with Composio, then keeps it. An empty key forgets Composio.pub async fn set_key(store: &Store, key: &str) -> Result<Value> {let key = key.trim();if key.is_empty() {- store.kv_set(SLOT, "")?;- return Ok(status(store));+ let _guard = store.connector_lock.lock().map_err(|_| anyhow!("connector storage is busy"))?;+ super::vault::write(store, SLOT, "")?;+ return status(store);}get(key, "/toolkits", &[("limit", "1")]).await?;- let mut c = load(store).unwrap_or_default();- c.key = key.to_owned();- if c.user_id.is_empty() {- c.user_id = format!("codync-{}", uuid::Uuid::new_v4());+ {+ let _guard = store.connector_lock.lock().map_err(|_| anyhow!("connector storage is busy"))?;+ let mut c = load(store)?.unwrap_or_default();+ key.clone_into(&mut c.key);+ if c.user_id.is_empty() {+ c.user_id = format!("codync-{}", uuid::Uuid::new_v4());+ }+ save(store, &c)?;}- save(store, &c)?;refresh(store).await?;- Ok(status(store))+ status(store)}/// Re-reads this computer's connected accounts from Composio.@@ -191,10 +195,19 @@ pub async fn refresh(store: &Store) -> Result<Vec<Connection>> {}}c.connections.clone_from(&list);- save(store, &c)?;+ save_refresh(store, &c)?;Ok(list)}+fn save_refresh(store: &Store, refreshed: &Config) -> Result<()> {+ let _guard = store.connector_lock.lock().map_err(|_| anyhow!("connector storage is busy"))?;+ let current = config(store)?;+ if current.key != refreshed.key || current.user_id != refreshed.user_id {+ bail!("Composio credentials changed. Refresh the connections again.");+ }+ save(store, refreshed)+}+/// Toolkits to connect: the popular ones, or matches for `search`.pub async fn toolkits(store: &Store, search: &str, cursor: &str) -> Result<Value> {let c = config(store)?;@@ -416,16 +429,19 @@ pub fn tools() -> Value {fn allowed(store: &Store, bot: &str) -> Result<Vec<Connection>> {let row = store.bot(bot)?.ok_or_else(|| anyhow!("unknown bot"))?;let on: Vec<&str> = row.config.connectors.iter().filter_map(|id| id.strip_prefix(PREFIX)).collect();- Ok(connections(store).into_iter().filter(|c| c.active() && on.contains(&c.toolkit.as_str())).collect())+ Ok(connections(store)?.into_iter().filter(|c| c.active() && on.contains(&c.toolkit.as_str())).collect())}/// Toolkits a bot has turned on, for its MCP server list (none: no server).-pub fn enabled_for(store: &Store, connectors: &[String]) -> bool {- let conns = connections(store);- connectors+pub fn enabled_for(store: &Store, connectors: &[String]) -> Result<bool> {+ if !connectors.iter().any(|s| s.starts_with(PREFIX)) {+ return Ok(false);+ }+ let conns = connections(store)?;+ Ok(connectors.iter().filter_map(|id| id.strip_prefix(PREFIX))- .any(|t| conns.iter().any(|c| c.active() && c.toolkit == t))+ .any(|t| conns.iter().any(|c| c.active() && c.toolkit == t)))}/// A tool call from a bot's `composio` MCP server.@@ -497,6 +513,20 @@ async fn tool(key: &str, slug: &str) -> Result<Value> {mod tests {use super::*;+ #[test]+ fn stale_refresh_cannot_restore_removed_or_replaced_credentials() {+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();+ let old = Config { key: "old-key".into(), user_id: "user".into(), connections: vec![] };+ save(&store, &old).unwrap();+ super::super::vault::write(&store, SLOT, "").unwrap();+ assert!(save_refresh(&store, &old).is_err());+ assert!(load(&store).unwrap().is_none());+ let new = Config { key: "new-key".into(), ..old.clone() };+ save(&store, &new).unwrap();+ assert!(save_refresh(&store, &old).is_err());+ assert_eq!(load(&store).unwrap().unwrap().key, "new-key");+ }+#[test]fn reads_key_based_fields() {let detail = json!({diff --git a/host/src/market/mod.rs b/host/src/market/mod.rsindex ba7cd759..31ceb9e8 100644--- a/host/src/market/mod.rs+++ b/host/src/market/mod.rs@@ -18,6 +18,10 @@pub mod composio;pub mod oauth;+pub mod passwords;+pub mod requests;+pub mod vault;+pub mod verify;use crate::LockExt;use anyhow::{Context, Result, anyhow, bail};@@ -69,9 +73,10 @@ impl Connector {/// which keeps sign-in tokens fresh and works with agents that only speak stdio./// A remote server still waiting for sign-in is left out.pub fn acp(&self, exe: &std::path::Path, port: u16) -> Option<Value> {- if let Some(command) = &self.command {- let env: Vec<Value> = self.env.iter().map(|(k, v)| json!({"name": k, "value": v})).collect();- return Some(json!({"name": self.id, "command": command, "args": self.args, "env": env}));+ if self.command.is_some() {+ return Some(+ json!({"name":self.id,"command":exe,"args":["mcp","local","--connector",self.id,"--port",port.to_string()],"env":[]}),+ );}self.url.as_ref()?;if self.oauth.as_ref().is_some_and(|o| !o.signed_in()) {@@ -92,8 +97,11 @@ impl Connector {"description": self.description,"registryName": self.registry_name,"kind": if self.command.is_some() { "local" } else { "remote" },- "command": self.command.as_ref().map(|c| std::iter::once(c.clone()).chain(self.args.iter().cloned()).collect::<Vec<_>>().join(" ")),- "url": self.url,+ "command": self.command.clone(),+ "url": self.url.as_deref().and_then(|raw| reqwest::Url::parse(raw).ok()).map(|mut url| {+ let _ = url.set_username(""); let _ = url.set_password(None);+ url.set_query(None); url.set_fragment(None); url.to_string()+ }),"keys": self.env.keys().chain(self.headers.keys()).collect::<Vec<_>>(),"auth": match &self.oauth {None => "none",@@ -149,8 +157,8 @@ fn load<T: for<'de> Deserialize<'de>>(store: &crate::store::Store, key: &str) ->store.kv_get(key).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()}-pub fn connectors(store: &crate::store::Store) -> Vec<Connector> {- load(store, "connectors")+pub fn connectors(store: &crate::store::Store) -> Result<Vec<Connector>> {+ vault::read(store, "connectors")?.map_or_else(|| Ok(Vec::new()), |s| serde_json::from_str(&s).map_err(Into::into))}pub fn skills(store: &crate::store::Store) -> Vec<Skill> {@@ -162,7 +170,33 @@ fn save<T: Serialize>(store: &crate::store::Store, key: &str, items: &[T]) -> Re}pub fn save_connectors(store: &crate::store::Store, items: &[Connector]) -> Result<()> {- save(store, "connectors", items)+ vault::write(store, "connectors", &serde_json::to_string(items)?)+}++/// Serialize read/modify/write so OAuth refreshes and installations cannot replace each other.+pub fn update_connectors<T>(+ store: &crate::store::Store,+ change: impl FnOnce(&mut Vec<Connector>) -> Result<T>,+) -> Result<T> {+ let _guard = store.connector_lock.locked();+ let mut all = connectors(store)?;+ let result = change(&mut all)?;+ save_connectors(store, &all)?;+ Ok(result)+}++fn add_connector(store: &crate::store::Store, mut c: Connector) -> Result<Value> {+ update_connectors(store, |all| {+ if let Some(name) = c.registry_name.as_deref()+ && let Some(existing) = all.iter().find(|x| x.registry_name.as_deref() == Some(name))+ {+ return Ok(existing.public());+ }+ c.id = unique_id(&c.name, &all.iter().map(|c| c.id.clone()).collect::<Vec<_>>());+ let public = c.public();+ all.push(c);+ Ok(public)+ })}fn unique_id(base: &str, taken: &[String]) -> String {@@ -206,14 +240,20 @@ async fn get_json_within(url: &str, timeout: Duration) -> Result<Value> {Ok(res.json().await?)}-async fn registry_search(search: &str, limit: usize) -> Result<Vec<Value>> {+/// One page of the registry (a search, or everything), with the cursor for the next page.+async fn registry_page(search: &str, cursor: &str, limit: usize) -> Result<(Vec<Value>, Option<String>)> {let mut url = reqwest::Url::parse(MCP_REGISTRY)?;url.query_pairs_mut().append_pair("version", "latest").append_pair("limit", &limit.to_string());if !search.is_empty() {url.query_pairs_mut().append_pair("search", search);}+ if !cursor.is_empty() {+ url.query_pairs_mut().append_pair("cursor", cursor);+ }let v = get_json_within(url.as_str(), SEARCH_TIMEOUT).await.context("searching the MCP Registry")?;- Ok(v["servers"].as_array().cloned().unwrap_or_default().into_iter().map(|s| s["server"].clone()).collect())+ let servers =+ v["servers"].as_array().cloned().unwrap_or_default().into_iter().map(|s| s["server"].clone()).collect();+ Ok((servers, v["metadata"]["nextCursor"].as_str().filter(|c| !c.is_empty()).map(str::to_owned)))}/// One registry server by exact name (its latest version).@@ -229,33 +269,41 @@ fn install_options(server: &Value) -> Vec<Value> {let mut out = vec![];for (i, p) in server["packages"].as_array().into_iter().flatten().enumerate() {let kind = p["registryType"].as_str().unwrap_or_default();- if !matches!(kind, "npm" | "pypi" | "oci") || p["transport"]["type"].as_str().is_some_and(|t| t != "stdio") {+ if !matches!(kind, "npm" | "pypi" | "oci" | "nuget")+ || p["transport"]["type"].as_str().is_some_and(|t| t != "stdio")+ {continue;}- let inputs: Vec<Value> = p["environmentVariables"]- .as_array()- .into_iter()- .flatten()- .map(|e| {- json!({"name": e["name"], "description": e["description"], "secret": e["isSecret"].as_bool().unwrap_or(false),- "required": e["isRequired"].as_bool().unwrap_or(false), "default": e["default"]})- })- .collect();+ let env = p["environmentVariables"].as_array().into_iter().flatten().map(|e| {+ json!({"name": e["name"], "description": e["description"], "secret": e["isSecret"].as_bool().unwrap_or(false),+ "required": e["isRequired"].as_bool().unwrap_or(false), "default": e["default"]})+ });+ let args = ["runtimeArguments", "packageArguments"]+ .iter()+ .flat_map(|k| p[*k].as_array().into_iter().flatten())+ .filter_map(|a| {+ let key = argument_input(a)?;+ Some(json!({"name": key, "description": a["description"], "secret": a["isSecret"].as_bool().unwrap_or(false),+ "required": a["isRequired"].as_bool().unwrap_or(false), "default": a["default"],+ "placeholder": a["valueHint"]}))+ });+ let inputs: Vec<Value> = env.chain(args).collect();out.push(json!({"id": format!("package:{i}"), "kind": kind, "label": format!("{kind} · {}", p["identifier"].as_str().unwrap_or_default()), "inputs": inputs}));}for (i, r) in server["remotes"].as_array().into_iter().flatten().enumerate() {- if r["type"] != "streamable-http" || r["url"].as_str().is_none_or(|u| u.contains('{')) {+ if !matches!(r["type"].as_str(), Some("streamable-http" | "sse")) || r["url"].as_str().is_none() {continue;}- let inputs: Vec<Value> = r["headers"]- .as_array()- .into_iter()- .flatten()- .map(|h| {- json!({"name": h["name"], "description": h["description"], "secret": h["isSecret"].as_bool().unwrap_or(true),- "required": h["isRequired"].as_bool().unwrap_or(false), "placeholder": h["value"]})- })- .collect();+ // `{name}` parts of the URL are the user's to fill in.+ let variables = r["variables"].as_object().into_iter().flatten().map(|(k, v)| {+ json!({"name": k, "description": v["description"], "secret": v["isSecret"].as_bool().unwrap_or(false),+ "required": v["isRequired"].as_bool().unwrap_or(false), "default": v["default"]})+ });+ let headers = r["headers"].as_array().into_iter().flatten().map(|h| {+ json!({"name": h["name"], "description": h["description"], "secret": h["isSecret"].as_bool().unwrap_or(true),+ "required": h["isRequired"].as_bool().unwrap_or(false), "placeholder": h["value"]})+ });+ let inputs: Vec<Value> = variables.chain(headers).collect();out.push(json!({"id": format!("remote:{i}"), "kind": "remote", "label": "Hosted", "inputs": inputs}));}// Some servers list a remote per region; one of each kind is enough.@@ -264,6 +312,55 @@ fn install_options(server: &Value) -> Vec<Value> {out}+/// The input a registry argument asks the user for: a positional's hint, or a named+/// option's name. None when the registry fixes it (a set value, or a bare flag).+fn argument_input(a: &Value) -> Option<String> {+ if a["value"].is_string() {+ return None;+ }+ let text = |k: &str| a[k].as_str().filter(|s| !s.is_empty()).map(str::to_owned);+ match a["type"].as_str() {+ Some("named") => text("name").filter(|_| a["valueHint"].is_string() || a["default"].is_string()),+ _ => text("valueHint").or_else(|| text("name")).or_else(|| Some("value".into())),+ }+}++/// A registry argument list as command-line words, taking values from the user's inputs.+fn arguments(list: &Value, input: &dyn Fn(&str) -> Option<String>) -> Result<Vec<String>> {+ let mut out = vec![];+ for a in list.as_array().into_iter().flatten() {+ let named = a["type"] == "named";+ let name = a["name"].as_str().unwrap_or_default();+ let value = match argument_input(a) {+ None => a["value"].as_str().map(str::to_owned),+ Some(key) => match input(&key).or_else(|| a["default"].as_str().map(str::to_owned)) {+ Some(v) => Some(v),+ None if a["isRequired"].as_bool().unwrap_or(false) => bail!("{key} is required"),+ None => continue,+ },+ };+ if named && !name.is_empty() {+ out.push(name.to_owned());+ }+ out.extend(value);+ }+ Ok(out)+}++/// Puts the user's values into a URL's `{name}` parts, or their defaults.+fn fill_url(url: &str, variables: &Value, input: &dyn Fn(&str) -> Option<String>) -> Result<String> {+ let mut url = url.to_owned();+ for (k, v) in variables.as_object().into_iter().flatten() {+ let value =+ input(k).or_else(|| v["default"].as_str().map(str::to_owned)).ok_or_else(|| anyhow!("{k} is required"))?;+ url = url.replace(&format!("{{{k}}}"), &value);+ }+ if url.contains('{') {+ bail!("this server's URL has parts the registry doesn't describe; add it as a custom connector");+ }+ Ok(url)+}+/// "com.notion/mcp" -> "Notion", "io.github.microsoft/playwright-mcp" -> "Playwright".fn title_from_name(name: &str) -> String {let (org, last) = name.split_once('/').unwrap_or(("", name));@@ -306,22 +403,30 @@ fn listing(server: &Value, installed: &[Connector]) -> Option<Value> {}))}-/// Browse the MCP Registry: featured connectors, or a search.-pub async fn browse_connectors(store: &crate::store::Store, search: &str) -> Result<Value> {- let installed = connectors(store);- let servers = if search.trim().is_empty() {+/// Browse the whole MCP Registry a page at a time (featured connectors lead the first+/// page of the unfiltered list), or search it. `nextCursor` fetches the following page.+pub async fn browse_connectors(store: &crate::store::Store, search: &str, cursor: &str) -> Result<Value> {+ let installed = connectors(store)?;+ let search = search.trim();+ let mut servers: Vec<Value> = if search.is_empty() && cursor.is_empty() {let lookups = FEATURED.iter().map(|n| registry_server(n));futures::future::join_all(lookups).await.into_iter().filter_map(Result::ok).collect()} else {- registry_search(search.trim(), 60).await?+ vec![]};+ let (page, next) = registry_page(search, cursor, 60).await?;+ // Later pages of the unfiltered list skip the featured servers the first page led with.+ let shown_already = |s: &Value| {+ search.is_empty() && !cursor.is_empty() && FEATURED.contains(&s["name"].as_str().unwrap_or_default())+ };+ servers.extend(page.into_iter().filter(|s| !shown_already(s)));let mut seen = std::collections::HashSet::new();let items: Vec<Value> = servers.iter().filter(|s| seen.insert(s["name"].as_str().unwrap_or_default().to_owned())).filter_map(|s| listing(s, &installed)).collect();- Ok(json!({"items": items}))+ Ok(json!({"items": items, "nextCursor": next}))}/// Fills `{placeholder}` in a header template with the user's value, or uses it as-is.@@ -336,13 +441,21 @@ fn fill(template: Option<&str>, value: &str) -> String {}}+pub async fn connector_info(store: &crate::store::Store, name: &str) -> Result<Value> {+ let server = registry_server(name).await?;+ listing(&server, &connectors(store)?).ok_or_else(|| anyhow!("No supported installation option"))+}+/// Installs a registry server with the user's inputs (`{NAME: value}`).pub async fn install_connector(store: &crate::store::Store, name: &str, option: &str, inputs: &Value) -> Result<Value> {let server = registry_server(name).await?;- let input = |k: &str| inputs[k].as_str().map(str::trim).filter(|v| !v.is_empty()).map(str::to_owned);+ let input = |k: &str| inputs[k].as_str().filter(|v| !v.is_empty()).map(str::to_owned);let (kind, index) = option.split_once(':').ok_or_else(|| anyhow!("unknown install option"))?;let index: usize = index.parse()?;- let mut all = connectors(store);+ let all = connectors(store)?;+ if let Some(c) = all.iter().find(|c| c.registry_name.as_deref() == Some(name)) {+ return Ok(c.public());+ }let title =listing(&server, &all).and_then(|l| l["title"].as_str().map(str::to_owned)).unwrap_or_else(|| name.into());let mut c = Connector {@@ -378,29 +491,42 @@ pub async fn install_connector(store: &crate::store::Store, name: &str, option:None => {}}}- match p["registryType"].as_str() {- Some("npm") => {- c.command = Some("npx".into());- c.args = vec!["-y".into(), format!("{id}@{version}")];- }- Some("pypi") => {- c.command = Some("uvx".into());- c.args = vec![format!("{id}=={version}")];- }+ let runtime = arguments(&p["runtimeArguments"], &input)?;+ let package = arguments(&p["packageArguments"], &input)?;+ let (command, mut args) = match p["registryType"].as_str() {+ Some("npm") => ("npx", vec!["-y".to_owned()]),+ Some("pypi") => ("uvx", vec![]),Some("oci") => {- c.command = Some("docker".into());- c.args = vec!["run".into(), "-i".into(), "--rm".into()];+ let mut args = vec!["run".to_owned(), "-i".into(), "--rm".into()];for k in c.env.keys() {- c.args.extend(["-e".into(), k.clone()]);+ args.extend(["-e".into(), k.clone()]);}- c.args.push(id.to_owned());+ ("docker", args)}+ Some("nuget") => ("dnx", vec![]),_ => bail!("this package type isn't supported"),+ };+ // Runtime arguments come before the package; skip flags we already pass.+ for a in runtime {+ if !a.starts_with('-') || !args.contains(&a) {+ args.push(a);+ }}+ args.push(match p["registryType"].as_str() {+ Some("pypi") => format!("{id}=={version}"),+ Some("oci") => id.to_owned(),+ _ => format!("{id}@{version}"),+ });+ if p["registryType"] == "nuget" {+ args.push("--yes".into());+ }+ args.extend(package);+ c.command = Some(command.into());+ c.args = args;}"remote" => {let r = server["remotes"].get(index).ok_or_else(|| anyhow!("unknown remote"))?;- c.url = r["url"].as_str().map(str::to_owned);+ c.url = Some(fill_url(r["url"].as_str().unwrap_or_default(), &r["variables"], &input)?);for h in r["headers"].as_array().into_iter().flatten() {let Some(k) = h["name"].as_str() else { continue };match input(k) {@@ -419,16 +545,63 @@ pub async fn install_connector(store: &crate::store::Store, name: &str, option:{c.oauth = Some(oauth::OAuth::default());}- all.push(c.clone());- save(store, "connectors", &all)?;- Ok(c.public())+ add_connector(store, c)}/// A connector you describe yourself: a command line or an https URL.pub async fn add_custom_connector(store: &crate::store::Store, b: &Value) -> Result<Value> {let name =b["name"].as_str().map(str::trim).filter(|s| !s.is_empty()).ok_or_else(|| anyhow!("`name` is required"))?;- let mut all = connectors(store);+ let all = connectors(store)?;+ let c = custom(name, b, &all).await?;+ add_connector(store, c)+}++/// Adds every server in a pasted MCP config: the `mcpServers` / `servers` JSON that+/// Claude, Cursor, VS Code and most READMEs use, or one server's own entry.+pub async fn import_connectors(store: &crate::store::Store, config: &str) -> Result<Value> {+ let v: Value = serde_json::from_str(config.trim()).context("that isn't JSON")?;+ let servers = config_servers(&v);+ if servers.is_empty() {+ bail!("no MCP servers in that config");+ }+ let all = connectors(store)?;+ let mut pending = vec![];+ for (name, entry) in servers {+ pending.push(custom(&name, &entry, &all).await.with_context(|| name.clone())?);+ }+ update_connectors(store, |all| {+ let mut added = vec![];+ for mut c in pending {+ c.id = unique_id(&c.name, &all.iter().map(|c| c.id.clone()).collect::<Vec<_>>());+ added.push(c.public());+ all.push(c);+ }+ Ok(json!({"items":added}))+ })+}++/// The named server entries in a pasted config.+fn config_servers(v: &Value) -> Vec<(String, Value)> {+ match ["mcpServers", "servers", "context_servers"].iter().find_map(|k| v[*k].as_object()) {+ Some(map) => map.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),+ None if v["command"].is_string() || v["url"].is_string() => {+ vec![(v["name"].as_str().unwrap_or("Custom").to_owned(), v.clone())]+ }+ // `{"github": {"command": …}}`: the map without its wrapper.+ None => v+ .as_object()+ .into_iter()+ .flatten()+ .filter(|(_, e)| e.is_object())+ .map(|(k, e)| (k.clone(), e.clone()))+ .collect(),+ }+}++/// A connector from `{command, args?, env?}` or `{url, headers?}`. A command without+/// `args` is split like a shell would (quotes work).+async fn custom(name: &str, b: &Value, all: &[Connector]) -> Result<Connector> {let map = |v: &Value| -> BTreeMap<String, String> {v.as_object().into_iter().flatten().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned()))).collect()};@@ -444,34 +617,40 @@ pub async fn add_custom_connector(store: &crate::store::Store, b: &Value) -> Resheaders: map(&b["headers"]),oauth: None,};- if let Some(url) = b["url"].as_str().map(str::trim).filter(|s| !s.is_empty()) {- if !url.starts_with("https://") && !url.starts_with("http://localhost") && !url.starts_with("http://127.0.0.1")- {+ let url =+ ["url", "serverUrl", "httpUrl"].iter().find_map(|k| b[*k].as_str()).map(str::trim).filter(|s| !s.is_empty());+ if let Some(url) = url {+ let local = ["http://localhost", "http://127.0.0.1", "http://[::1]"].iter().any(|p| url.starts_with(p));+ if !url.starts_with("https://") && !local {bail!("remote connectors need an https URL");}if oauth::required(url, &c.headers).await {c.oauth = Some(oauth::OAuth::default());}c.url = Some(url.to_owned());- } else {- let line = b["command"]- .as_str()- .map(str::trim)- .filter(|s| !s.is_empty())- .ok_or_else(|| anyhow!("give a command or a URL"))?;- let mut parts = line.split_whitespace().map(str::to_owned);- c.command = parts.next();- c.args = parts.collect();+ return Ok(c);}- all.push(c.clone());- save(store, "connectors", &all)?;- Ok(c.public())+ let line = b["command"]+ .as_str()+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .ok_or_else(|| anyhow!("give a command or a URL"))?;+ let mut words = match b["args"].as_array() {+ Some(args) => {+ std::iter::once(line.to_owned()).chain(args.iter().filter_map(|a| a.as_str().map(str::to_owned))).collect()+ }+ None => shlex::split(line).ok_or_else(|| anyhow!("the command has an unclosed quote"))?,+ }+ .into_iter();+ c.command = words.next();+ c.args = words.collect();+ Ok(c)}/// Installed MCP servers, then the apps connected through Composio.-pub fn list_connectors(store: &crate::store::Store) -> Value {- let mut items: Vec<Value> = connectors(store).iter().map(Connector::public).collect();- items.extend(composio::connections(store).iter().filter(|c| c.active()).map(|c| {+pub fn list_connectors(store: &crate::store::Store) -> Result<Value> {+ let mut items: Vec<Value> = connectors(store)?.iter().map(Connector::public).collect();+ items.extend(composio::connections(store)?.iter().filter(|c| c.active()).map(|c| {json!({"id": format!("{}{}", composio::PREFIX, c.toolkit),"name": c.name,@@ -484,13 +663,14 @@ pub fn list_connectors(store: &crate::store::Store) -> Value {"logo": c.logo,})}));- json!({"items": items})+ Ok(json!({"items": items}))}pub fn remove_connector(store: &crate::store::Store, id: &str) -> Result<()> {- let mut all = connectors(store);- all.retain(|c| c.id != id);- save(store, "connectors", &all)+ update_connectors(store, |all| {+ all.retain(|c| c.id != id);+ Ok(())+ })}// MARK: skills@@ -661,6 +841,42 @@ pub fn skills_brief(store: &crate::store::Store, enabled: &[String]) -> Option<Smod tests {use super::*;+ #[test]+ fn registry_arguments_become_words() {+ let list = json!([+ {"type": "named", "name": "--rm"},+ {"type": "named", "name": "--db", "valueHint": "path", "isRequired": true},+ {"type": "named", "name": "--mode", "value": "ro"},+ {"type": "positional", "valueHint": "source", "isRequired": false},+ ]);+ let input = |k: &str| (k == "--db").then(|| "/tmp/a.db".to_owned());+ assert_eq!(arguments(&list, &input).unwrap(), ["--rm", "--db", "/tmp/a.db", "--mode", "ro"]);+ assert!(arguments(&list, &|_: &str| None).is_err(), "--db is required");+ assert_eq!(argument_input(&list[0]), None);+ assert_eq!(argument_input(&list[3]).as_deref(), Some("source"));+ }++ #[test]+ fn url_templates_fill_in() {+ let vars = json!({"agent_id": {"isRequired": true}, "region": {"default": "us"}});+ let input = |k: &str| (k == "agent_id").then(|| "a1".to_owned());+ assert_eq!(fill_url("https://x/{region}/{agent_id}/mcp", &vars, &input).unwrap(), "https://x/us/a1/mcp");+ assert!(fill_url("https://x/{agent_id}", &vars, &|_: &str| None).is_err());+ assert!(fill_url("https://x/{other}", &json!({}), &|_: &str| None).is_err());+ }++ #[test]+ fn pasted_configs_list_their_servers() {+ let claude = json!({"mcpServers": {"github": {"command": "npx", "args": ["-y", "x"]}, "linear": {"url": "https://l/mcp"}}});+ assert_eq!(config_servers(&claude).len(), 2);+ let vscode = json!({"servers": {"a": {"type": "sse", "url": "https://a/sse"}}});+ assert_eq!(config_servers(&vscode)[0].0, "a");+ let one = json!({"command": "uvx", "args": ["y"]});+ assert_eq!(config_servers(&one)[0].0, "Custom");+ let bare = json!({"fs": {"command": "npx"}});+ assert_eq!(config_servers(&bare)[0].0, "fs");+ }+#[test]fn slugs_are_safe() {assert_eq!(slug("GitHub MCP Server"), "github-mcp-server");@@ -704,7 +920,10 @@ mod tests {oauth: None,};let exe = std::path::Path::new("/bin/codync-host");- assert_eq!(c.acp(exe, 1).unwrap()["env"][0]["name"], "TOKEN");+ let config = c.acp(exe, 1).unwrap();+ assert_eq!(config["args"][1], "local");+ assert_eq!(config["env"], json!([]));+ assert!(!config.to_string().contains("secret"));assert!(c.public().get("env").is_none(), "secrets never leave the host");c.command = None;c.url = Some("https://example.com/mcp".into());diff --git a/host/src/market/oauth.rs b/host/src/market/oauth.rsindex a563f70b..dc76d70b 100644--- a/host/src/market/oauth.rs+++ b/host/src/market/oauth.rs@@ -107,6 +107,15 @@ pub async fn required(url: &str, headers: &std::collections::BTreeMap<String, Stfor (k, v) in headers {req = req.header(k, v);}+ let Ok(res) = req.send().await else { return false };+ if !matches!(res.status().as_u16(), 400 | 404 | 405) {+ return res.status() == reqwest::StatusCode::UNAUTHORIZED;+ }+ // Not streamable HTTP: ask the older SSE endpoint instead (the stream is dropped unread).+ let mut req = crate::http().get(url).header("accept", "text/event-stream").timeout(TIMEOUT);+ for (k, v) in headers {+ req = req.header(k, v);+ }req.send().await.is_ok_and(|r| r.status() == reqwest::StatusCode::UNAUTHORIZED)}@@ -171,17 +180,16 @@ fn text(v: &Value) -> Option<String> {}fn update(store: &Store, id: &str, f: impl FnOnce(&mut Connector)) -> Result<Connector> {- let mut all = market::connectors(store);- let c = all.iter_mut().find(|c| c.id == id).ok_or_else(|| anyhow!("unknown connector"))?;- f(c);- let out = c.clone();- market::save_connectors(store, &all)?;- Ok(out)+ market::update_connectors(store, |all| {+ let c = all.iter_mut().find(|c| c.id == id).ok_or_else(|| anyhow!("unknown connector"))?;+ f(c);+ Ok(c.clone())+ })}/// Starts signing in to connector `id`: the page to open.pub async fn start(store: &Store, port: u16, id: &str, callback: Callback) -> Result<Value> {- let c = market::connectors(store).into_iter().find(|c| c.id == id).ok_or_else(|| anyhow!("unknown connector"))?;+ let c = market::connectors(store)?.into_iter().find(|c| c.id == id).ok_or_else(|| anyhow!("unknown connector"))?;let url = c.url.clone().ok_or_else(|| anyhow!("{} runs on this computer; it has nothing to sign in to", c.name))?;let app = app_uri(store);let redirect_uri = match callback {@@ -278,7 +286,7 @@ pub async fn finish(store: &Store, state: &str, code: Option<&str>, error: Optiobail!("Sign-in didn't finish: {error}");}let code = code.ok_or_else(|| anyhow!("Sign-in didn't return a code"))?;- let c = market::connectors(store)+ let c = market::connectors(store)?.into_iter().find(|c| c.id == p.connector).ok_or_else(|| anyhow!("unknown connector"))?;@@ -316,8 +324,7 @@ async fn token_request(oauth: &OAuth, form: &[(&str, &str)]) -> Result<Value> {let status = res.status();let v: Value = res.json().await.unwrap_or(Value::Null);if !status.is_success() || !v["access_token"].is_string() {- let why = text(&v["error_description"]).or_else(|| text(&v["error"])).unwrap_or_else(|| status.to_string());- bail!("the sign-in server refused: {why}");+ bail!("The sign-in server refused the request ({status}). Reopen sign-in and try again.");}Ok(v)}@@ -352,9 +359,12 @@ pub fn sign_out(store: &Store, id: &str) -> Result<Connector> {/// What the `remote` MCP proxy sends to connector `id`: its URL and headers, with a fresh token./// `stale`: the server just said 401, so refresh even if the token looks valid.pub async fn target(store: &Store, id: &str, stale: bool) -> Result<Value> {- let c = market::connectors(store).into_iter().find(|c| c.id == id).ok_or_else(|| anyhow!("unknown connector"))?;+ let c = market::connectors(store)?.into_iter().find(|c| c.id == id).ok_or_else(|| anyhow!("unknown connector"))?;let url = c.url.clone().ok_or_else(|| anyhow!("{} isn't a remote connector", c.name))?;- let mut headers = c.headers.clone();+ let mut headers = std::collections::BTreeMap::new();+ for (k, v) in &c.headers {+ headers.insert(k.clone(), market::passwords::resolve(store, v).await?);+ }if let Some(o) = &c.oauth {let o = fresh(store, &c, o, stale).await?;headers.insert("Authorization".into(), format!("Bearer {}", o.access_token));@@ -373,7 +383,7 @@ async fn fresh(store: &Store, c: &Connector, o: &OAuth, stale: bool) -> Result<O}let _one = REFRESH.lock().await;// Someone else may have refreshed while we waited.- let current = market::connectors(store).into_iter().find(|x| x.id == c.id).and_then(|x| x.oauth);+ let current = market::connectors(store)?.into_iter().find(|x| x.id == c.id).and_then(|x| x.oauth);if let Some(cur) = ¤t&& cur.access_token != o.access_token&& cur.signed_in()diff --git a/host/src/market/passwords.rs b/host/src/market/passwords.rsnew file mode 100644index 00000000..d6fbc2aa--- /dev/null+++ b/host/src/market/passwords.rs@@ -0,0 +1,79 @@+//! Optional 1Password references. The service token is encrypted in the same vault;+//! references resolve only at the execution boundary and never enter transcripts.+use crate::store::Store;+use anyhow::{Result, anyhow, bail};+use serde_json::{Value, json};+use std::{process::Stdio, time::Duration};++pub fn status(store: &Store) -> Result<Value> {+ Ok(json!({"provider":if cfg!(target_os="macos") {"Keychain"} else {"Secret Service"},+ "onePasswordConnected":super::vault::read(store,"credential.1password")?.is_some_and(|s| !s.is_empty())}))+}++pub async fn set_token(store: &Store, token: &str) -> Result<Value> {+ if !token.is_empty() {+ let result = tokio::time::timeout(+ Duration::from_secs(20),+ tokio::process::Command::new("op")+ .args(["vault", "list", "--format", "json"])+ .env("OP_SERVICE_ACCOUNT_TOKEN", token)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .kill_on_drop(true)+ .status(),+ )+ .await;+ if !matches!(result, Ok(Ok(s)) if s.success()) {+ bail!(+ "Install the 1Password CLI on this computer and provide a service account token with access to your shared vault."+ );+ }+ }+ super::vault::write(store, "credential.1password", token)?;+ status(store)+}++pub async fn resolve(store: &Store, value: &str) -> Result<String> {+ if !value.starts_with("op://") {+ return Ok(value.to_owned());+ }+ if value.len() > 2048 || value.contains(['\n', '\r']) {+ bail!("Invalid 1Password reference");+ }+ let token = super::vault::read(store, "credential.1password")?+ .filter(|s| !s.is_empty())+ .ok_or_else(|| anyhow!("Connect 1Password in Credentials first"))?;+ let result = tokio::time::timeout(+ Duration::from_secs(20),+ tokio::process::Command::new("op")+ .args(["read", "--no-newline", value])+ .env("OP_SERVICE_ACCOUNT_TOKEN", token)+ .stdin(Stdio::null())+ .stderr(Stdio::null())+ .kill_on_drop(true)+ .output(),+ )+ .await+ .map_err(|_| anyhow!("1Password timed out"))?+ .map_err(|_| anyhow!("Install the 1Password CLI on this computer"))?;+ if !result.status.success() {+ bail!("Could not read the 1Password reference. Check shared vault access.");+ }+ String::from_utf8(result.stdout).map_err(|_| anyhow!("Invalid credential encoding"))+}++#[cfg(test)]+mod tests {+ use super::*;+ #[tokio::test]+ async fn ordinary_values_are_unchanged_and_references_require_a_connected_vault() {+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();+ assert_eq!(resolve(&store, " a secret with spaces ").await.unwrap(), " a secret with spaces ");+ assert!(resolve(&store, "op://shared/service/key").await.is_err());+ assert!(!status(&store).unwrap()["onePasswordConnected"].as_bool().unwrap());+ super::super::vault::write(&store, "credential.1password", "test-token").unwrap();+ assert!(status(&store).unwrap()["onePasswordConnected"].as_bool().unwrap());+ assert!(!status(&store).unwrap().to_string().contains("test-token"));+ }+}diff --git a/host/src/market/requests.rs b/host/src/market/requests.rsnew file mode 100644index 00000000..97e67dda--- /dev/null+++ b/host/src/market/requests.rs@@ -0,0 +1,302 @@+//! Durable, non-secret connection requests. Only the client submits credentials;+//! tools receive status, never credential values.+use super::connectors;+use crate::{+ agent::bot::Cmd,+ hub::Hub,+ store::{Entry, EntryKind, Lane, now_ms},+};+use anyhow::{Result, anyhow, bail};+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use std::sync::Arc;++pub const INSTRUCTIONS: &str = "Connect external services with search_connectors, list_connectors and request_connection. To update an installed connector's key use request_secret. Requests appear as secure cards in the user's conversation. Never ask for passwords or keys in ordinary chat or tool arguments. After requesting, finish your turn and wait; Codync resumes you after the user completes setup.";+#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+enum RequestKind {+ Connection,+ Secret,+ App,+}++#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+enum RequestStatus {+ Pending,+ Ready,+ Cancelled,+}++fn has_status(request: &Value, status: RequestStatus) -> bool {+ serde_json::from_value::<RequestStatus>(request["status"].clone()).ok() == Some(status)+}++const MAX_AGE: i64 = 24 * 60 * 60 * 1000;+static MUTATION: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());++pub fn tools() -> Value {+ json!([+ {"name":"search_connectors","description":"Find registry connectors by service name.","inputSchema":{"type":"object","properties":{"query":{"type":"string"}},"required":["query"]}},+ {"name":"list_connectors","description":"List installed connectors without credentials.","inputSchema":{"type":"object","properties":{}}},+ {"name":"request_connection","description":"Invite the user to install or authorize a connector. Supply either registryName from search or connectorId from the installed list.","inputSchema":{"type":"object","properties":{"registryName":{"type":"string"},"connectorId":{"type":"string"},"reason":{"type":"string"}},"required":["reason"]}},+ {"name":"request_app","description":"Invite the user to connect a hosted app through Composio, for example gmail or slack.","inputSchema":{"type":"object","properties":{"toolkit":{"type":"string"},"reason":{"type":"string"}},"required":["toolkit","reason"]}},+ {"name":"request_secret","description":"Ask the user to securely provide a credential for an installed connector. The value goes directly to that connector and is never returned to you.","inputSchema":{"type":"object","properties":{"connectorId":{"type":"string"},"field":{"type":"string"},"location":{"type":"string","enum":["env","header"]},"reason":{"type":"string"}},"required":["connectorId","field","location","reason"]}}+ ])+}++pub async fn call(hub: &Arc<Hub>, bot: &str, name: &str, args: &Value) -> Result<Value> {+ hub.store.bot(bot)?.filter(|b| !b.deleted && !b.config.is_group()).ok_or_else(|| anyhow!("unknown bot"))?;+ match name {+ "search_connectors" => super::browse_connectors(&hub.store, text(args, "query")?, "").await,+ "list_connectors" => super::list_connectors(&hub.store),+ "request_app" => {+ let toolkit = text(args, "toolkit")?.to_ascii_lowercase();+ if toolkit.len() > 100 || !toolkit.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-') {+ bail!("Invalid app identifier");+ }+ let lane = hub.runtime(bot).lane.unwrap_or_else(|| Lane::main(bot));+ let reason: String = text(args, "reason")?.chars().take(400).collect();+ let entry = hub.add_entry(&lane,EntryKind::Notice,hub.store.max_turn(bot),&json!({"text":reason,"connectionRequest":{+ "kind":RequestKind::App,"status":RequestStatus::Pending,"title":toolkit,"botId":bot,"toolkit":toolkit,"connectorId":format!("{}{}",super::composio::PREFIX,toolkit)+ }})).ok_or_else(|| anyhow!("Could not save connection request"))?;+ Ok(json!({"requestId":entry.id,"status":"waitingForUser"}))+ }+ "request_connection" | "request_secret" => {+ let installed = args["connectorId"].as_str().filter(|s| !s.is_empty());+ let (title, registry) = if let Some(id) = installed {+ let c = connectors(&hub.store)?+ .into_iter()+ .find(|c| c.id == id)+ .ok_or_else(|| anyhow!("unknown connector"))?;+ (c.name, c.registry_name)+ } else {+ let registry = text(args, "registryName")?;+ let item = super::connector_info(&hub.store, registry).await?;+ (item["title"].as_str().unwrap_or(registry).to_owned(), Some(registry.to_owned()))+ };+ let secret = name == "request_secret";+ if secret {+ if installed.is_none() {+ bail!("A secret request needs an installed connector");+ }+ let field = text(args, "field")?;+ if field.len() > 128 || !field.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') {+ bail!("Invalid credential field");+ }+ if !matches!(text(args, "location")?, "env" | "header") {+ bail!("Invalid credential destination");+ }+ }+ let lane = hub.runtime(bot).lane.unwrap_or_else(|| Lane::main(bot));+ let request = json!({"kind":if secret {RequestKind::Secret} else {RequestKind::Connection}, "status":RequestStatus::Pending, "title":title,+ "registryName":registry, "connectorId":installed, "botId":bot,+ "field":if secret {args["field"].clone()} else {Value::Null},+ "location":if secret {args["location"].clone()} else {Value::Null}});+ let reason: String = text(args, "reason")?.chars().take(400).collect();+ let entry = hub+ .add_entry(+ &lane,+ EntryKind::Notice,+ hub.store.max_turn(bot),+ &json!({"text":reason,"connectionRequest":request}),+ )+ .ok_or_else(|| anyhow!("Could not save connection request"))?;+ Ok(json!({"requestId":entry.id,"status":"waitingForUser"}))+ }+ _ => bail!("Unknown connection tool"),+ }+}++fn text<'a>(v: &'a Value, key: &str) -> Result<&'a str> {+ v[key].as_str().filter(|s| !s.is_empty()).ok_or_else(|| anyhow!("{key} is required"))+}++fn pending(hub: &Hub, id: &str, cancelling: bool) -> Result<Entry> {+ let e = hub.store.entry(id).ok_or_else(|| anyhow!("Unknown connection request"))?;+ if !has_status(&e.data["connectionRequest"], RequestStatus::Pending) {+ bail!("This request is already completed or cancelled");+ }+ if !cancelling && now_ms() - e.created_at > MAX_AGE {+ bail!("This request expired. Ask the bot for a new request.");+ }+ let bot = text(&e.data["connectionRequest"], "botId")?;+ hub.store.bot(bot)?.filter(|b| !b.deleted).ok_or_else(|| anyhow!("The requesting bot was removed"))?;+ Ok(e)+}++pub async fn finish(hub: &Arc<Hub>, args: &Value) -> Result<Value> {+ let _guard = MUTATION.lock().await;+ let id = text(args, "entryId")?;+ if let Some(entry) = hub.store.entry(id)+ && has_status(&entry.data["connectionRequest"], RequestStatus::Ready)+ {+ return Ok(json!({"entry":entry}));+ }+ let e = pending(hub, id, args["cancel"] == true)?;+ let request = &e.data["connectionRequest"];+ let kind: RequestKind = serde_json::from_value(request["kind"].clone())?;+ if args["cancel"] == true {+ let mut data = e.data.clone();+ data["connectionRequest"]["status"] = serde_json::to_value(RequestStatus::Cancelled)?;+ return Ok(json!({"entry":hub.set_entry(id, &data).ok_or_else(|| anyhow!("Could not cancel request"))?}));+ }+ let connector_id = request["connectorId"]+ .as_str()+ .or(args["connectorId"].as_str())+ .ok_or_else(|| anyhow!("Choose a connector"))?;+ if kind != RequestKind::App {+ super::update_connectors(&hub.store, |all| {+ let c = all.iter_mut().find(|c| c.id == connector_id).ok_or_else(|| anyhow!("Unknown connector"))?;+ if request["connectorId"].is_null() && request["registryName"].as_str() != c.registry_name.as_deref() {+ bail!("This connector does not match the request");+ }+ if kind == RequestKind::Secret {+ let value = text(args, "value")?;+ if value.len() > 64 * 1024 {+ bail!("Credential is too large");+ }+ let field = text(request, "field")?.to_owned();+ match text(request, "location")? {+ "env" if c.command.is_some() => {+ c.env.insert(field, value.to_owned());+ }+ "header" if c.url.is_some() => {+ c.headers.insert(field, value.to_owned());+ }+ _ => bail!("Credential destination does not match this connector"),+ }+ }+ Ok(())+ })?;+ }+ super::verify::verify(&hub.store, connector_id, hub.port).await?;+ let bot = text(request, "botId")?;+ let row = hub.store.bot(bot)?.ok_or_else(|| anyhow!("Unknown bot"))?;+ let mut enabled = row.config.connectors;+ if !enabled.iter().any(|s| s == connector_id) {+ enabled.push(connector_id.to_owned());+ }+ hub.update_bot(&json!({"id":bot,"connectors":enabled}))?;+ hub.send_cmd(bot, Cmd::RefreshTools)?;+ let mut data = e.data.clone();+ data["connectionRequest"]["status"] = serde_json::to_value(RequestStatus::Ready)?;+ let entry = hub.set_entry(id, &data).ok_or_else(|| anyhow!("Could not complete request"))?;+ let lane = Lane { chat: e.bot_id, thread: e.thread_id };+ let text = format!(+ "[Connection setup completed: {}. Credentials were submitted securely and are not in this conversation. Continue the task.]",+ request["title"].as_str().unwrap_or("Connector")+ );+ let (ack, added) = hub.add_entry_once(+ &format!("connection-ack-{id}"),+ &lane,+ EntryKind::User,+ &json!({"text":text,"status":"queued"}),+ )?;+ if added {+ hub.send_cmd(bot, Cmd::Send { lane, entry_id: ack.id, text })?;+ }+ Ok(json!({"entry":entry}))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::store::{BotConfig, Store};+ use std::path::{Path, PathBuf};++ fn fixture() -> (Arc<Hub>, PathBuf) {+ let dir = std::env::temp_dir().join(format!("codync-credentials-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let store = Store::open(Path::new(":memory:")).unwrap();+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");+ let cfg: BotConfig = serde_json::from_value(json!({"id":"bot","name":"bot","backend":"fixture","cwd":dir,"command":format!("python3 -u '{}'",agent.display()),"notify":false})).unwrap();+ store.save_bot(&cfg).unwrap();+ let c: super::super::Connector = serde_json::from_value(json!({"id":"fixture","name":"Fixture","command":"python3","args":[PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/credential_mcp.py")]})).unwrap();+ super::super::save_connectors(&store, &[c]).unwrap();+ let hub = Hub::new(+ store,+ "test".into(),+ crate::remote::identity::Identity::load_or_create(&dir).unwrap(),+ "test".into(),+ 19222,+ );+ hub.start().unwrap();+ (hub, dir)+ }++ #[tokio::test]+ async fn secure_submission_enables_connector_and_resumes_only_once() {+ let (hub, dir) = fixture();+ let r = call(+ &hub,+ "bot",+ "request_secret",+ &json!({"connectorId":"fixture","field":"API_KEY","location":"env","reason":"Connect the test service"}),+ )+ .await+ .unwrap();+ let id = r["requestId"].as_str().unwrap();+ let submitted = json!({"entryId":id,"value":"test-private-key"});+ let first = finish(&hub, &submitted).await.unwrap();+ assert_eq!(first["entry"]["data"]["connectionRequest"]["status"], "ready");+ assert!(!first.to_string().contains("test-private-key"));+ assert!(hub.store.bot("bot").unwrap().unwrap().config.connectors.contains(&"fixture".to_owned()));+ assert!(!hub.store.kv_read("connectors").unwrap().unwrap().contains("test-private-key"));+ finish(&hub, &submitted).await.unwrap();+ let history = hub.store.history("bot", i64::MAX, 100).unwrap();+ assert_eq!(history.iter().filter(|e| e.id == format!("connection-ack-{id}")).count(), 1);+ assert!(!serde_json::to_string(&history).unwrap().contains("test-private-key"));+ hub.shutdown().await;+ std::fs::remove_dir_all(dir).unwrap();+ }++ #[test]+ fn remote_control_devices_cannot_retrieve_credentials_or_forge_requests() {+ let caller =+ crate::api::devices::Caller::Device { key: "test".into(), scopes: vec![crate::store::Scope::Control] };+ for method in ["connectorRuntime", "connectorTarget", "connectorCall"] {+ assert!(crate::api::devices::permit(&caller, method).is_err());+ }+ assert!(crate::api::devices::permit(&caller, "connectorRequestFinish").is_ok());+ }++ #[tokio::test]+ async fn cancellation_rejects_later_secret_submission() {+ let (hub, dir) = fixture();+ let r = call(+ &hub,+ "bot",+ "request_secret",+ &json!({"connectorId":"fixture","field":"API_KEY","location":"env","reason":"Test"}),+ )+ .await+ .unwrap();+ let id = &r["requestId"];+ finish(&hub, &json!({"entryId":id,"cancel":true})).await.unwrap();+ assert!(finish(&hub, &json!({"entryId":id,"value":"test-private-key"})).await.is_err());+ assert!(connectors(&hub.store).unwrap()[0].env.is_empty());+ hub.shutdown().await;+ std::fs::remove_dir_all(dir).unwrap();+ }++ #[tokio::test]+ async fn failed_verification_does_not_enable_connector_or_resume() {+ let (hub, dir) = fixture();+ let r = call(+ &hub,+ "bot",+ "request_secret",+ &json!({"connectorId":"fixture","field":"API_KEY","location":"env","reason":"Test"}),+ )+ .await+ .unwrap();+ let id = r["requestId"].as_str().unwrap();+ assert!(finish(&hub, &json!({"entryId":id,"value":"wrong"})).await.is_err());+ assert_eq!(hub.store.entry(id).unwrap().data["connectionRequest"]["status"], "pending");+ assert!(hub.store.bot("bot").unwrap().unwrap().config.connectors.is_empty());+ assert!(hub.store.entry(&format!("connection-ack-{id}")).is_none());+ hub.shutdown().await;+ std::fs::remove_dir_all(dir).unwrap();+ }+}diff --git a/host/src/market/vault.rs b/host/src/market/vault.rsnew file mode 100644index 00000000..11981879--- /dev/null+++ b/host/src/market/vault.rs@@ -0,0 +1,140 @@+//! Encrypted records backed by the operating system credential store. The database+//! contains ciphertext only; its random master key lives in Keychain/Secret Service.+use crate::{LockExt, store::Store};+use anyhow::{Result, anyhow, bail};+use base64::{Engine, engine::general_purpose::STANDARD};+use chacha20poly1305::{+ XChaCha20Poly1305, XNonce,+ aead::{Aead, KeyInit, Payload},+};+use std::sync::Arc;+use zeroize::Zeroizing;++const PREFIX: &str = "vault:v1:";+const SERVICE: &str = "dev.codync.credentials";++pub async fn unlock(hub: Arc<crate::hub::Hub>) -> Result<()> {+ if hub.store.secret_key.locked().is_some() {+ return Ok(());+ }+ tokio::task::spawn_blocking(move || {+ let store = &hub.store;+ let mut cache = store.secret_key.locked();+ if cache.is_some() { return Ok(()); }+ let id = if let Some(id) = store.kv_read("vault.id")? { id } else {+ let id = uuid::Uuid::new_v4().to_string();+ store.kv_set("vault.id", &id)?;+ id+ };+ let entry = keyring::Entry::new(SERVICE, &id).map_err(|_| unavailable())?;+ let key = match entry.get_secret() {+ Ok(key) => key,+ Err(keyring::Error::NoEntry) => {+ if store.kv_read("vault.initialized")?.is_some() {+ bail!("The credential key is missing. Restore this computer's keychain; encrypted credentials were preserved.");+ }+ let mut key = vec![0; 32];+ getrandom::fill(&mut key).map_err(|_| anyhow!("Could not generate credential key"))?;+ entry.set_secret(&key).map_err(|_| unavailable())?;+ key+ }+ Err(_) => return Err(unavailable()),+ };+ if key.len() != 32 { bail!("Invalid credential key; restore this computer's keychain."); }+ store.kv_set("vault.initialized", "true")?;+ *cache = Some(Zeroizing::new(key));+ Ok(())+ }).await??;+ Ok(())+}++fn unavailable() -> anyhow::Error {+ anyhow!(+ "Secure credential storage is locked or unavailable. Unlock Keychain on macOS, or start and unlock a Secret Service keyring in this Linux user's D-Bus session. Credentials are never saved as plain text."+ )+}++pub fn read(store: &Store, slot: &str) -> Result<Option<String>> {+ let Some(raw) = store.kv_read(slot)? else {+ return Ok(None);+ };+ if !raw.starts_with(PREFIX) {+ // Move existing host configuration into the vault before returning it.+ write(store, slot, &raw)?;+ return Ok(Some(raw));+ }+ let key = store.secret_key.locked();+ let key = key.as_ref().ok_or_else(unavailable)?;+ let bytes = STANDARD.decode(&raw[PREFIX.len()..]).map_err(|_| anyhow!("Invalid encrypted credential record"))?;+ if bytes.len() < 24 {+ bail!("Invalid encrypted credential record");+ }+ let cipher = XChaCha20Poly1305::new_from_slice(key).map_err(|_| unavailable())?;+ let plain = cipher+ .decrypt(+ &XNonce::try_from(&bytes[..24]).map_err(|_| anyhow!("Invalid credential nonce"))?,+ Payload { msg: &bytes[24..], aad: slot.as_bytes() },+ )+ .map_err(|_| anyhow!("Could not decrypt credentials; the stored record was preserved"))?;+ Ok(Some(String::from_utf8(plain)?))+}++pub fn write(store: &Store, slot: &str, value: &str) -> Result<()> {+ let key = store.secret_key.locked();+ let key = key.as_ref().ok_or_else(unavailable)?;+ let cipher = XChaCha20Poly1305::new_from_slice(key).map_err(|_| unavailable())?;+ let mut nonce = [0; 24];+ getrandom::fill(&mut nonce).map_err(|_| anyhow!("Could not generate credential nonce"))?;+ let sealed = cipher+ .encrypt(&nonce.into(), Payload { msg: value.as_bytes(), aad: slot.as_bytes() })+ .map_err(|_| anyhow!("Could not encrypt credentials"))?;+ let bytes: Vec<u8> = nonce.into_iter().chain(sealed).collect();+ store.kv_set(slot, &format!("{PREFIX}{}", STANDARD.encode(bytes)))+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ #[ignore = "requires an unlocked OS keychain or Secret Service session"]+ fn platform_keyring_roundtrip() {+ let id = format!("test-{}", uuid::Uuid::new_v4());+ let entry = keyring::Entry::new(SERVICE, &id).unwrap();+ let key = [42u8; 32];+ entry.set_secret(&key).unwrap();+ let loaded = entry.get_secret().unwrap();+ entry.delete_credential().unwrap();+ assert_eq!(loaded, key);+ assert!(matches!(entry.get_secret(), Err(keyring::Error::NoEntry)));+ }++ #[test]+ fn existing_plaintext_is_migrated_before_use() {+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();+ store.kv_set("record", "private password").unwrap();+ assert_eq!(read(&store, "record").unwrap().as_deref(), Some("private password"));+ assert!(store.kv_read("record").unwrap().unwrap().starts_with(PREFIX));+ }++ #[test]+ fn ciphertext_is_random_and_bound_to_its_record() {+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();+ write(&store, "one", "private password").unwrap();+ let first = store.kv_read("one").unwrap().unwrap();+ assert!(!first.contains("private password"));+ assert_eq!(read(&store, "one").unwrap().as_deref(), Some("private password"));+ write(&store, "one", "private password").unwrap();+ assert_ne!(first, store.kv_read("one").unwrap().unwrap());+ store.kv_set("two", &first).unwrap();+ assert!(read(&store, "two").is_err());+ }+ #[test]+ fn locked_storage_preserves_existing_data() {+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();+ store.kv_set("record", "existing secret").unwrap();+ *store.secret_key.locked() = None;+ assert!(read(&store, "record").is_err());+ assert!(write(&store, "record", "replacement").is_err());+ assert_eq!(store.kv_read("record").unwrap().as_deref(), Some("existing secret"));+ }+}diff --git a/host/src/market/verify.rs b/host/src/market/verify.rsnew file mode 100644index 00000000..8b1e0869--- /dev/null+++ b/host/src/market/verify.rs@@ -0,0 +1,93 @@+//! Check the MCP handshake and tool discovery before reporting a connector ready.+use crate::store::Store;+use anyhow::{Result, anyhow, bail};+use serde_json::{Value, json};+use std::{process::Stdio, time::Duration};+use tokio::{+ io::{AsyncBufReadExt, AsyncWriteExt, BufReader},+ process::Command,+};++pub async fn verify(store: &Store, id: &str, port: u16) -> Result<Value> {+ if let Some(toolkit) = id.strip_prefix(super::composio::PREFIX) {+ let connections = super::composio::refresh(store).await?;+ if connections.iter().any(|c| c.toolkit == toolkit && c.active()) {+ return Ok(json!({"status":"ready"}));+ }+ bail!("Finish signing in before checking this connection.");+ }+ let c = super::connectors(store)?.into_iter().find(|c| c.id == id).ok_or_else(|| anyhow!("Unknown connector"))?;+ if c.oauth.as_ref().is_some_and(|o| !o.signed_in()) {+ bail!("Sign in before checking this connection.");+ }+ let mut command = if let Some(exe) = &c.command {+ let mut command = Command::new(exe);+ command.args(&c.args);+ for (name, value) in &c.env {+ command.env(name, super::passwords::resolve(store, value).await?);+ }+ command+ } else {+ let mut command = Command::new(std::env::current_exe()?);+ command.args(["mcp", "remote", "--connector", id, "--port", &port.to_string()]);+ command+ };+ let mut child = command+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .kill_on_drop(true)+ .spawn()+ .map_err(|_| anyhow!("Could not start the connector. Install its runtime on this computer and retry."))?;+ let mut input = child.stdin.take().ok_or_else(|| anyhow!("Connector input unavailable"))?;+ let output = child.stdout.take().ok_or_else(|| anyhow!("Connector output unavailable"))?;+ let mut lines = BufReader::new(output).lines();+ let check = async {+ for (id, method, params) in [+ (+ 1,+ "initialize",+ json!({"protocolVersion":crate::mcp::PROTOCOL_VERSION,"capabilities":{},"clientInfo":{"name":"Codync","version":env!("CARGO_PKG_VERSION")}}),+ ),+ (2, "tools/list", json!({})),+ ] {+ let wire = format!("{}\n", json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}));+ input.write_all(wire.as_bytes()).await?;+ input.flush().await?;+ loop {+ let line = lines.next_line().await?.ok_or_else(|| anyhow!("Connector exited during setup"))?;+ if line.len() > 4 * 1024 * 1024 {+ bail!("Connector response too large");+ }+ let Ok(reply) = serde_json::from_str::<Value>(&line) else {+ continue;+ };+ if reply["id"] != id {+ continue;+ }+ if reply.get("error").is_some() {+ bail!("Connector rejected setup. Check its credentials and try again.");+ }+ if id == 1 {+ if !reply["result"]["protocolVersion"].is_string() {+ bail!("Invalid MCP handshake");+ }+ input.write_all(b"{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n").await?;+ } else {+ let tools = reply["result"]["tools"]+ .as_array()+ .ok_or_else(|| anyhow!("Connector did not return its tools"))?;+ return Ok(json!({"status":"ready","toolCount":tools.len()}));+ }+ break;+ }+ }+ bail!("Connector verification did not complete")+ };+ let result = tokio::time::timeout(Duration::from_secs(90), check)+ .await+ .map_err(|_| anyhow!("Connector setup timed out. Check the runtime and connection, then retry."));+ let _ = child.kill().await;+ let _ = child.wait().await;+ result?+}diff --git a/host/src/mcp.rs b/host/src/mcp.rsindex 8bea86e6..56367657 100644--- a/host/src/mcp.rs+++ b/host/src/mcp.rs@@ -11,6 +11,7 @@ pub const PROTOCOL_VERSION: &str = "2025-06-18";#[derive(Clone, Copy)]pub enum Server {+ Connectors,Routines,Computer,Team,@@ -106,6 +107,9 @@ pub async fn serve(bot: String, port: u16, server: Server) -> Result<()> {let mut lines = BufReader::new(tokio::io::stdin()).lines();let mut out = tokio::io::stdout();let (name, instructions, available_tools) = match server {+ Server::Connectors => {+ ("codync-connectors", crate::market::requests::INSTRUCTIONS, crate::market::requests::tools())+ }Server::Computer => ("codync-computer", INSTRUCTIONS, tools()),Server::Routines => ("codync-routines", crate::routines::INSTRUCTIONS, crate::routines::tools()),Server::Team => ("codync-team", crate::chat::team::INSTRUCTIONS, crate::chat::team::tools()),@@ -151,6 +155,7 @@ async fn call(port: u16, token: &str, bot: &str, params: &Value, server: Server)"arguments": params.get("arguments").filter(|a| a.is_object()).cloned().unwrap_or_else(|| json!({})),});let (method, timeout) = match server {+ Server::Connectors => ("connectorCall", Duration::from_secs(90)),Server::Routines => ("routineCall", Duration::from_secs(30)),Server::Computer => ("computerCall", Duration::from_secs(60)),Server::Team => ("teamCall", crate::chat::team::ASK_TIMEOUT + Duration::from_secs(30)),@@ -170,7 +175,7 @@ async fn call(port: u16, token: &str, bot: &str, params: &Value, server: Server)Ok(v) if ok => {return match server {Server::Computer => json!({"content": v["content"]}),- Server::Team | Server::Routines => {+ Server::Team | Server::Routines | Server::Connectors => {json!({"content": [{"type": "text", "text": v.to_string()}]})}Server::Composio => json!({"content": [{"type": "text", "text": v["result"].to_string()}]}),@@ -186,128 +191,316 @@ async fn call(port: u16, token: &str, bot: &str, params: &Value, server: Server)}/// `codync-host mcp remote`: a stdio MCP server that forwards every message to a remote-/// (streamable HTTP) connector with the headers and fresh sign-in token the host gives it.+/// connector with the headers and fresh sign-in token the host gives it. Speaks streamable+/// HTTP, and falls back to the older HTTP+SSE transport when the server doesn't.pub async fn serve_remote(connector: String, port: u16) -> Result<()> {let token = std::fs::read_to_string(crate::service::data_dir().join("token")).unwrap_or_default();- let token = token.trim().to_owned();+ let remote = Remote { port, token: token.trim().to_owned(), connector };+ // Both transports answer through one writer: the SSE one answers from its own stream.+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Value>();+ let writer = tokio::spawn(async move {+ let mut out = tokio::io::stdout();+ while let Some(reply) = rx.recv().await {+ let mut line = serde_json::to_vec(&reply)?;+ line.push(b'\n');+ out.write_all(&line).await?;+ out.flush().await?;+ }+ anyhow::Ok(())+ });let mut lines = BufReader::new(tokio::io::stdin()).lines();- let mut out = tokio::io::stdout();let mut session: Option<String> = None;+ // The POST endpoint of a server on the older SSE transport, and the task reading its stream.+ let mut legacy: Option<String> = None;+ let mut stream: Option<tokio::task::JoinHandle<()>> = None;while let Some(line) = lines.next_line().await? {let Ok(msg) = serde_json::from_str::<Value>(&line) else { continue };- let replies = match forward(port, &token, &connector, &msg, &mut session).await {- Ok(replies) => replies,- // Only requests get an answer; a failed notification is dropped.- Err(e) => match msg.get("id").filter(|id| !id.is_null()) {- Some(id) => {- vec![json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32603, "message": format!("{e:#}")}})]- }- None => vec![],+ let replies = match &legacy {+ Some(endpoint) => remote.post_legacy(endpoint, &msg).await,+ None => match remote.forward(&msg, &mut session).await {+ Ok(Some(replies)) => Ok(replies),+ Ok(None) => match remote.open_legacy(tx.clone()).await {+ Ok((endpoint, reader)) => {+ let replies = remote.post_legacy(&endpoint, &msg).await;+ legacy = Some(endpoint);+ stream = Some(reader);+ replies+ }+ Err(e) => Err(e),+ },+ Err(e) => Err(e),},};+ let replies = replies.unwrap_or_else(|e| match msg.get("id").filter(|id| !id.is_null()) {+ // Only requests get an answer; a failed notification is dropped.+ Some(id) => {+ vec![json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32603, "message": format!("{e:#}")}})]+ }+ None => vec![],+ });for reply in replies {- let mut line = serde_json::to_vec(&reply)?;- line.push(b'\n');- out.write_all(&line).await?;+ tx.send(reply)?;}- out.flush().await?;}+ // The agent is gone: stop reading the stream, then write what's left.+ if let Some(reader) = stream {+ reader.abort();+ let _ = reader.await;+ }+ drop(tx);+ writer.await??;Ok(())}-/// Sends one message; returns what the server answered (JSON, or the events of an SSE stream).-async fn forward(+struct Remote {port: u16,- token: &str,- connector: &str,- msg: &Value,- session: &mut Option<String>,-) -> Result<Vec<Value>> {- use futures::StreamExt as _;- for stale in [false, true] {- let target = crate::http()- .post(format!("http://127.0.0.1:{port}/api/connectorTarget"))- .bearer_auth(token)- .json(&json!({"id": connector, "stale": stale}))+ token: String,+ connector: String,+}++impl Remote {+ /// The connector's URL and headers, with a fresh sign-in token (`stale` forces a refresh).+ async fn target(&self, stale: bool) -> Result<(String, reqwest::header::HeaderMap)> {+ let res = crate::http()+ .post(format!("http://127.0.0.1:{}/api/connectorTarget", self.port))+ .bearer_auth(&self.token)+ .json(&json!({"id": self.connector, "stale": stale})).timeout(Duration::from_secs(30)).send().await.map_err(|e| anyhow::anyhow!("can't reach the Codync host: {e}"))?;- let ok = target.status().is_success();- let target: Value = target.json().await?;+ let ok = res.status().is_success();+ let target: Value = res.json().await?;if !ok {anyhow::bail!("{}", target["error"].as_str().unwrap_or("the Codync host refused"));}- let url = target["url"].as_str().unwrap_or_default();- let mut req = crate::http()- .post(url)- .header("accept", "application/json, text/event-stream")- .json(msg)- .timeout(Duration::from_secs(600));+ let mut headers = reqwest::header::HeaderMap::new();for (k, v) in target["headers"].as_object().into_iter().flatten() {- req = req.header(k.as_str(), v.as_str().unwrap_or_default());- }- if let Some(s) = session.as_deref() {- req = req.header("mcp-session-id", s);- }- let res = req.send().await.map_err(|e| anyhow::anyhow!("can't reach {url}: {e}"))?;- if res.status() == reqwest::StatusCode::UNAUTHORIZED && !stale {- continue;- }- if res.status() == reqwest::StatusCode::NOT_FOUND && session.is_some() && !stale {- // The server forgot our session; start over without it.- *session = None;- continue;- }- if let Some(s) = res.headers().get("mcp-session-id").and_then(|v| v.to_str().ok()) {- *session = Some(s.to_owned());+ headers.insert(+ reqwest::header::HeaderName::from_bytes(k.as_bytes())?,+ reqwest::header::HeaderValue::from_str(v.as_str().unwrap_or_default())?,+ );}- if !res.status().is_success() {- anyhow::bail!("{url} answered {}", res.status());- }- let sse = res- .headers()- .get("content-type")- .and_then(|v| v.to_str().ok())- .is_some_and(|t| t.starts_with("text/event-stream"));- if !sse {- let body = res.bytes().await?;- if body.is_empty() {- return Ok(vec![]);+ Ok((target["url"].as_str().unwrap_or_default().to_owned(), headers))+ }++ /// Sends one message over streamable HTTP; returns what the server answered (JSON, or+ /// the events of an SSE stream). None: the server doesn't speak streamable HTTP.+ async fn forward(&self, msg: &Value, session: &mut Option<String>) -> Result<Option<Vec<Value>>> {+ for stale in [false, true] {+ let (url, headers) = self.target(stale).await?;+ let mut req = crate::http()+ .post(&url)+ .headers(headers)+ .header("accept", "application/json, text/event-stream")+ .json(msg)+ .timeout(Duration::from_secs(600));+ if let Some(s) = session.as_deref() {+ req = req.header("mcp-session-id", s);}- return Ok(match serde_json::from_slice::<Value>(&body)? {- Value::Array(all) => all,- one => vec![one],- });- }- // Read events until the answer to this request arrives (servers may keep the stream open).- let id = msg.get("id").filter(|id| !id.is_null());- let mut got = vec![];- let mut buf = String::new();- let mut stream = res.bytes_stream();- while let Some(chunk) = stream.next().await {- buf.push_str(&String::from_utf8_lossy(&chunk?).replace("\r\n", "\n"));- while let Some(end) = buf.find("\n\n") {- let event: String = buf.drain(..end + 2).collect();+ let res = req.send().await.map_err(|e| anyhow::anyhow!("can't reach {url}: {e}"))?;+ if res.status() == reqwest::StatusCode::UNAUTHORIZED && !stale {+ continue;+ }+ if res.status() == reqwest::StatusCode::NOT_FOUND && session.is_some() && !stale {+ // The server forgot our session; start over without it.+ *session = None;+ continue;+ }+ // The spec's test for an older server: its first POST fails with one of these.+ if session.is_none() && matches!(res.status().as_u16(), 400 | 404 | 405) {+ return Ok(None);+ }+ if let Some(s) = res.headers().get("mcp-session-id").and_then(|v| v.to_str().ok()) {+ *session = Some(s.to_owned());+ }+ if !res.status().is_success() {+ anyhow::bail!("{url} answered {}", res.status());+ }+ if !is_sse(&res) {+ return Ok(Some(json_replies(&res.bytes().await?)?));+ }+ // Read events until the answer to this request arrives (servers may keep the stream open).+ let id = msg.get("id").filter(|id| !id.is_null());+ let mut got = vec![];+ let mut events = Events::new(res);+ while let Some(event) = events.next().await? {if let Some(v) = sse_data(&event) {let done = id.is_some_and(|id| v.get("id") == Some(id) && v.get("method").is_none());got.push(v);if done {- return Ok(got);+ break;+ }+ }+ }+ return Ok(Some(got));+ }+ anyhow::bail!("{} still refuses the sign-in; sign in again in Marketplace", self.connector)+ }++ /// Opens the older transport's event stream, which carries every answer from now on+ /// (sent to `tx`); returns the URL messages are posted to and the task reading the stream.+ async fn open_legacy(+ &self,+ tx: tokio::sync::mpsc::UnboundedSender<Value>,+ ) -> Result<(String, tokio::task::JoinHandle<()>)> {+ for stale in [false, true] {+ let (url, headers) = self.target(stale).await?;+ let res = crate::http()+ .get(&url)+ .headers(headers)+ .header("accept", "text/event-stream")+ .send()+ .await+ .map_err(|e| anyhow::anyhow!("can't reach {url}: {e}"))?;+ if res.status() == reqwest::StatusCode::UNAUTHORIZED && !stale {+ continue;+ }+ if !res.status().is_success() || !is_sse(&res) {+ anyhow::bail!("{url} speaks neither streamable HTTP nor SSE ({})", res.status());+ }+ let mut events = Events::new(res);+ let endpoint = loop {+ let event =+ events.next().await?.ok_or_else(|| anyhow::anyhow!("{url} closed before naming its endpoint"))?;+ if event.lines().any(|l| l.trim() == "event: endpoint" || l.trim() == "event:endpoint") {+ let path = sse_text(&event);+ break reqwest::Url::parse(&url)?.join(path.trim())?.to_string();+ }+ };+ let connector = self.connector.clone();+ let reader = tokio::spawn(async move {+ while let Ok(Some(event)) = events.next().await {+ if let Some(v) = sse_data(&event)+ && tx.send(v).is_err()+ {+ return;}}+ // ponytail: the session lives on this stream, so losing it ends the proxy and the+ // agent sees the server exit. Reconnect and re-initialize if that proves too blunt.+ eprintln!("{connector}: the server closed its event stream");+ std::process::exit(1);+ });+ return Ok((endpoint, reader));+ }+ anyhow::bail!("{} still refuses the sign-in; sign in again in Marketplace", self.connector)+ }++ /// Posts one message on the older transport. Answers normally arrive on the stream;+ /// a server that answers in the body is heard too.+ async fn post_legacy(&self, endpoint: &str, msg: &Value) -> Result<Vec<Value>> {+ for stale in [false, true] {+ let (_, headers) = self.target(stale).await?;+ let res = crate::http()+ .post(endpoint)+ .headers(headers)+ .json(msg)+ .timeout(Duration::from_secs(60))+ .send()+ .await+ .map_err(|e| anyhow::anyhow!("can't reach {endpoint}: {e}"))?;+ if res.status() == reqwest::StatusCode::UNAUTHORIZED && !stale {+ continue;+ }+ if !res.status().is_success() {+ anyhow::bail!("{endpoint} answered {}", res.status());}+ let body = res.bytes().await?;+ return Ok(json_replies(&body).unwrap_or_default());}- return Ok(got);+ anyhow::bail!("{} still refuses the sign-in; sign in again in Marketplace", self.connector)+ }+}++fn is_sse(res: &reqwest::Response) -> bool {+ res.headers().get("content-type").and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/event-stream"))+}++/// A JSON body as messages (one, or a batch); an empty body is none.+fn json_replies(body: &[u8]) -> Result<Vec<Value>> {+ if body.iter().all(u8::is_ascii_whitespace) {+ return Ok(vec![]);}- anyhow::bail!("{connector} still refuses the sign-in; sign in again in Marketplace")+ Ok(match serde_json::from_slice::<Value>(body)? {+ Value::Array(all) => all,+ one => vec![one],+ })+}++/// The raw events of an SSE response, one at a time.+struct Events {+ res: reqwest::Response,+ buf: String,+}++impl Events {+ fn new(res: reqwest::Response) -> Self {+ Self { res, buf: String::new() }+ }++ async fn next(&mut self) -> Result<Option<String>> {+ loop {+ if let Some(end) = self.buf.find("\n\n") {+ return Ok(Some(self.buf.drain(..end + 2).collect()));+ }+ match self.res.chunk().await? {+ Some(chunk) => self.buf.push_str(&String::from_utf8_lossy(&chunk).replace("\r\n", "\n")),+ None => return Ok(None),+ }+ }+ }+}++/// One SSE event's `data:` lines, joined.+fn sse_text(event: &str) -> String {+ event+ .lines()+ .filter_map(|l| l.strip_prefix("data:"))+ .map(|d| d.strip_prefix(' ').unwrap_or(d))+ .collect::<Vec<_>>()+ .join("\n")}/// The JSON in one SSE event's `data:` lines.fn sse_data(event: &str) -> Option<Value> {- let data: Vec<&str> =- event.lines().filter_map(|l| l.strip_prefix("data:")).map(|d| d.strip_prefix(' ').unwrap_or(d)).collect();- serde_json::from_str(&data.join("\n")).ok()+ serde_json::from_str(&sse_text(event)).ok()+}++/// Inject secrets into the connector process, never the agent's MCP definition.+pub async fn serve_local(connector: String, port: u16) -> Result<()> {+ use std::process::Stdio;+ let token = tokio::fs::read_to_string(crate::service::data_dir().join("token")).await?;+ let res = crate::http()+ .post(format!("http://127.0.0.1:{port}/api/connectorRuntime"))+ .bearer_auth(token.trim())+ .json(&json!({"id":connector}))+ .send()+ .await?;+ if !res.status().is_success() {+ anyhow::bail!("Connector credentials unavailable; check Credentials in Codync");+ }+ let v: Value = res.json().await?;+ let command = v["command"].as_str().ok_or_else(|| anyhow::anyhow!("Not a local connector"))?;+ let mut child = tokio::process::Command::new(command);+ child.args(v["args"].as_array().into_iter().flatten().filter_map(Value::as_str));+ for (k, v) in v["env"].as_object().into_iter().flatten() {+ if let Some(v) = v.as_str() {+ child.env(k, v);+ }+ }+ let status = child+ .stdin(Stdio::inherit())+ .stdout(Stdio::inherit())+ .stderr(Stdio::null())+ .kill_on_drop(true)+ .spawn()?+ .wait()+ .await?;+ if !status.success() {+ anyhow::bail!("Connector exited unsuccessfully");+ }+ Ok(())}#[cfg(test)]diff --git a/host/src/routines/editor.rs b/host/src/routines/editor.rsnew file mode 100644index 00000000..db89424d--- /dev/null+++ b/host/src/routines/editor.rs@@ -0,0 +1,279 @@+//! The host owns editor hydration, cron generation, validation and preview.+use super::Trigger;+use anyhow::{Context, Result, bail};+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use std::collections::BTreeSet;++#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(default, rename_all = "camelCase")]+pub struct ScheduleDraft {+ pub kind: String,+ pub amount: String,+ pub unit: i64,+ pub calendar_style: String,+ pub weekday: u8,+ pub selected_days: BTreeSet<u8>,+ pub month_day: u8,+ pub minute_step: u8,+ pub hour: u8,+ pub minute: u8,+ pub at: i64,+ pub expression: String,+ pub zone: String,+ pub original: Vec<Trigger>,+}++impl Default for ScheduleDraft {+ fn default() -> Self {+ Self {+ kind: "cron".into(),+ amount: "1".into(),+ unit: 3600,+ calendar_style: "daily".into(),+ weekday: 1,+ selected_days: [1, 2, 3, 4, 5].into(),+ month_day: 1,+ minute_step: 15,+ hour: 9,+ minute: 0,+ at: 0,+ expression: "0 9 * * *".into(),+ zone: "UTC".into(),+ original: Vec::new(),+ }+ }+}++impl ScheduleDraft {+ fn hydrate(triggers: &[Trigger], zone: String, now: i64) -> Self {+ let mut draft = Self { original: triggers.to_owned(), zone, at: now + 3_600_000, ..Self::default() };+ let [trigger] = triggers else {+ if !triggers.is_empty() {+ draft.kind = "keep".into();+ }+ return draft;+ };+ match trigger {+ Trigger::Interval { seconds } => {+ draft.kind = "interval".into();+ draft.unit = [86400, 3600, 60, 1].into_iter().find(|unit| seconds % unit == 0).unwrap_or(1);+ draft.amount = (seconds / draft.unit).to_string();+ }+ Trigger::Once { at } => {+ draft.kind = "once".into();+ draft.at = *at;+ }+ Trigger::Webhook => draft.kind = "webhook".into(),+ Trigger::Event { .. } => draft.kind = "keep".into(),+ Trigger::Cron { expression, time_zone } => {+ draft.zone.clone_from(time_zone);+ draft.expression.clone_from(expression);+ draft.calendar_style = "custom".into();+ draft.read_cron();+ }+ }+ draft+ }++ fn read_cron(&mut self) {+ let fields: Vec<_> = self.expression.split_whitespace().collect();+ let [minute, hour, day, month, weekday] = fields.as_slice() else { return };+ if [hour, day, month, weekday].iter().all(|field| **field == "*")+ && let Some(step) = minute.strip_prefix("*/").and_then(|value| value.parse::<u8>().ok())+ && [1, 5, 10, 15, 20, 30].contains(&step)+ {+ self.calendar_style = "minutes".into();+ self.minute_step = step;+ return;+ }+ let Ok(minute) = minute.parse::<u8>() else { return };+ if minute > 59 {+ return;+ }+ self.minute = minute;+ if [hour, day, month, weekday].iter().all(|field| **field == "*") {+ self.calendar_style = "hourly".into();+ return;+ }+ let Ok(hour) = hour.parse::<u8>() else { return };+ if hour > 23 || *month != "*" {+ return;+ }+ self.hour = hour;+ if *day == "*" {+ if *weekday == "*" {+ self.calendar_style = "daily".into();+ } else if *weekday == "1-5" {+ self.calendar_style = "weekdays".into();+ } else if let Ok(day) = weekday.parse::<u8>() {+ if day <= 6 {+ self.calendar_style = "weekly".into();+ self.weekday = day;+ }+ } else if let Ok(days) = weekday.split(',').map(str::parse::<u8>).collect::<Result<Vec<_>, _>>()+ && !days.is_empty()+ && days.iter().all(|day| *day <= 6)+ && days.windows(2).all(|pair| pair[0] < pair[1])+ {+ self.calendar_style = "days".into();+ self.selected_days = days.into_iter().collect();+ }+ } else if *weekday == "*"+ && let Ok(day) = day.parse::<u8>()+ && (1..=31).contains(&day)+ {+ self.calendar_style = "monthly".into();+ self.month_day = day;+ }+ }++ pub fn triggers(&self) -> Result<Vec<Trigger>> {+ Ok(match self.kind.as_str() {+ "keep" => self.original.clone(),+ "interval" => {+ let amount = self.amount.parse::<i64>().context("enter a whole number for the interval")?;+ if amount <= 0 || ![1, 60, 3600, 86400].contains(&self.unit) {+ bail!("invalid interval");+ }+ vec![Trigger::Interval { seconds: amount.checked_mul(self.unit).context("interval overflow")? }]+ }+ "once" => vec![Trigger::Once { at: self.at }],+ "webhook" => vec![Trigger::Webhook],+ "cron" => vec![Trigger::Cron { expression: self.cron()?, time_zone: self.zone.clone() }],+ _ => bail!("choose when this routine should run"),+ })+ }++ fn cron(&self) -> Result<String> {+ if self.hour > 23 || self.minute > 59 {+ bail!("choose a valid hour and minute");+ }+ let (minute, hour) = (self.minute, self.hour);+ Ok(match self.calendar_style.as_str() {+ "minutes" => {+ if ![1, 5, 10, 15, 20, 30].contains(&self.minute_step) {+ bail!("choose a minute interval that divides the hour evenly");+ }+ format!("*/{} * * * *", self.minute_step)+ }+ "hourly" => format!("{minute} * * * *"),+ "daily" => format!("{minute} {hour} * * *"),+ "weekdays" => format!("{minute} {hour} * * 1-5"),+ "weekly" => {+ if self.weekday > 6 {+ bail!("choose a weekday");+ }+ format!("{minute} {hour} * * {}", self.weekday)+ }+ "days" => {+ if self.selected_days.is_empty() || self.selected_days.iter().any(|day| *day > 6) {+ bail!("choose at least one valid weekday");+ }+ format!(+ "{minute} {hour} * * {}",+ self.selected_days.iter().map(u8::to_string).collect::<Vec<_>>().join(",")+ )+ }+ "monthly" => {+ if !(1..=31).contains(&self.month_day) {+ bail!("choose a day from 1 to 31");+ }+ format!("{minute} {hour} {} * *", self.month_day)+ }+ "custom" => self.expression.split_whitespace().collect::<Vec<_>>().join(" "),+ _ => bail!("choose a schedule frequency"),+ })+ }+}++pub fn preview(body: &Value, now: i64) -> Result<Value> {+ let draft = if let Some(value) = body.get("draft") {+ serde_json::from_value::<ScheduleDraft>(value.clone()).context("invalid schedule fields")?+ } else {+ let triggers = body.get("triggers").cloned().unwrap_or_else(|| json!([]));+ ScheduleDraft::hydrate(+ &serde_json::from_value::<Vec<Trigger>>(triggers)?,+ body["timeZone"].as_str().unwrap_or("UTC").into(),+ now,+ )+ };+ let triggers = draft.triggers()?;+ if triggers.is_empty() || triggers.len() > 20 {+ bail!("a routine requires 1 to 20 triggers");+ }+ for trigger in &triggers {+ // Existing expired one-shots may be edited without changing their date.+ if matches!(trigger, Trigger::Once { .. }) && draft.original.contains(trigger) {+ continue;+ }+ trigger.validate(now)?;+ }+ let next =+ triggers.iter().map(|trigger| trigger.next(now)).collect::<Result<Vec<_>>>()?.into_iter().flatten().min();+ let warning = (draft.kind == "cron" && draft.calendar_style == "monthly" && draft.month_day > 28)+ .then(|| format!("Months without day {} are skipped.", draft.month_day));+ Ok(+ json!({"draft":draft,"triggers":triggers,"summary":triggers.iter().map(Trigger::description).collect::<Vec<_>>().join(" · "),+ "nextRunAt":next,"warning":warning}),+ )+}++#[cfg(test)]+mod tests {+ use super::*;+ const NOW: i64 = 1_790_470_800_000;++ #[test]+ fn defaults_and_presets_are_compiled_and_validated_on_the_host() {+ let result = preview(&json!({"timeZone":"Asia/Taipei"}), NOW).unwrap();+ assert_eq!(result["triggers"][0]["type"], "cron");+ assert_eq!(result["triggers"][0]["expression"], "0 9 * * *");+ for (style, expression) in [+ ("minutes", "*/15 * * * *"),+ ("hourly", "47 * * * *"),+ ("days", "47 23 * * 1,3,5"),+ ("monthly", "47 23 31 * *"),+ ] {+ let result = preview(+ &json!({"draft":{"calendarStyle":style,"hour":23,"minute":47,+ "selectedDays":[5,1,3],"monthDay":31,"zone":"Asia/Taipei"}}),+ NOW,+ )+ .unwrap();+ assert_eq!(result["triggers"][0]["expression"], expression);+ assert!(result["nextRunAt"].as_i64().is_some_and(|next| next > NOW));+ }+ }++ #[test]+ fn editor_round_trips_existing_triggers_without_changing_cadence() {+ for expression in ["*/15 * * * *", "37 * * * *", "5 23 * * 1,3,6", "45 8 31 * *", "*/7 * * * *", "0 9 L * *"] {+ let triggers = json!([{"type":"cron","expression":expression,"timeZone":"Asia/Taipei"}]);+ let result = preview(&json!({"triggers":triggers}), NOW).unwrap();+ assert_eq!(result["triggers"], triggers);+ }+ for triggers in [+ json!([{"type":"interval","seconds":5400}]),+ json!([{"type":"once","at":1000}]),+ json!([{"type":"webhook"},{"type":"interval","seconds":90}]),+ ] {+ assert_eq!(preview(&json!({"triggers":triggers}), NOW).unwrap()["triggers"], triggers);+ }+ }++ #[test]+ fn preview_rejects_invalid_schedules_before_saving() {+ for draft in [+ json!({"calendarStyle":"days","selectedDays":[]}),+ json!({"calendarStyle":"minutes","minuteStep":7}),+ json!({"zone":"invalid/zone"}),+ json!({"hour":24}),+ json!({"calendarStyle":"custom","expression":"61 9 * * *"}),+ json!({"calendarStyle":"custom","expression":"0 0 9 * * *"}),+ json!({"kind":"once","at":1}),+ ] {+ assert!(preview(&json!({"draft":draft}), NOW).is_err());+ }+ }+}diff --git a/host/src/routines/mod.rs b/host/src/routines/mod.rsindex 70697388..40910d35 100644--- a/host/src/routines/mod.rs+++ b/host/src/routines/mod.rs@@ -1,4 +1,6 @@//! Durable bot routines, shared by API clients and the built-in MCP server.+mod editor;+pub use editor::preview as schedule_preview;mod runner;mod schedule;pub use runner::start;@@ -159,15 +161,24 @@ impl Routines {if name.is_empty() || name.len() > 200 || instruction.is_empty() || instruction.len() > 32_000 {bail!("routine name or instruction is empty or too long");}- let triggers: Vec<Trigger> = serde_json::from_value(body["triggers"].clone()).context("invalid triggers")?;+ let triggers: Vec<Trigger> = if let Some(draft) = body.get("schedule") {+ serde_json::from_value::<editor::ScheduleDraft>(draft.clone()).context("invalid schedule")?.triggers()?+ } else {+ serde_json::from_value(body["triggers"].clone()).context("invalid triggers")?+ };if triggers.is_empty() || triggers.len() > 20 {bail!("a routine requires 1 to 20 triggers");}- if let Some(value) = body.get("timeoutSeconds")- && value.as_u64().is_none_or(|n| !(1..=86_400).contains(&n))- {- bail!("timeoutSeconds must be an integer between 1 and 86400");- }+ let timeout = body+ .get("timeoutSeconds")+ .map(|value| {+ value+ .as_u64()+ .or_else(|| value.as_str()?.parse::<u64>().ok())+ .filter(|seconds| (1..=86_400).contains(seconds))+ .context("timeoutSeconds must be an integer between 1 and 86400")+ })+ .transpose()?;let now = now_ms();let id = body["id"].as_str().map_or_else(|| uuid::Uuid::new_v4().to_string(), str::to_owned);let updated = body["id"].is_string();@@ -208,8 +219,7 @@ impl Routines {|r| r.webhook_key.clone(),),deleted: false,- timeout_seconds: body["timeoutSeconds"]- .as_u64()+ timeout_seconds: timeout.unwrap_or_else(|| old.as_ref().map_or_else(default_timeout, |r| r.timeout_seconds)),last_error: None,};@@ -384,14 +394,14 @@ pub fn call(hub: &Arc<Hub>, bot: &str, name: &str, args: &Value) -> Result<Value}}-pub const INSTRUCTIONS: &str = "Create and manage persistent Codync routines when the user asks for scheduled or event-driven work. Use the built-in routines tools (save_routine, list_routines, set_routine_enabled, delete_routine, run_routine, routine_webhook), not operating-system cron or an improvised background process. Before saving, resolve the task, trigger and intended timezone for calendar/one-time schedules from the conversation; ask only for missing or ambiguous details. If the request is already clear, create it without another confirmation. Check that tools, connector sign-ins and files needed by the task are available; describe any missing setup rather than promising the task will work. Use list_routines before creating or editing to avoid duplicates; preserve unrelated triggers, enabled state and instructions. Save returns the actual routine ID, trigger descriptions and nextRunAt: use these to report what was really saved, including timezone, next occurrence and enabled/paused state. Do not claim success if the tool failed. run_routine executes the real task immediately, including its side effects; use it when the user requested a test or immediate execution, not merely to validate a schedule. A routine runs locally in its own conversation; the host must be running and awake, results appear in the main chat, and (pass) stays silent. Webhooks use a per-routine bearer key; the returned URL is local to the host and does not configure a public tunnel or provider subscription. Establish the event source, reachable ingress and authentication separately. Never claim a third-party integration is connected until a real delivery has been verified; report a saved webhook as awaiting connection when that setup is missing. Keep secrets out of routine instructions and ordinary status summaries.";+pub const INSTRUCTIONS: &str = "Create and manage persistent Codync routines when the user asks for scheduled or event-driven work. Use the built-in routines tools (save_routine, list_routines, set_routine_enabled, delete_routine, run_routine, routine_webhook), not operating-system cron or an improvised background process. For recurring clock schedules, always use a five-field cron trigger with an explicit IANA timezone, including minute/hour frequencies; do not create interval triggers for those requests. Preserve existing intervals when editing unrelated fields. Cron steps reset within their field: */7 minutes is not an exact seven-minute duration across hours. Use once for a single dated execution; never approximate a one-time task with an annually repeating cron expression. Before saving, resolve the task, trigger and intended timezone for calendar/one-time schedules from the conversation; ask only for missing or ambiguous details. If the request is already clear, create it without another confirmation. Check that tools, connector sign-ins and files needed by the task are available; describe any missing setup rather than promising the task will work. Use list_routines before creating or editing to avoid duplicates; preserve unrelated triggers, enabled state and instructions. Save returns the actual routine ID, trigger descriptions and nextRunAt: use these to report what was really saved, including timezone, next occurrence and enabled/paused state. Do not claim success if the tool failed. run_routine executes the real task immediately, including its side effects; use it when the user requested a test or immediate execution, not merely to validate a schedule. A routine runs locally in its own conversation; the host must be running and awake, results appear in the main chat, and (pass) stays silent. Webhooks use a per-routine bearer key; the returned URL is local to the host and does not configure a public tunnel or provider subscription. Establish the event source, reachable ingress and authentication separately. Never claim a third-party integration is connected until a real delivery has been verified; report a saved webhook as awaiting connection when that setup is missing. Keep secrets out of routine instructions and ordinary status summaries.";pub fn tools() -> Value {let id = json!({"type":"string"});let mut tools = vec![json!({"name":"list_routines","description":"List this bot's routines and run history.","inputSchema":{"type":"object","properties":{}}}),];- tools.push(json!({"name":"save_routine","description":"Create or replace a routine. Omit id to create; include id to update. triggers is an OR list: interval {type:interval,seconds}; once {type:once,at:Unix milliseconds}; cron {type:cron,expression:five cron fields,timeZone:IANA zone}; webhook {type:webhook}; event {type:event,source:slack/github/origin/microsoftTeams/linear/sentry/pagerduty/email,event:event name or *,filters:field-to-value map}. Events require a configured webhook sender. Minimum interval is one second.","inputSchema":{"type":"object","properties":{"id":id,"name":{"type":"string"},"instruction":{"type":"string"},"enabled":{"type":"boolean"},"timeoutSeconds":{"type":"integer","minimum":1,"maximum":86400},"triggers":{"type":"array","items":{"type":"object"}}},"required":["name","instruction","triggers"]}}));+ tools.push(json!({"name":"save_routine","description":"Create or replace a routine. Omit id to create; include id to update. triggers is an OR list. Use cron for recurring clock schedules; interval is for explicitly requested elapsed-duration semantics or existing schedules: interval {type:interval,seconds}; once {type:once,at:Unix milliseconds}; cron {type:cron,expression:five cron fields,timeZone:IANA zone}; webhook {type:webhook}; event {type:event,source:slack/github/origin/microsoftTeams/linear/sentry/pagerduty/email,event:event name or *,filters:field-to-value map}. Events require a configured webhook sender. Minimum interval is one second.","inputSchema":{"type":"object","properties":{"id":id,"name":{"type":"string"},"instruction":{"type":"string"},"enabled":{"type":"boolean"},"timeoutSeconds":{"type":"integer","minimum":1,"maximum":86400},"triggers":{"type":"array","items":{"type":"object"}}},"required":["name","instruction","triggers"]}}));for (name, description) in [("set_routine_enabled", "Pause or resume a routine; enabled boolean is required."),("delete_routine", "Delete a routine and cancel pending runs."),diff --git a/host/src/routines/schedule.rs b/host/src/routines/schedule.rsindex 67435c3f..68f45a4c 100644--- a/host/src/routines/schedule.rs+++ b/host/src/routines/schedule.rs@@ -135,6 +135,22 @@ mod tests {let expected = DateTime::parse_from_rfc3339("2026-09-27T06:20:00Z").unwrap().timestamp_millis();assert_eq!(t.next(now).unwrap(), Some(expected));}+ #[test]+ fn calendar_presets_follow_clock_boundaries() {+ let now = DateTime::parse_from_rfc3339("2026-09-27T01:07:00Z").unwrap().timestamp_millis();+ for (expression, expected) in [+ ("*/15 * * * *", "2026-09-27T01:15:00Z"),+ ("37 * * * *", "2026-09-27T01:37:00Z"),+ ("0 9 * * 1,3,5", "2026-09-28T01:00:00Z"),+ ("0 9 31 * *", "2026-10-31T01:00:00Z"),+ ] {+ let trigger = Trigger::Cron { expression: expression.into(), time_zone: "Asia/Taipei".into() };+ trigger.validate(now).unwrap();+ let expected = DateTime::parse_from_rfc3339(expected).unwrap().timestamp_millis();+ assert_eq!(trigger.next(now).unwrap(), Some(expected), "{expression}");+ }+ }+#[test]fn event_filters_require_all_fields() {let t = Trigger::Event {diff --git a/host/src/store.rs b/host/src/store.rsindex df88489e..4e20b5f4 100644--- a/host/src/store.rs+++ b/host/src/store.rs@@ -196,6 +196,8 @@ type RawBot = (String, String, i64, bool, Option<String>, i64);pub struct Store {db: Mutex<Connection>,+ pub(crate) connector_lock: Mutex<()>,+ pub(crate) secret_key: Mutex<Option<zeroize::Zeroizing<Vec<u8>>>>,}pub fn now_ms() -> i64 {@@ -365,6 +367,7 @@ impl Store {c.execute_batch("PRAGMA journal_mode=WAL;PRAGMA synchronous=NORMAL;+ PRAGMA secure_delete=ON;CREATE TABLE IF NOT EXISTS kv(k TEXT PRIMARY KEY, v TEXT NOT NULL);CREATE TABLE IF NOT EXISTS bots(id TEXT PRIMARY KEY, rev INTEGER NOT NULL, deleted INTEGER NOT NULL DEFAULT 0,@@ -377,7 +380,14 @@ impl Store {CREATE INDEX IF NOT EXISTS entries_bot ON entries(bot_id, seq);",)?;migrate(&c)?;- Ok(Self { db: Mutex::new(c) })+ let secret_key = if path == Path::new(":memory:") {+ let mut key = vec![0; 32];+ getrandom::fill(&mut key).map_err(|_| anyhow::anyhow!("random key unavailable"))?;+ Some(zeroize::Zeroizing::new(key))+ } else {+ None+ };+ Ok(Self { db: Mutex::new(c), connector_lock: Mutex::new(()), secret_key: Mutex::new(secret_key) })}/// Durable control state must distinguish a missing key from a failed read.@@ -548,7 +558,17 @@ impl Store {let data: String = r.get(1)?;let at: i64 = r.get(2)?;let data = serde_json::from_str::<Value>(&data).unwrap_or_default();- let text = data["text"].as_str().unwrap_or_default().to_owned();+ let mut text = data["text"].as_str().unwrap_or_default().to_owned();+ // A files-only message previews as its file names.+ if text.is_empty() {+ let names: Vec<&str> = data["attachments"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|a| a["name"].as_str())+ .collect();+ text = names.join(", ");+ }let author =(kind != EntryKind::User.as_str()).then(|| data["author"].as_str().unwrap_or(id).to_owned());Ok(LastMessage { text, at, author })diff --git a/host/src/tui/app.rs b/host/src/tui/app.rsindex fb776e99..d2c8521b 100644--- a/host/src/tui/app.rs+++ b/host/src/tui/app.rs@@ -74,6 +74,7 @@ pub struct Bot {pub shape: String,pub backend: String,pub cwd: String,+ pub managed_workspace: bool,pub auto: bool,pub model: Option<String>,pub pinned: bool,@@ -100,6 +101,11 @@ fn strs(v: &Value) -> Vec<String> {}impl Bot {+ /// Where it works, as the header shows it.+ pub fn folder(&self, home: &str) -> String {+ if self.managed_workspace { "personal workspace".to_owned() } else { tilde(&self.cwd, home) }+ }+fn parse(v: &Value) -> Option<Self> {let s = |k: &str| v[k].as_str().unwrap_or_default().to_owned();Some(Self {@@ -110,6 +116,7 @@ impl Bot {shape: v["avatarShape"].as_str().unwrap_or("blob").to_owned(),backend: s("backend"),cwd: s("cwd"),+ managed_workspace: v["managedWorkspace"] == true,auto: v["permission"] == "auto",model: v["model"].as_str().filter(|m| !m.is_empty()).map(str::to_owned),pinned: v["pinned"].as_bool().unwrap_or(false),@@ -210,6 +217,24 @@ impl Entry {self.data["text"].as_str().unwrap_or_default()}+ /// Files sent with a user message: `(name, size)`.+ pub fn attachments(&self) -> Vec<(&str, u64)> {+ self.data["attachments"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|a| Some((a["name"].as_str()?, a["size"].as_u64().unwrap_or(0))))+ .collect()+ }++ /// A notice's line; a voice call gets its length ("Voice chat · 00:16").+ pub fn notice_text(&self) -> String {+ match self.data["callSeconds"].as_u64() {+ Some(s) => format!("{} · {:02}:{:02}", self.text(), s / 60, s % 60),+ None => self.text().to_owned(),+ }+ }+pub fn is_final(&self) -> bool {self.kind == Kind::Agent && self.data["final"].as_bool().unwrap_or(false)}@@ -446,8 +471,6 @@ pub struct FolderPicker {pub query: Editor,pub cursor: usize,pub error: Option<String>,- /// `Some(backend)`: step 2 of a new bot. `None`: picking for the open form.- pub new_bot: Option<String>,}pub const COLORS: [&str; 11] =@@ -609,6 +632,8 @@ pub struct App {/// Narrow layout: showing the chat page (else the roster page).pub chat_page: bool,pub drafts: HashMap<String, Editor>,+ /// Files dropped on the composer (pasted paths), per draft like the text.+ pub files: HashMap<String, Vec<std::path::PathBuf>>,/// Lines scrolled up from the bottom of the chat (0 = follow new messages).pub chat_scroll: usize,pub trace_scroll: usize,@@ -656,6 +681,7 @@ impl App {typing: false,chat_page: false,drafts: HashMap::new(),+ files: HashMap::new(),chat_scroll: 0,trace_scroll: 0,trace: TraceMode::Off,@@ -739,6 +765,10 @@ impl App {self.draft_key().and_then(|k| self.drafts.get(&k).cloned()).unwrap_or_default()}+ pub fn draft_files(&self) -> &[std::path::PathBuf] {+ self.draft_key().and_then(|k| self.files.get(&k)).map_or(&[], Vec::as_slice)+ }+/// Name of an entry's author (a group reply's bot), as the apps show it.pub fn author_name(&self, id: Option<&str>) -> String {id.and_then(|id| self.bots.get(id)).map_or_else(|| "A deleted bot".into(), |b| b.name.clone())@@ -1115,7 +1145,11 @@ impl App {} else if let Some(key) = self.draft_key() {self.typing = true;self.focus = Focus::Chat;- self.drafts.entry(key).or_default().insert(&s);+ // A file dragged onto the terminal pastes its path: attach it (groups have no folder for files).+ match dropped_files(&s).filter(|_| self.bot().is_some_and(|b| !b.group)) {+ Some(paths) => self.files.entry(key).or_default().extend(paths),+ None => self.drafts.entry(key).or_default().insert(&s),+ }}}@@ -1169,14 +1203,15 @@ impl App {let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);let newline = k.modifiers.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT);let thread = self.thread.clone();- let draft = self.drafts.entry(key).or_default();+ let draft = self.drafts.entry(key.clone()).or_default();match k.code {KeyCode::Esc => self.typing = false,KeyCode::Enter if newline => draft.insert("\n"),KeyCode::Char('j') if ctrl => draft.insert("\n"),KeyCode::Enter => {let text = draft.text.trim().to_owned();- if text.is_empty() {+ let files = self.files.remove(&key).unwrap_or_default();+ if text.is_empty() && files.is_empty() {return;}draft.clear();@@ -1186,7 +1221,17 @@ impl App {if let Some(root) = thread {body["threadId"] = root.into();}- self.call("send", body, After::Nothing);+ if files.is_empty() {+ self.call("send", body, After::Nothing);+ } else {+ self.flash(&format!("uploading {} file{}…", files.len(), if files.len() == 1 { "" } else { "s" }));+ self.client.spawn_send_files(body, files, self.tx.clone());+ }+ }+ KeyCode::Backspace if draft.text.is_empty() => {+ if let Some(files) = self.files.get_mut(&key) {+ files.pop();+ }}KeyCode::Char('c') if ctrl => {if draft.text.is_empty() {@@ -1572,7 +1617,8 @@ impl App {};// OSC 52: the terminal puts it on the clipboard, over SSH too.let mut out = std::io::stdout();- let _ = write!(out, "\x1b]52;c;{}\x07", base64(text.as_bytes()));+ let _ =+ write!(out, "\x1b]52;c;{}\x07", base64::Engine::encode(&base64::engine::general_purpose::STANDARD, text));let _ = out.flush();self.flash("Copied the last reply");}@@ -1695,7 +1741,7 @@ impl App {instructions: Editor::with(&b.description),backend: b.backend.clone(),model: Editor::with(b.model.as_deref().unwrap_or_default()),- cwd: b.cwd.clone(),+ cwd: if b.managed_workspace { String::new() } else { b.cwd.clone() },auto: b.auto,notify: b.notify,color: COLORS.iter().position(|c| *c == b.color).unwrap_or(7),@@ -1862,9 +1908,8 @@ impl App {let backend =self.agent_choices(&a.query.text).get(a.cursor).and_then(|b| b["id"].as_str()).map(str::to_owned);if let Some(backend) = backend {- let start = self.bot().map(|b| parent_dir(&b.cwd)).unwrap_or_default();self.overlays.push(Overlay::Agents(a));- self.open_folder(Some(backend), &start);+ self.new_bot_form(backend);return None;}}@@ -1877,7 +1922,7 @@ impl App {Some(Overlay::Agents(a))}- fn open_folder(&mut self, new_bot: Option<String>, start: &str) {+ fn open_folder(&mut self, start: &str) {self.overlays.push(Overlay::Folder(FolderPicker {path: start.to_owned(),parent: None,@@ -1885,7 +1930,6 @@ impl App {query: Editor::default(),cursor: 0,error: None,- new_bot,}));let body = if start.is_empty() { json!({}) } else { json!({"path": start}) };self.call("listDirs", body, After::Dirs);@@ -1919,12 +1963,12 @@ impl App {} else {matches.get(p.cursor).map_or_else(|| p.path.clone(), |d| d.path.clone())};- self.folder_chosen(p.new_bot.take(), chosen);+ self.folder_chosen(chosen);return None;}KeyCode::Char('.') if p.query.text.is_empty() => {let chosen = p.path.clone();- self.folder_chosen(p.new_bot.take(), chosen);+ self.folder_chosen(chosen);return None;}_ => {@@ -1936,50 +1980,52 @@ impl App {Some(Overlay::Folder(p))}- fn folder_chosen(&mut self, new_bot: Option<String>, path: String) {- if let Some(backend) = new_bot {- // Step 3: name and looks, prefilled.- if let Some(i) = self.overlays.iter().rposition(|o| matches!(o, Overlay::Agents(_))) {- self.overlays.truncate(i);- }- let n = self.bots.len() + usize::try_from(crate::store::now_ms() % 97).unwrap_or(0);- let name = NAMES[n % NAMES.len()].to_owned();- let f = Form {- bot_id: None,- name: Editor::with(&name),- instructions: Editor::default(),- backend,- model: Editor::default(),- cwd: path,- auto: false,- notify: true,- color: (n * 7) % COLORS.len(),- shape: n % SHAPES.len(),- connectors: self- .market- .0- .iter()- .map(|t| Toggle { id: t.id.clone(), name: t.name.clone(), on: false })- .collect(),- skills: self- .market- .1- .iter()- .map(|t| Toggle { id: t.id.clone(), name: t.name.clone(), on: false })- .collect(),- field: 0,- sub: 0,- error: None,- saving: false,- };- self.overlays.push(Overlay::Form(Box::new(f)));- self.call("connectors", json!({}), After::Connectors);- self.call("skills", json!({}), After::Skills);- } else if let Some(Overlay::Form(f)) = self.overlays.last_mut() {+ fn folder_chosen(&mut self, path: String) {+ if let Some(Overlay::Form(f)) = self.overlays.last_mut() {f.cwd = path;}}+ /// Step 2 of a new bot: name and looks, prefilled, in a personal workspace.+ fn new_bot_form(&mut self, backend: String) {+ if let Some(i) = self.overlays.iter().rposition(|o| matches!(o, Overlay::Agents(_))) {+ self.overlays.truncate(i);+ }+ let n = self.bots.len() + usize::try_from(crate::store::now_ms() % 97).unwrap_or(0);+ let name = NAMES[n % NAMES.len()].to_owned();+ let f = Form {+ bot_id: None,+ name: Editor::with(&name),+ instructions: Editor::default(),+ backend,+ model: Editor::default(),+ cwd: String::new(),+ auto: false,+ notify: true,+ color: (n * 7) % COLORS.len(),+ shape: n % SHAPES.len(),+ connectors: self+ .market+ .0+ .iter()+ .map(|t| Toggle { id: t.id.clone(), name: t.name.clone(), on: false })+ .collect(),+ skills: self+ .market+ .1+ .iter()+ .map(|t| Toggle { id: t.id.clone(), name: t.name.clone(), on: false })+ .collect(),+ field: 0,+ sub: 0,+ error: None,+ saving: false,+ };+ self.overlays.push(Overlay::Form(Box::new(f)));+ self.call("connectors", json!({}), After::Connectors);+ self.call("skills", json!({}), After::Skills);+ }+fn form_key(&mut self, mut f: Box<Form>, k: KeyEvent) -> Option<Overlay> {let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);let field = f.current();@@ -2002,10 +2048,11 @@ impl App {f.instructions.insert("\n");}KeyCode::Char('j') if ctrl && field == Field::Instructions => f.instructions.insert("\n"),+ KeyCode::Backspace | KeyCode::Delete if field == Field::Folder => f.cwd.clear(),KeyCode::Enter if field == Field::Folder => {let start = f.cwd.clone();self.overlays.push(Overlay::Form(f));- self.open_folder(None, &start);+ self.open_folder(&start);return None;}KeyCode::Enter => self.save_form(&mut f),@@ -2217,6 +2264,19 @@ pub fn fuzzy(query: &str, fields: &[&str]) -> bool {})}+/// Paths a terminal pastes for dropped files (shell-escaped, quoted or `file://`), when every one is a file.+fn dropped_files(s: &str) -> Option<Vec<std::path::PathBuf>> {+ let paths: Vec<std::path::PathBuf> = shlex::split(s.trim())?+ .into_iter()+ .map(|p| match p.strip_prefix("file://") {+ Some(url) => url.replace("%20", " "),+ None => p,+ })+ .map(std::path::PathBuf::from)+ .collect();+ (!paths.is_empty() && paths.iter().all(|p| p.is_absolute() && p.is_file())).then_some(paths)+}+pub fn tilde(path: &str, home: &str) -> String {match path.strip_prefix(home) {Some(rest) if !home.is_empty() => format!("~{rest}"),@@ -2224,38 +2284,23 @@ pub fn tilde(path: &str, home: &str) -> String {}}-fn parent_dir(path: &str) -> String {- std::path::Path::new(path).parent().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default()-}--fn base64(data: &[u8]) -> String {- const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";- let mut out = String::with_capacity(data.len().div_ceil(3) * 4);- for chunk in data.chunks(3) {- let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];- let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);- for i in 0..4 {- if i <= chunk.len() {- out.push(char::from(T[((n >> (18 - 6 * i)) & 63) as usize]));- } else {- out.push('=');- }- }- }- out-}-#[cfg(test)]mod tests {use super::*;#[test]- fn base64_matches_rfc4648() {- assert_eq!(base64(b""), "");- assert_eq!(base64(b"f"), "Zg==");- assert_eq!(base64(b"fo"), "Zm8=");- assert_eq!(base64(b"foo"), "Zm9v");- assert_eq!(base64(b"foobar"), "Zm9vYmFy");+ fn dropped_paths_are_files_only() {+ let dir = std::env::temp_dir().join(format!("codync-drop-{}", std::process::id()));+ std::fs::create_dir_all(&dir).expect("temp dir");+ let a = dir.join("a b.txt");+ std::fs::write(&a, "x").expect("write");+ let esc = a.to_string_lossy().replace(' ', "\\ ");+ assert_eq!(dropped_files(&esc), Some(vec![a.clone()]));+ assert_eq!(dropped_files(&format!("'{}'", a.display())), Some(vec![a.clone()]));+ assert_eq!(dropped_files(&format!("file://{}", a.to_string_lossy().replace(' ', "%20"))), Some(vec![a]));+ assert_eq!(dropped_files(&dir.to_string_lossy()), None);+ assert_eq!(dropped_files("hello world"), None);+ std::fs::remove_dir_all(&dir).expect("cleanup");}#[test]diff --git a/host/src/tui/net.rs b/host/src/tui/net.rsindex aaef633c..9c1f65e5 100644--- a/host/src/tui/net.rs+++ b/host/src/tui/net.rs@@ -1,7 +1,8 @@//! Host API over HTTP: JSON commands and the SSE event stream (same wire as the apps).use futures::StreamExt;-use serde_json::Value;+use serde_json::{Value, json};+use std::path::PathBuf;use std::sync::Arc;use std::sync::atomic::{AtomicI64, Ordering};use std::time::Duration;@@ -59,6 +60,48 @@ impl Client {});}+ /// Uploads `files` in 384 KiB chunks (under the channel's message limit, like the apps), then sends+ /// `body` with them attached. The reply comes back as `Msg::Reply(After::Nothing, …)`.+ pub fn spawn_send_files(&self, mut body: Value, files: Vec<PathBuf>, tx: UnboundedSender<Msg>) {+ use base64::Engine as _;+ const CHUNK: usize = 384 * 1024;+ const MAX: u64 = 100 * 1024 * 1024;+ let c = self.clone();+ tokio::spawn(async move {+ let upload = async {+ let mut ids = Vec::new();+ for path in &files {+ let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ let data = tokio::fs::read(path).await.map_err(|e| format!("Can't read {name}: {e}"))?;+ if data.len() as u64 > MAX {+ return Err(format!("{name} is over 100 MB."));+ }+ let id = uuid::Uuid::new_v4().to_string();+ let mut offset = 0;+ loop {+ let end = (offset + CHUNK).min(data.len());+ let chunk = base64::engine::general_purpose::STANDARD.encode(&data[offset..end]);+ let done = end == data.len();+ c.call(+ "upload",+ &json!({"botId": body["botId"], "uploadId": id, "name": name,+ "offset": offset, "data": chunk, "done": done}),+ )+ .await?;+ if done {+ break;+ }+ offset = end;+ }+ ids.push(id);+ }+ body["attachments"] = ids.into();+ c.call("send", &body).await+ };+ let _ = tx.send(Msg::Reply(After::Nothing, upload.await));+ });+ }+/// Streams host events forever, reconnecting with `since = last rev`.pub fn spawn_stream(&self, tx: UnboundedSender<Msg>) {let c = self.clone();diff --git a/host/src/tui/view.rs b/host/src/tui/view.rsindex 727cf82a..0bf8ddc3 100644--- a/host/src/tui/view.rs+++ b/host/src/tui/view.rs@@ -717,7 +717,7 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {put(buf, x, r.y, room, &truncate(&format!("group · {}", names.join(", ")), usize::from(room)), t.secondary);} else if !narrow {let mode = if b.auto { "auto" } else { "ask" };- let cwd = truncate(&tilde(&b.cwd, &app.home), usize::from(room).saturating_sub(w(&b.backend) + w(mode) + 6));+ let cwd = truncate(&b.folder(&app.home), usize::from(room).saturating_sub(w(&b.backend) + w(mode) + 6));put(buf, x, r.y, room, &format!("{} · {cwd} · {mode}", b.backend), t.secondary);}let mut top = r.y + 1;@@ -745,13 +745,26 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {let inner = usize::from(r.width.saturating_sub(4)).max(1);let (clines, cursor) = composer_lines(&draft, inner);let ch = u(clines.len().clamp(1, 8));- let comp_top = r.bottom().saturating_sub(ch + 2);+ // Attached files: one row of names above the text.+ let files = app.draft_files();+ let fh = u16::from(!files.is_empty());+ let box_top = r.bottom().saturating_sub(ch + fh + 2);let typing = app.typing && app.overlays.is_empty();let rule = if typing { t.text } else { t.line };- hline(buf, r.x, comp_top, r.width, rule);- hline(buf, r.x, comp_top + ch + 1, r.width, rule);+ hline(buf, r.x, box_top, r.width, rule);+ hline(buf, r.x, box_top + fh + ch + 1, r.width, rule);+ if fh > 0 {+ let names: Vec<String> = files+ .iter()+ .map(|p| format!("▤ {}", p.file_name().map(|n| n.to_string_lossy()).unwrap_or_default()))+ .collect();+ let hint = if draft.text.is_empty() { "⌫ removes" } else { "" };+ put(buf, r.x + 3, box_top + 1, r.width.saturating_sub(u(w(hint)) + 6), &names.join(" "), t.secondary);+ rput(buf, r.right() - 1, box_top + 1, hint, t.dim);+ }+ let comp_top = box_top + fh;put(buf, r.x + 1, comp_top + 1, 1, "›", if typing { t.bold } else { t.dim });- let comp_rect = Rect::new(r.x, comp_top, r.width, ch + 2);+ let comp_rect = Rect::new(r.x, box_top, r.width, ch + fh + 2);app.hits.clicks.push((comp_rect, Click::Composer));let first = clines.len().saturating_sub(usize::from(ch)).min(cursor.1.saturating_sub(usize::from(ch) - 1));// Where the first composer line's text ends, so the chip on its right never covers it.@@ -801,7 +814,7 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {}// Transcript.- let body = Rect::new(r.x, top + 1, r.width, comp_top.saturating_sub(top + 1));+ let body = Rect::new(r.x, top + 1, r.width, box_top.saturating_sub(top + 1));app.chat_height = usize::from(body.height);let built = build_chat(app, &b, usize::from(body.width.saturating_sub(1)));let total = built.lines.len();@@ -836,7 +849,7 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {}if app.chat_scroll > 0 {let s = format!(" ↓ {} more ", app.chat_scroll);- rput(buf, r.right() - 1, comp_top.saturating_sub(1), &s, t.btn);+ rput(buf, r.right() - 1, box_top.saturating_sub(1), &s, t.btn);}}@@ -1020,7 +1033,7 @@ fn intro(out: &mut Built, app: &App, b: &Bot, width: usize) {)} else {(- format!("{} · {}", b.backend, tilde(&b.cwd, &app.home)),+ format!("{} · {}", b.backend, b.folder(&app.home)),format!("Say what you need. {} works in the background and pings you when it's done or needs you.", b.name),)};@@ -1064,12 +1077,23 @@ fn entry_lines(_ => {}}out.lines.push(Line::from(head));- let body = md::wrap(- &[Span::styled(e.text().to_owned(), t.text)],- width.saturating_sub(1),- &[Span::raw(" › ")],- &[Span::raw(" ")],- );+ let mut body = if e.text().is_empty() {+ vec![]+ } else {+ md::wrap(+ &[Span::styled(e.text().to_owned(), t.text)],+ width.saturating_sub(1),+ &[Span::raw(" › ")],+ &[Span::raw(" ")],+ )+ };+ for (name, size) in e.attachments() {+ body.push(Line::from(vec![+ Span::styled(" ▤ ", t.dim),+ Span::styled(truncate(name, width.saturating_sub(14)), t.text),+ Span::styled(format!(" {}", file_size(size)), t.dim),+ ]));+ }out.lines.extend(with_bg(body, width, t.band));out.messages.push((e.id.clone(), from, out.lines.len()));if main {@@ -1114,7 +1138,7 @@ fn entry_lines(}}Kind::Notice => {- let text = e.text().to_owned();+ let text = e.notice_text();gap(out);match e.data["style"].as_str() {Some("divider") => {@@ -1140,6 +1164,20 @@ fn entry_lines(}}+/// A user message on one line: its text, then its files.+fn user_line(e: &Entry) -> String {+ let files = e.attachments().iter().map(|(n, _)| format!("▤ {n}")).collect::<Vec<_>>().join(" ");+ [e.text(), files.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::<Vec<_>>().join(" ")+}++fn file_size(bytes: u64) -> String {+ match bytes {+ 0..1024 => format!("{bytes} B"),+ 1024..1_048_576 => format!("{} KB", bytes / 1024),+ _ => format!("{}.{} MB", bytes / 1_048_576, bytes % 1_048_576 * 10 / 1_048_576),+ }+}+/// Under a message with a thread: how many replies, how recently (click opens it).fn thread_line(out: &mut Built, app: &App, e: &Entry) {let Some(text) = thread_summary(&e.data["thread"]) else { return };@@ -1412,7 +1450,7 @@ fn build_trace(app: &App, b: &Bot, turn: i64, width: usize, full: bool) -> Vec<LKind::User => out.push(Line::from(vec![Span::styled(" › ", t.dim),label("you"),- Span::styled(truncate(e.text(), text_rest(width)), t.text),+ Span::styled(truncate(&user_line(e), text_rest(width)), t.text),])),Kind::Thought | Kind::Agent => {let (g, lab) = if e.kind == Kind::Thought {@@ -1535,7 +1573,7 @@ fn build_trace(app: &App, b: &Bot, turn: i64, width: usize, full: bool) -> Vec<L}Kind::Notice => out.push(Line::from(vec![Span::styled(" · ", t.dim),- Span::styled(truncate(e.text(), width.saturating_sub(4)), t.dim),+ Span::styled(truncate(&e.notice_text(), width.saturating_sub(4)), t.dim),])),Kind::Other => {}}@@ -1589,7 +1627,7 @@ fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay) {let group_row = App::agent_group_row(&a.query.text);let h = u(choices.len() + usize::from(group_row) + 8).min(area.height.saturating_sub(2)).max(10);let r = centered(area, 74, h);- let inner = frame_box(buf, r, t.text, t.panel, Some(("New bot · 1/3 agent", t.text)));+ let inner = frame_box(buf, r, t.text, t.panel, Some(("New bot · 1/2 agent", t.text)));field_line(buf, inner, inner.y, &a.query, "type to filter", true);let list_h = usize::from(inner.height.saturating_sub(4));let off = a.cursor.saturating_sub(list_h.saturating_sub(1));@@ -1656,8 +1694,7 @@ fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay) {let t = theme();let matches = App::folder_matches(p);let r = centered(area, 74, 22);- let title = if p.new_bot.is_some() { "New bot · 2/3 folder" } else { "Folder" };- let inner = frame_box(buf, r, t.text, t.panel, Some((title, t.text)));+ let inner = frame_box(buf, r, t.text, t.panel, Some(("Folder", t.text)));let shown = tilde(&p.path, &app.home);let path = format!("{}/", shown.trim_end_matches('/'));let x = put(@@ -1800,7 +1837,7 @@ fn goto(buf: &mut Buffer, area: Rect, app: &mut App, g: &super::app::Goto, itemsput(buf, inner.x + 5, y, 10, &b.name, t.bold.patch(base));put(buf, inner.x + 16, y, 10, if b.group { "group" } else { &b.backend }, t.secondary.patch(base));let cwd =- if b.group { format!("{} bots", b.members.len()) } else { truncate(&tilde(&b.cwd, &app.home), 18) };+ if b.group { format!("{} bots", b.members.len()) } else { truncate(&b.folder(&app.home), 18) };put(buf, inner.x + 27, y, 19, &cwd, t.secondary.patch(base));let (pv, ps) = preview(b);let room = inner.width.saturating_sub(47);@@ -1840,7 +1877,7 @@ fn goto(buf: &mut Buffer, area: Rect, app: &mut App, g: &super::app::Goto, itemslet names: Vec<String> = b.members.iter().map(|m| app.author_name(Some(m))).collect();format!("{} · group · {}", b.name, names.join(", "))} else {- format!("{} · {} · {}", b.name, b.backend, tilde(&b.cwd, &app.home))+ format!("{} · {} · {}", b.name, b.backend, b.folder(&app.home))};put(buf, inner.x, inner.bottom() - 2, inner.width, &meta, t.secondary.patch(t.panel));}@@ -1953,7 +1990,7 @@ fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {let r = centered(area, 88, 30);let title = match &f.bot_id {Some(_) => format!("Edit {}", f.name.text),- None => "New bot · 3/3 name and looks".into(),+ None => "New bot · 2/2 name and looks".into(),};let inner = frame_box(buf, r, t.text, t.panel, Some((&title, t.text)));let wide = inner.width >= 70;@@ -1984,7 +2021,7 @@ fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {Field::Instructions => "Instructions",Field::Agent => "Agent",Field::Model => "Model",- Field::Folder => "Folder",+ Field::Folder => "Workspace",Field::Approvals => "Approvals",Field::Notify => "Notify",Field::Color => "Color",@@ -2029,7 +2066,13 @@ fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {vx,y,vw,- &format!("{} ▸", truncate(&tilde(&f.cwd, &app.home), usize::from(vw.saturating_sub(4)))),+ &format!(+ "{} ▸",+ truncate(+ &if f.cwd.is_empty() { "Personal workspace".to_owned() } else { tilde(&f.cwd, &app.home) },+ usize::from(vw.saturating_sub(4))+ )+ ),t.text.patch(base),);}@@ -2089,7 +2132,7 @@ fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {let x = put(buf, inner.x, by, 14, save, t.btn_primary) + 1;put(buf, x, by, 12, " esc Cancel ", t.text.patch(t.btn).add_modifier(Modifier::BOLD));let hint = match f.current() {- Field::Folder => "↵ browse · tab next field",+ Field::Folder => "↵ project folder · backspace personal · tab next field",Field::Connectors | Field::Skills => "←→ move · space toggle · tab next",Field::Agent | Field::Color | Field::Shape | Field::Approvals | Field::Notify => "←→ change · tab next field",Field::Instructions => "⇧↵ new line · tab next field",@@ -2144,8 +2187,11 @@ fn group_view(buf: &mut Buffer, area: Rect, app: &App, g: &GroupForm) {put(buf, inner.x, y, 2, if on { "☑" } else { "☐" }, if on { t.bold } else { t.dim }.patch(base));put_line(buf, inner.x + 2, y, 2, &avatar(app, b));put(buf, inner.x + 5, y, inner.width / 2, &b.name, if sel { t.bold } else { t.text }.patch(base));- let folder =- std::path::Path::new(&b.cwd).file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();+ let folder = if b.managed_workspace {+ "personal".to_owned()+ } else {+ std::path::Path::new(&b.cwd).file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default()+ };rput(buf, inner.right(), y, &truncate(&folder, usize::from(inner.width / 3)), t.dim.patch(base));}let by = inner.bottom() - 1;diff --git a/host/tests/e2e.rs b/host/tests/e2e.rsindex e2e9893a..b008f784 100644--- a/host/tests/e2e.rs+++ b/host/tests/e2e.rs@@ -289,3 +289,46 @@ async fn phone_pairs_and_chats_over_the_direct_channel() {assert_eq!(devices["devices"][0]["name"], "Test iPhone");assert_eq!(devices["devices"][0]["connected"], true);}++#[tokio::test]+async fn personal_workspaces_are_unique_persistent_and_optional() {+ let host = start_host().await;+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/workspace_agent.py");+ let first = host+ .call(+ "createBot",+ json!({"name": "One", "backend": "custom", "command": format!("python3 '{}'", agent.display())}),+ )+ .await;+ let second = host.call("createBot", json!({"name": "Two", "backend": "claude", "cwd": ""})).await;+ let first = &first["bot"];+ let second = &second["bot"];+ let dir = PathBuf::from(first["cwd"].as_str().unwrap());+ assert_eq!(dir, host.home.join("bots").join(first["id"].as_str().unwrap()).join("workspace"));+ assert!(dir.is_dir());+ assert_ne!(first["cwd"], second["cwd"]);+ assert_eq!(first["managedWorkspace"], true);+ host.call("send", json!({"botId": first["id"], "text": "verify"})).await;+ host.wait_for(first["id"].as_str().unwrap(), |e| e["kind"] == "agent" && e["data"]["final"] == true).await;+ let execution: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("execution.json")).unwrap()).unwrap();+ assert_eq!(+ std::fs::canonicalize(execution["process"].as_str().unwrap()).unwrap(),+ std::fs::canonicalize(&dir).unwrap()+ );+ assert_eq!(execution["session"], first["cwd"]);+ std::fs::write(dir.join("keep.txt"), "persistent output").unwrap();+ let renamed = host.call("updateBot", json!({"id": first["id"], "name": "Renamed", "cwd": ""})).await;+ assert_eq!(renamed["bot"]["cwd"], first["cwd"]);+ let project = host.home.join("project");+ std::fs::create_dir(&project).unwrap();+ let explicit = host.call("updateBot", json!({"id": first["id"], "cwd": project})).await;+ assert_eq!(explicit["bot"]["managedWorkspace"], false);+ let restored = host.call("updateBot", json!({"id": first["id"], "cwd": ""})).await;+ assert_eq!(restored["bot"]["cwd"], first["cwd"]);+ assert_eq!(std::fs::read_to_string(dir.join("keep.txt")).unwrap(), "persistent output");+ host.call("deleteBot", json!({"botId": first["id"]})).await;+ assert!(dir.join("keep.txt").is_file(), "deleting a bot must retain its files");+ let group = host.call("createBot", json!({"name": "Group", "kind": "group", "members": [second["id"]]})).await;+ assert_eq!(group["bot"]["cwd"], "");+ assert_eq!(group["bot"]["managedWorkspace"], false);+}diff --git a/host/tests/fixtures/credential_mcp.py b/host/tests/fixtures/credential_mcp.pynew file mode 100644index 00000000..60f1e929--- /dev/null+++ b/host/tests/fixtures/credential_mcp.py@@ -0,0 +1,13 @@+"""MCP fixture verifies secrets reach only the connector process."""+import json+import os+import sys+for line in sys.stdin:+ msg = json.loads(line)+ if 'id' not in msg:+ continue+ if os.environ.get('API_KEY') != 'test-private-key':+ print(json.dumps({'jsonrpc':'2.0','id':msg['id'],'error':{'message':'invalid key'}}),flush=True)+ continue+ result = {'protocolVersion':'2025-06-18','capabilities':{'tools':{}},'serverInfo':{'name':'fixture','version':'1'}} if msg['method']=='initialize' else {'tools':[]}+ print(json.dumps({'jsonrpc':'2.0','id':msg['id'],'result':result}),flush=True)diff --git a/host/tests/fixtures/workspace_agent.py b/host/tests/fixtures/workspace_agent.pynew file mode 100644index 00000000..eb5e7010--- /dev/null+++ b/host/tests/fixtures/workspace_agent.py@@ -0,0 +1,32 @@+"""ACP fixture recording the actual process and session working directories."""+import json+import os+import sys+from pathlib import Path+++def send(value):+ print(json.dumps(value), flush=True)+++for line in sys.stdin:+ message = json.loads(line)+ method = message.get("method")+ if method == "initialize":+ result = {"protocolVersion": 1, "agentCapabilities": {"loadSession": False}}+ elif method == "session/new":+ Path("execution.json").write_text(json.dumps({+ "process": os.getcwd(), "session": message["params"]["cwd"]+ }))+ result = {"sessionId": "workspace-test"}+ elif method == "session/prompt":+ send({"jsonrpc": "2.0", "method": "session/update", "params": {+ "sessionId": "workspace-test", "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {"type": "text", "text": "Workspace verified"}+ }+ }})+ result = {"stopReason": "end_turn"}+ else:+ continue+ send({"jsonrpc": "2.0", "id": message["id"], "result": result})diff --git a/host/tests/routines_e2e.rs b/host/tests/routines_e2e.rsindex ccf9ab4e..fe751bc8 100644--- a/host/tests/routines_e2e.rs+++ b/host/tests/routines_e2e.rs@@ -434,3 +434,49 @@ async fn agent_discovers_and_calls_routine_tools_over_real_mcp_stdio() {host.wait_status(&bot, routine["id"].as_str().unwrap(), "succeeded").await;host.wait_event("mcp-setup", "finished", "MCP_TASK_RESULT").await;}++#[tokio::test]+async fn schedule_editor_preview_and_save_share_host_rules() {+ let host = Host::start().await;+ let bot = host.stable_bot("schedule-editor").await;+ let preview = host+ .call(+ "routineSchedule",+ json!({"draft": {+ "calendarStyle":"days", "hour":23, "minute":47,+ "selectedDays":[5,1,3], "zone":"Asia/Taipei"+ }}),+ )+ .await;+ assert_eq!(preview["triggers"][0]["expression"], "47 23 * * 1,3,5");+ let saved = host+ .call(+ "saveRoutine",+ json!({+ "botId":bot,"name":"Calendar editor","instruction":"Do not execute this paused test.",+ "enabled":false,"schedule":preview["draft"],"timeoutSeconds":"60"+ }),+ )+ .await;+ assert_eq!(saved["routine"]["triggers"], preview["triggers"]);+ assert_eq!(saved["routine"]["timeoutSeconds"], 60);+ let loaded = host.call("routineSchedule", json!({"triggers":saved["routine"]["triggers"]})).await;+ assert_eq!(loaded["draft"]["calendarStyle"], "days");+ assert_eq!(loaded["draft"]["zone"], "Asia/Taipei");+ // Saving directly must validate even when a caller bypasses the preview UI.+ for schedule in [+ json!({"calendarStyle":"days","selectedDays":[]}),+ json!({"calendarStyle":"custom","expression":"61 9 * * *"}),+ json!({"zone":"invalid/zone"}),+ ] {+ let response = reqwest::Client::new()+ .post(format!("{}/api/saveRoutine", host.base))+ .bearer_auth(&host.token)+ .json(&json!({"botId":bot,"name":"Invalid","instruction":"Never run", "schedule":schedule}))+ .send()+ .await+ .unwrap();+ assert!(!response.status().is_success());+ }+ assert!(host.call("routines", json!({"botId":bot})).await["runs"].as_array().unwrap().is_empty());+}diff --git a/kit/Sources/CodyncKit/Client/ChannelTransport.swift b/kit/Sources/CodyncKit/Client/ChannelTransport.swiftindex 10b7c6f6..b3f44592 100644--- a/kit/Sources/CodyncKit/Client/ChannelTransport.swift+++ b/kit/Sources/CodyncKit/Client/ChannelTransport.swift@@ -32,7 +32,7 @@ public actor ChannelTransport: RemoteTransport {private var restartRequested = falseprivate var supervisor: Task<Void, Never>?private var monitor: NWPathMonitor?- private var sawFirstPath = false+ private var lastInterfaces: [String]?/// Relay upgrades refused with 403 since the last handshake. Right after a pairing or an/// approval the device can reach the relay before the host's new ACL does, so a few are retried.private var refusals = 0@@ -95,7 +95,8 @@ public actor ChannelTransport: RemoteTransport {let monitor = NWPathMonitor()monitor.pathUpdateHandler = { [weak self] path inguard path.status == .satisfied else { return }- Task { await self?.networkChanged() }+ let interfaces = path.availableInterfaces.map(\.name)+ Task { await self?.networkChanged(interfaces) }}monitor.start(queue: .global(qos: .utility))self.monitor = monitor@@ -127,9 +128,11 @@ public actor ChannelTransport: RemoteTransport {wake()}- private func networkChanged() {- // The monitor reports the current path right away; only later ones are changes.- guard sawFirstPath else { sawFirstPath = true; return }+ private func networkChanged(_ interfaces: [String]) {+ // The monitor reports the current path right away, then every small path change+ // (DNS, expensive/constrained flags); only a different set of interfaces is a new network.+ defer { lastInterfaces = interfaces }+ guard let lastInterfaces, lastInterfaces != interfaces else { return }reconnect()}diff --git a/kit/Sources/CodyncKit/Client/HostClient.swift b/kit/Sources/CodyncKit/Client/HostClient.swiftindex 4e58672e..564aca5c 100644--- a/kit/Sources/CodyncKit/Client/HostClient.swift+++ b/kit/Sources/CodyncKit/Client/HostClient.swift@@ -203,13 +203,47 @@ public extension HostClient {}/// `threadId`: reply in the thread on that main-chat message.- func send(botId: String, text: String, clientNonce: String, threadId: String? = nil) async throws -> Entry {- struct Body: Encodable { var botId: String; var text: String; var clientNonce: String; var threadId: String? }+ func send(botId: String, text: String, clientNonce: String, threadId: String? = nil, attachments: [String]? = nil) async throws -> Entry {+ struct Body: Encodable { var botId: String; var text: String; var clientNonce: String; var threadId: String?; var attachments: [String]? }struct Res: Decodable { var entry: Entry }- let res: Res = try await call("send", Body(botId: botId, text: text, clientNonce: clientNonce, threadId: threadId))+ let res: Res = try await call("send", Body(botId: botId, text: text, clientNonce: clientNonce, threadId: threadId, attachments: attachments))return res.entry}+ /// Bytes per `upload` call: base64 of it stays well under the channel's 1 MiB message.+ static let uploadChunk = 384 * 1024++ /// Sends one file in chunks for a later `send`; `id` names the upload there.+ func upload(botId: String, id: String, name: String, data: Data) async throws {+ struct Body: Encodable { var botId, uploadId, name, data: String; var offset: Int; var done: Bool }+ var offset = 0+ repeat {+ let end = min(offset + Self.uploadChunk, data.count)+ let chunk = data.subdata(in: offset..<end).base64EncodedString()+ let _: Empty = try await call("upload", Body(botId: botId, uploadId: id, name: name, data: chunk, offset: offset, done: end == data.count), timeout: 60)+ offset = end+ } while offset < data.count+ }++ /// A sent file, fetched back in chunks.+ func readUpload(botId: String, id: String) async throws -> Data {+ struct Body: Encodable { var botId, uploadId: String; var offset: Int }+ struct Res: Decodable { var data: String; var size: Int }+ var out = Data()+ repeat {+ let res: Res = try await call("readUpload", Body(botId: botId, uploadId: id, offset: out.count), timeout: 60)+ guard let chunk = Data(base64Encoded: res.data), !chunk.isEmpty else { break }+ out.append(chunk)+ if out.count >= res.size { break }+ } while true+ return out+ }++ func logCall(_ botId: String, seconds: Int) async throws {+ struct Body: Encodable { var botId: String; var seconds: Int }+ let _: Empty = try await call("logCall", Body(botId: botId, seconds: seconds))+ }+func stop(_ botId: String) async throws {let _: Empty = try await call("stop", ["botId": botId])}diff --git a/kit/Sources/CodyncKit/Models/Market.swift b/kit/Sources/CodyncKit/Models/Market.swiftindex 481919e2..26407bbf 100644--- a/kit/Sources/CodyncKit/Models/Market.swift+++ b/kit/Sources/CodyncKit/Models/Market.swift@@ -51,6 +51,9 @@ public struct ComposioApp: Decodable, Hashable, Sendable, Identifiable {public var connection: Connection?public var id: String { slug }public var connected: Bool { connection?.status == "active" }+ public init(slug: String, name: String) {+ self.slug = slug; self.name = name+ }}/// What connecting an app needs: a sign-in page, or fields for a key-based app.@@ -131,10 +134,12 @@ public extension HostClient {return res.items}- /// Featured connectors, or MCP Registry search results (search can take ~30 s).- func marketConnectors(search: String) async throws -> [MarketConnector] {- let res: Items<MarketConnector> = try await call("marketConnectors", ["search": search], timeout: 60)- return res.items+ /// A page of the MCP Registry (featured first), or of a search (can take ~30 s).+ /// Pass the returned cursor to get the next page; nil means there is none.+ func marketConnectors(search: String, cursor: String? = nil) async throws -> (items: [MarketConnector], next: String?) {+ struct Page: Decodable { var items: [MarketConnector]; var nextCursor: String? }+ let res: Page = try await call("marketConnectors", ["search": search, "cursor": cursor ?? ""], timeout: 60)+ return (res.items, res.nextCursor)}@discardableResult@@ -152,6 +157,12 @@ public extension HostClient {return res.connector}+ /// Adds every server in a pasted MCP config (`mcpServers` / `servers` JSON, or one server's entry).+ func importConnectors(config: String) async throws -> [InstalledConnector] {+ let res: Items<InstalledConnector> = try await call("importConnectors", ["config": config], timeout: 60)+ return res.items+ }+func connectorSignIn(_ id: String) async throws -> ConnectorSignIn {try await call("connectorSignIn", ["id": id], timeout: 60)}@@ -214,3 +225,50 @@ public extension HostClient {let _: Empty = try await call("removeSkill", ["id": id])}}++public struct ConnectionRequest: Codable, Hashable, Sendable {+ public var toolkit: String?+ public var kind: String+ public var status: String+ public var title: String+ public var botId: String+ public var registryName: String?+ public var connectorId: String?+ public var field: String?+ public var location: String?+}++public struct CredentialStatus: Decodable, Sendable {+ public var provider: String+ public var onePasswordConnected: Bool+}++public extension HostClient {+ func connectorInfo(_ name: String) async throws -> MarketConnector {+ try await call("connectorInfo", ["registryName": name], timeout: 60)+ }++ func verifyConnector(_ id: String) async throws {+ struct Verified: Decodable { var status: String }+ let _: Verified = try await call("connectorVerify", ["id": id], timeout: 120)+ }++ func finishConnectionRequest(_ entryId: String, connectorId: String? = nil, value: String? = nil, cancel: Bool = false) async throws {+ struct Body: Encodable { var entryId: String; var connectorId: String?; var value: String?; var cancel: Bool }+ struct Response: Decodable { var entry: Entry }+ let _: Response = try await call("connectorRequestFinish", Body(entryId: entryId, connectorId: connectorId, value: value, cancel: cancel), timeout: 120)+ }++ func credentialStatus() async throws -> CredentialStatus { try await call("credentialStatus", timeout: 60) }+ func setOnePasswordToken(_ token: String) async throws -> CredentialStatus {+ try await call("credentialSetOnePassword", ["token": token], timeout: 60)+ }+}++public extension HostClient {+ func updateConnectorCredentials(_ id: String, fields: [String: String]) async throws {+ struct Body: Encodable { var id: String; var fields: [String: String] }+ struct Result: Decodable { var status: String }+ let _: Result = try await call("credentialUpdateConnector", Body(id: id, fields: fields), timeout: 120)+ }+}diff --git a/kit/Sources/CodyncKit/Models/Models.swift b/kit/Sources/CodyncKit/Models/Models.swiftindex 281239bf..1d1c72fa 100644--- a/kit/Sources/CodyncKit/Models/Models.swift+++ b/kit/Sources/CodyncKit/Models/Models.swift@@ -16,6 +16,8 @@ public struct Bot: Codable, Identifiable, Hashable, Sendable {public var backend: Stringpublic var command: String?public var cwd: String+ /// Host-allocated personal workspace rather than a user-selected project.+ public var managedWorkspace: Bool = false/// `ask` or `auto`.public var permission: Stringpublic var model: String?@@ -49,7 +51,7 @@ public struct Bot: Codable, Identifiable, Hashable, Sendable {isWorking && (workingChat ?? id) == chat && workingThread == thread}public var needsInput: Bool { status == "needsInput" }- public var folderName: String { (cwd as NSString).lastPathComponent }+ public var folderName: String { managedWorkspace ? "Personal workspace" : (cwd as NSString).lastPathComponent }}/// Just enough of a `bot` event to detect deletions.@@ -100,6 +102,7 @@ public struct Entry: Codable, Identifiable, Hashable, Sendable {}public struct EntryData: Codable, Hashable, Sendable {+ public var connectionRequest: ConnectionRequest?public var routineId: String?public var runId: String?public var text: String?@@ -126,6 +129,10 @@ public struct EntryData: Codable, Hashable, Sendable {public var thread: ThreadSummary?/// The user's emoji reactions, oldest first.public var reactions: [String]?+ /// Files sent with a user message.+ public var attachments: [Attachment]?+ /// notice: a finished voice call's length.+ public var callSeconds: Int?public init(text: String? = nil, status: String? = nil, clientNonce: String? = nil) {self.text = text@@ -134,6 +141,23 @@ public struct EntryData: Codable, Hashable, Sendable {}}+/// A file sent with a message; the agent reads it on the computer.+public struct Attachment: Codable, Hashable, Sendable, Identifiable {+ public var id: String+ public var name: String+ public var size: Int64++ public init(id: String, name: String, size: Int64) {+ self.id = id+ self.name = name+ self.size = size+ }++ public var isImage: Bool {+ ["png", "jpg", "jpeg", "heic", "gif", "webp", "tiff", "bmp"].contains((name as NSString).pathExtension.lowercased())+ }+}+public struct ThreadSummary: Codable, Hashable, Sendable {public var count: Intpublic var lastAt: Int64@@ -448,7 +472,7 @@ public struct BotDraft: Codable, Hashable, Sendable {avatarShape = bot.avatarShapebackend = bot.backendcommand = bot.command- cwd = bot.cwd+ cwd = bot.managedWorkspace ? "" : bot.cwdpermission = bot.permissionmodel = bot.modelpinned = bot.pinned@@ -478,6 +502,7 @@ extension Bot {backend = try c.decodeIfPresent(String.self, forKey: .backend) ?? "custom"command = try c.decodeIfPresent(String.self, forKey: .command)cwd = try c.decodeIfPresent(String.self, forKey: .cwd) ?? ""+ managedWorkspace = try c.decodeIfPresent(Bool.self, forKey: .managedWorkspace) ?? falsepermission = try c.decodeIfPresent(String.self, forKey: .permission) ?? "ask"model = try c.decodeIfPresent(String.self, forKey: .model)pinned = try c.decodeIfPresent(Bool.self, forKey: .pinned) ?? falsediff --git a/kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swift b/kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swiftindex 7eab9e26..331bcf05 100644--- a/kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swift+++ b/kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swift@@ -1,81 +1,63 @@import Foundation-/// Editable common schedules, with a lossless fallback for compound/event triggers.-public struct RoutineScheduleDraft: Sendable {- public var kind = "interval"+/// Form values only. The host hydrates, compiles, validates and describes schedules.+public struct RoutineScheduleDraft: Codable, Hashable, Sendable {+ public var kind = "cron"public var amount = "1"public var unit: Int64 = 3600public var calendarStyle = "daily"public var weekday = 1- public var timeOfDay = Date(timeIntervalSince1970: 9 * 3600)- public var date = Date().addingTimeInterval(3600)- public var expression = "0 9 * * *"- public var zone = TimeZone.current.identifier+ public var selectedDays: Set<Int> = []+ public var monthDay = 1+ public var minuteStep = 15+ public var hour = 9+ public var minute = 0+ public var at: Int64 = 0+ public var expression = ""+ public var zone = ""public var original: [RoutineTrigger] = []- public init(triggers: [RoutineTrigger] = []) {- original = triggers- guard !triggers.isEmpty else { return }- guard triggers.count == 1, let trigger = triggers.first else { kind = "keep"; return }- kind = trigger.type- switch trigger.type {- case "interval":- let seconds = trigger.seconds ?? 3600- unit = [Int64(86400), 3600, 60, 1].first { seconds % $0 == 0 } ?? 1- amount = String(seconds / unit)- case "once": date = Date(timeIntervalSince1970: Double(trigger.at ?? 0) / 1000)- case "cron":- expression = trigger.expression ?? ""- zone = trigger.timeZone ?? TimeZone.current.identifier- calendarStyle = "custom"- let fields = expression.split(separator: " ").map(String.init)- if fields.count == 5, let minute = Int(fields[0]), (0...59).contains(minute),- let hour = Int(fields[1]), (0...23).contains(hour), fields[2] == "*", fields[3] == "*" {- timeOfDay = Date(timeIntervalSince1970: Double(hour * 3600 + minute * 60))- if fields[4] == "*" { calendarStyle = "daily" }- else if fields[4] == "1-5" { calendarStyle = "weekdays" }- else if let day = Int(fields[4]), (0...6).contains(day) {- weekday = day- calendarStyle = "weekly"- }- }- case "webhook": break- default: kind = "keep"- }+ public init() {}++ /// DatePicker's Date is converted only for wire encoding; no scheduling is done here.+ public var date: Date {+ get { Date(timeIntervalSince1970: Double(at) / 1000) }+ set { at = Int64((newValue.timeIntervalSince1970 * 1000).rounded()) }}+}- public func triggers() throws -> [RoutineTrigger] {- switch kind {- case "keep": return original- case "interval":- guard let count = Int64(amount), count > 0, [1, 60, 3600, 86400].contains(unit) else {- throw ValidationError("Enter a positive whole number for the interval.")- }- let (seconds, overflow) = count.multipliedReportingOverflow(by: unit)- guard !overflow, seconds <= 31_536_000 else { throw ValidationError("The interval must be no longer than 365 days.") }- return [RoutineTrigger(type: "interval", seconds: seconds)]- case "cron":- guard TimeZone(identifier: zone) != nil else { throw ValidationError("Enter a valid time zone, such as Asia/Taipei.") }- var cron = expression- if calendarStyle != "custom" {- let seconds = Int(timeOfDay.timeIntervalSince1970)- let hour = ((seconds / 3600) % 24 + 24) % 24- let minute = ((seconds / 60) % 60 + 60) % 60- let days = calendarStyle == "weekly" ? String(weekday) : calendarStyle == "weekdays" ? "1-5" : "*"- cron = "\(minute) \(hour) * * \(days)"- }- return [RoutineTrigger(type: "cron", expression: cron, timeZone: zone)]- case "once":- if original.count == 1, original[0].type == "once", let at = original[0].at,- date == Date(timeIntervalSince1970: Double(at) / 1000) { return original }- return [RoutineTrigger(type: "once", at: Int64((date.timeIntervalSince1970 * 1000).rounded()))]- case "webhook": return [RoutineTrigger(type: "webhook")]- default: throw ValidationError("Choose when this routine should run.")- }+public struct RoutineSchedulePreview: Codable, Sendable {+ public var draft: RoutineScheduleDraft+ public var triggers: [RoutineTrigger]+ public var summary: String+ public var nextRunAt: Int64?+ public var warning: String?+}++extension HostClient {+ public func routineSchedule(triggers: [RoutineTrigger], timeZone: String) async throws -> RoutineSchedulePreview {+ struct Body: Encodable { let triggers: [RoutineTrigger]; let timeZone: String }+ return try await call("routineSchedule", Body(triggers: triggers, timeZone: timeZone))+ }++ public func routineSchedule(draft: RoutineScheduleDraft) async throws -> RoutineSchedulePreview {+ struct Body: Encodable { let draft: RoutineScheduleDraft }+ return try await call("routineSchedule", Body(draft: draft))}- private struct ValidationError: LocalizedError {- let errorDescription: String?- init(_ message: String) { errorDescription = message }+ public func saveRoutine(botId: String, id: String?, name: String, instruction: String,+ schedule: RoutineScheduleDraft, timeoutSeconds: String) async throws -> Routine {+ struct Body: Encodable {+ let botId: String+ let id: String?+ let name: String+ let instruction: String+ let schedule: RoutineScheduleDraft+ let timeoutSeconds: String+ }+ struct Response: Decodable { let routine: Routine }+ let response: Response = try await call("saveRoutine", Body(botId: botId, id: id, name: name,+ instruction: instruction, schedule: schedule, timeoutSeconds: timeoutSeconds))+ return response.routine}}diff --git a/kit/Sources/CodyncUI/Bots/AgentModelPicker.swift b/kit/Sources/CodyncUI/Bots/AgentModelPicker.swiftindex 1d9aefdc..d5ff5649 100644--- a/kit/Sources/CodyncUI/Bots/AgentModelPicker.swift+++ b/kit/Sources/CodyncUI/Bots/AgentModelPicker.swift@@ -44,7 +44,11 @@ struct AgentModelPicker: View {var body: some View {VStack(alignment: .leading, spacing: 6) {- OptionRow("Model") {+ HStack(spacing: 8) {+ Text("Model")+ .foregroundStyle(Palette.text)+ .fixedSize()+ Spacer(minLength: 0)HStack(spacing: 4) {if backend != "custom" { refreshControl }if backend == "custom" || (!loading && catalog?.models.isEmpty != false) {@@ -52,10 +56,10 @@ struct AgentModelPicker: View {.plainTextInput().multilineTextAlignment(.trailing).textFieldStyle(.plain)- .frame(width: InterfaceMetrics.value(mac: 160, mobile: 180))+ .frame(minWidth: 0, maxWidth: InterfaceMetrics.value(mac: 160, mobile: 180)).pill()} else {- ChoicePicker(selection: value, options: options, fill: Palette.background)+ ChoicePicker(selection: value, options: options, fill: Palette.background, fitsAvailableWidth: true)}}}diff --git a/kit/Sources/CodyncUI/Bots/BotEditorView.swift b/kit/Sources/CodyncUI/Bots/BotEditorView.swiftindex 6d3b542a..a29447fe 100644--- a/kit/Sources/CodyncUI/Bots/BotEditorView.swift+++ b/kit/Sources/CodyncUI/Bots/BotEditorView.swift@@ -13,8 +13,15 @@ public struct BotEditorView: View {@Environment(BotStore.self) private var model@Environment(\.dismissModal) private var dismiss@State var draft: BotDraft-- public init(draft: BotDraft) { _draft = State(initialValue: draft) }+ private let computers: [(id: ComputerID, label: String)]+ private let computer: Binding<ComputerID>?++ /// `computer` lets a new bot pick which computer it runs on; the caller swaps the `BotStore` to match.+ public init(draft: BotDraft, computers: [(id: ComputerID, label: String)] = [], computer: Binding<ComputerID>? = nil) {+ _draft = State(initialValue: draft)+ self.computers = computers+ self.computer = computer+ }@State private var saving = false@State private var error: String?@@ -30,10 +37,18 @@ public struct BotEditorView: View {.disabled(!draft.isValid)}}- BotSettingsForm(draft: $draft, error: error)+ BotSettingsForm(draft: $draft, error: error, computers: computers, computer: computer)}.background(Palette.background).onAppear { if isNew { model.fillDefaults(&draft) } }+ .onChange(of: model.computer.id) {+ // Folders, models and connectors belong to the old computer.+ draft.cwd = ""+ draft.model = nil+ draft.connectors = nil+ draft.skills = nil+ model.fillDefaults(&draft)+ }}private func save() {@@ -91,7 +106,10 @@ public struct BotSettingsPanel: View {struct BotSettingsForm: View {@Binding var draft: BotDraftlet error: String?+ var computers: [(id: ComputerID, label: String)] = []+ var computer: Binding<ComputerID>?@Environment(BotStore.self) private var model+ @Environment(\.accessibilityReduceMotion) private var reduceMotion@State private var pickingFolder = false@State private var pickingAvatar = false@State private var avatarFrame: CGRect = .zero@@ -141,9 +159,13 @@ struct BotSettingsForm: View {// Grok-style option card: no dividers, values in outlined pills.VStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 12, mobile: 20)) {OptionRow("Computer") {- Text(model.hostName)- .lineLimit(1)- .foregroundStyle(Palette.secondary)+ if let computer {+ ChoicePicker(selection: computer, options: computers, fill: Palette.background)+ } else {+ Text(model.hostName)+ .lineLimit(1)+ .foregroundStyle(Palette.secondary)+ }}OptionRow("Agent") {ChoicePicker(selection: $draft.backend,@@ -161,17 +183,30 @@ struct BotSettingsForm: View {.fieldBox()}AgentModelPicker(backend: draft.backend, selection: $draft.model)- OptionRow("Project folder") {- Button { pickingFolder = true } label: {+ OptionRow("Workspace") {+ DropdownMenu {+ [+ MenuItem("Personal workspace", selected: draft.cwd.isEmpty) {+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { draft.cwd = "" }+ },+ MenuItem("Choose project folder…", selected: !draft.cwd.isEmpty) {+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { pickingFolder = true }+ },+ ]+ } label: {HStack(spacing: 6) {- Text(draft.cwd.isEmpty ? "Choose" : (draft.cwd as NSString).lastPathComponent).lineLimit(1)- Image(systemName: "chevron.right").font(.caption2.weight(.semibold)).foregroundStyle(Palette.secondary)+ Text(draft.cwd.isEmpty ? "Personal" : (draft.cwd as NSString).lastPathComponent).lineLimit(1)+ Image(systemName: "chevron.down").font(.caption2.weight(.semibold))}.pill()}- .buttonStyle(.plain)- .help(draft.cwd)+ .help(draft.cwd.isEmpty ? "A persistent workspace allocated for this bot" : draft.cwd)}+ Text(draft.cwd.isEmpty+ ? "This bot has its own space for files. It can work in other folders when you ask."+ : "This project is the default starting folder. The bot can work elsewhere when you ask.")+ .font(.caption)+ .foregroundStyle(Palette.secondary)OptionRow("Permissions") {ChoicePicker(selection: $draft.permission, options: [("ask", "Ask me"), ("auto", "Approve automatically")],fill: Palette.background)@@ -332,7 +367,7 @@ extension View {}extension BotDraft {- var isValid: Bool { !name.trimmingCharacters(in: .whitespaces).isEmpty && !cwd.isEmpty }+ var isValid: Bool { !name.trimmingCharacters(in: .whitespaces).isEmpty }/// What the host should get: no stale command unless the agent is custom.var normalized: BotDraft {@@ -343,13 +378,12 @@ extension BotDraft {}public extension BotStore {- /// Picks an installed agent and the home folder for a new bot.+ /// Picks an installed agent; empty cwd requests a personal workspace from the host.func fillDefaults(_ draft: inout BotDraft) {if hello?.backends.first(where: { $0.id == draft.backend })?.available != true,let first = hello?.backends.first(where: \.available) {draft.backend = first.id}- if draft.cwd.isEmpty, let home = hello?.home { draft.cwd = home }}/// Creates "New Bot" with sensible defaults and opens it (desktop compose flow).diff --git a/kit/Sources/CodyncUI/Bots/BotRow.swift b/kit/Sources/CodyncUI/Bots/BotRow.swiftindex 4ef779da..e0bdcfc0 100644--- a/kit/Sources/CodyncUI/Bots/BotRow.swift+++ b/kit/Sources/CodyncUI/Bots/BotRow.swift@@ -103,43 +103,3 @@ public struct BotRow: View {}}}--public struct ConnectionBanner: View {- @Environment(BotStore.self) private var model-- public init() {}-- public var body: some View {- switch model.connection {- case .online, .unpaired:- EmptyView()- case .connecting:- EmptyView()- case let .computerOffline(lastSeen):- let seen = lastSeen.map { " Last seen \(RelativeTime.day($0))." } ?? ""- banner(icon: "moon.zzz", title: "\(model.hostName) is offline",- detail: (model.canQueue ? "Messages wait and go out when it's back online." : "It's asleep or turned off.") + seen,- retry: false)- case let .offline(reason):- banner(icon: "wifi.exclamationmark", title: "Can't reach \(model.hostName)", detail: reason, retry: true)- case let .unauthorized(reason):- banner(icon: "lock.slash", title: "No access to \(model.hostName)", detail: reason, retry: false)- }- }-- private func banner(icon: String, title: String, detail: String, retry: Bool) -> some View {- HStack(alignment: .top, spacing: 8) {- Image(systemName: icon).foregroundStyle(Palette.warning)- VStack(alignment: .leading, spacing: 2) {- Text(title).font(.footnote.weight(.semibold)).foregroundStyle(Palette.text)- Text(detail).font(.footnote).foregroundStyle(Palette.secondary)- }- Spacer()- if retry {- IconButton("Retry", systemImage: "arrow.clockwise") { model.restartStream() }- }- }- .padding(10)- .background(Palette.surface, in: RoundedRectangle(cornerRadius: 10))- }-}diff --git a/kit/Sources/CodyncUI/Bots/BotTemplateView.swift b/kit/Sources/CodyncUI/Bots/BotTemplateView.swiftindex 3faad00f..d1679c6a 100644--- a/kit/Sources/CodyncUI/Bots/BotTemplateView.swift+++ b/kit/Sources/CodyncUI/Bots/BotTemplateView.swift@@ -36,7 +36,7 @@ struct BotTemplateView: View {}.background(Palette.surface, in: RoundedRectangle(cornerRadius: 12))HStack {- Text("Includes the working folder and agent configuration.")+ Text("Includes workspace preferences and agent configuration.").font(.caption).foregroundStyle(Palette.secondary)Spacer()Button {diff --git a/kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swift b/kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swiftnew file mode 100644index 00000000..faf189b5--- /dev/null+++ b/kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swift@@ -0,0 +1,113 @@+import CodyncKit+import SwiftUI++/// The roster's only connection surface: a quiet summary, with details and filters on demand.+public struct ComputerFilterHeader: View {+ let accounts: AccountStore+ @Binding var hidden: String+ let manage: () -> Void+ let compact: Bool+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ public init(accounts: AccountStore, hidden: Binding<String>, compact: Bool = false, manage: @escaping () -> Void) {+ self.accounts = accounts+ _hidden = hidden+ self.manage = manage+ self.compact = compact+ }++ private var selection: ComputerSelection {+ ComputerSelection(all: accounts.computers.map(\.id), hidden: hidden)+ }++ private var stores: [BotStore] { selection.shown.compactMap { accounts.store(for: $0) } }+ private var summary: String { ConnectionSummary(connections: stores.map(\.connection)).text }++ public var body: some View {+ #if os(iOS)+ Menu {+ Button("All computers", systemImage: selection.shown.count == accounts.computers.count ? "checkmark" : "desktopcomputer") { update("") }+ ForEach(accounts.computers) { computer in+ Button {+ update(selection.toggling(computer.id))+ } label: {+ Label(computerTitle(computer), systemImage: selection.shown.contains(computer.id) ? "checkmark" : "desktopcomputer")+ }+ .menuActionDismissBehavior(.disabled)+ }+ if accounts.computers.count > 1 {+ Menu("Show only") {+ ForEach(accounts.computers) { computer in+ Button(computer.name) { update(selection.only(computer.id)) }+ }+ }+ }+ Divider()+ Button("Reconnect", systemImage: "arrow.clockwise", action: reconnect)+ .disabled(stores.isEmpty)+ Button("Manage computers", systemImage: "desktopcomputer", action: manage)+ } label: { label }+ .accessibilityLabel("Computers, \(summary). Filter conversations")+ #else+ DropdownMenu {+ var items = [MenuItem("All computers", selected: selection.shown.count == accounts.computers.count) { update("") }]+ items += accounts.computers.map { computer in+ MenuItem(computerTitle(computer), selected: selection.shown.contains(computer.id)) {+ update(selection.toggling(computer.id))+ }+ }+ if accounts.computers.count > 1 {+ items += accounts.computers.enumerated().map { index, computer in+ MenuItem("Only \(computer.name)", divider: index == 0) { update(selection.only(computer.id)) }+ }+ }+ if !stores.isEmpty {+ items.append(MenuItem("Reconnect", icon: "arrow.clockwise", divider: true, action: reconnect))+ }+ items.append(MenuItem("Manage computers", icon: "desktopcomputer", action: manage))+ return items+ } label: { label }+ .accessibilityLabel("Computers, \(summary). Filter conversations")+ #endif+ }++ private var label: some View {+ HStack(spacing: 4) {+ if compact {+ Image(systemName: "desktopcomputer")+ } else {+ Text(summary).lineLimit(1).contentTransition(.opacity)+ }+ Image(systemName: "chevron.down").font(.system(size: 8, weight: .semibold))+ }+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(Palette.secondary)+ .help(summary)+ .padding(.vertical, 6)+ .contentShape(Rectangle())+ .animation(Motion.reduced(Motion.fade, reduceMotion), value: summary)+ }++ private func computerTitle(_ computer: Computer) -> String {+ guard let store = accounts.store(for: computer.id) else { return computer.name }+ return "\(store.hostName) · \(store.connectionLabel)"+ }++ private func update(_ value: String) {+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { hidden = value }+ }++ private func reconnect() { for store in stores { store.restartStream() } }+}++public extension BotStore {+ var connectionLabel: String {+ switch connection {+ case .online: "Connected"+ case .connecting: "Connecting…"+ case .computerOffline, .offline: "Offline"+ case .unauthorized: "No access"+ case .unpaired: "Not paired"+ }+ }+}diff --git a/kit/Sources/CodyncUI/Call/CallSession.swift b/kit/Sources/CodyncUI/Call/CallSession.swiftindex b5d68ee9..013ac31f 100644--- a/kit/Sources/CodyncUI/Call/CallSession.swift+++ b/kit/Sources/CodyncUI/Call/CallSession.swift@@ -24,6 +24,8 @@ final class CallSession {private(set) var heard = ""/// The reply being read aloud.private(set) var said = ""+ /// Microphone loudness, 0…1, while listening.+ private(set) var level: Float = 0var muted = false {didSet {guard muted != oldValue, phase == .listening else { return }@@ -43,8 +45,15 @@ final class CallSession {private var speechDone: SpeechDone?private var ended = false+ /// Call settings (the gear), kept across calls.+ static let pauseKey = "callPause"+ static let rateKey = "callRate"+/// A pause this long ends what you're saying and sends it.- static let endOfUtterance: Duration = .milliseconds(1500)+ private var endOfUtterance: Duration {+ let seconds = UserDefaults.standard.double(forKey: Self.pauseKey)+ return .milliseconds(Int((seconds > 0 ? seconds : 1.5) * 1000))+ }init(send: @escaping (String) -> Void) {self.send = send@@ -90,6 +99,8 @@ final class CallSession {phase = .speakinglet utterance = AVSpeechUtterance(string: text)utterance.voice = Self.voice(for: text)+ let rate = UserDefaults.standard.float(forKey: Self.rateKey)+ utterance.rate = rate > 0 ? rate : AVSpeechUtteranceDefaultSpeechRatesynthesizer.speak(utterance)}@@ -114,7 +125,9 @@ final class CallSession {self.request = requestlet input = engine.inputNodeinput.removeTap(onBus: 0)- input.installTap(onBus: 0, bufferSize: 1024, format: input.outputFormat(forBus: 0), block: Self.tap(request))+ input.installTap(onBus: 0, bufferSize: 1024, format: input.outputFormat(forBus: 0), block: Self.tap(request) { [weak self] level in+ Task { @MainActor in self?.level = level }+ })engine.prepare()do {try engine.start()@@ -135,6 +148,7 @@ final class CallSession {request = nilif engine.isRunning { engine.stop() }engine.inputNode.removeTap(onBus: 0)+ level = 0}fileprivate func recognized(_ text: String, final: Bool, generation: Int) {@@ -143,7 +157,7 @@ final class CallSession {silence?.cancel()if final { return submit() }silence = Task {- try? await Task.sleep(for: Self.endOfUtterance)+ try? await Task.sleep(for: endOfUtterance)guard !Task.isCancelled else { return }submit()}@@ -169,8 +183,18 @@ final class CallSession {// MARK: audio-thread closures (built outside the main actor)- private nonisolated static func tap(_ request: SFSpeechAudioBufferRecognitionRequest) -> AVAudioNodeTapBlock {- { buffer, _ in request.append(buffer) }+ private nonisolated static func tap(_ request: SFSpeechAudioBufferRecognitionRequest,+ meter: @escaping @Sendable (Float) -> Void) -> AVAudioNodeTapBlock {+ { buffer, _ in+ request.append(buffer)+ guard let samples = buffer.floatChannelData?[0], buffer.frameLength > 0 else { return }+ let n = Int(buffer.frameLength)+ var sum: Float = 0+ for i in 0..<n { sum += samples[i] * samples[i] }+ // -50 dB (quiet room) … 0 dB mapped to 0…1.+ let db = 10 * log10(max(sum / Float(n), 1e-10))+ meter(min(1, max(0, (db + 50) / 50)))+ }}private nonisolated static func results(_ session: CallSession, generation: Int) -> @Sendable (SFSpeechRecognitionResult?, (any Error)?) -> Void {diff --git a/kit/Sources/CodyncUI/Call/CallView.swift b/kit/Sources/CodyncUI/Call/CallView.swiftindex 3ac25e61..9fcce615 100644--- a/kit/Sources/CodyncUI/Call/CallView.swift+++ b/kit/Sources/CodyncUI/Call/CallView.swift@@ -1,9 +1,11 @@#if os(iOS)+import AVFoundationimport CodyncKitimport SwiftUI-/// A voice call with a bot: talk hands-free, hear its final replies. Everything else about the-/// turn (tools, thinking) stays in the chat.+/// A voice call with a bot, as Grok Bot does it: a floating bar over the chat, which stays+/// readable underneath. What you say goes out as ordinary messages, its final replies are+/// read aloud, and the chat gets a "Voice chat · 00:16" line when the call ends.struct CallView: View {let botId: Stringlet close: () -> Void@@ -11,138 +13,169 @@ struct CallView: View {@Environment(\.accessibilityReduceMotion) private var reduceMotion@State private var session: CallSession?@State private var startedAt = Date.now+ @State private var settings = falseprivate var bot: Bot? { model.bots[botId] }/// The newest final reply; each new one is read aloud.private var lastReply: Entry? { model.chat(botId).last { $0.kind == "agent" && $0.data.final == true } }+ private var color: Color { bot.map { AvatarPalette.color($0.avatarColor) } ?? Palette.accent }var body: some View {- VStack(spacing: 0) {- header.padding(.top, 24)- Spacer()- center- Spacer()- caption- .frame(maxWidth: .infinity, minHeight: 96, alignment: .top)- .padding(.horizontal, 32)- controls.padding(.bottom, 32).padding(.top, 24)+ VStack(spacing: 6) {+ bar+ if case .failed(let message) = session?.phase {+ Text(message)+ .font(.footnote)+ .foregroundStyle(Palette.danger)+ .multilineTextAlignment(.center)+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ .glass(in: Capsule())+ .transition(.opacity)+ }}- .frame(maxWidth: .infinity, maxHeight: .infinity)- .background(Palette.background.ignoresSafeArea())+ .padding(.horizontal, 12).animation(Motion.reduced(Motion.fade, reduceMotion), value: session?.phase).onAppear {let session = CallSession { [model, botId] in model.send($0, to: botId) }self.session = session+ startedAt = .nowTask { await session.start() }}- .onDisappear { session?.end() }+ .onDisappear {+ session?.end()+ model.logCall(botId, seconds: Int(Date.now.timeIntervalSince(startedAt)))+ }.onChange(of: lastReply?.id) { _, _ inif let text = lastReply?.data.text { session?.speak(text) }}.onChange(of: bot?.needsInput) { _, needs inif needs == true { session?.speak("\(bot?.name ?? "The bot") needs your approval in the chat.") }}+ .codyncSheet(isPresented: $settings) { CallSettingsView() }}- private var header: some View {- VStack(spacing: 6) {- Text(bot?.name ?? "")- .font(.title2.weight(.semibold))- .foregroundStyle(Palette.text)- TimelineView(.periodic(from: startedAt, by: 1)) { context in- Text(status(now: context.date))- .font(.subheadline.monospacedDigit())- .foregroundStyle(Palette.secondary)- .contentTransition(.numericText())+ private var bar: some View {+ HStack(spacing: 10) {+ avatar+ CallLevelDots(level: session?.level ?? 0, speaking: session?.phase == .speaking,+ working: bot?.isWorking == true, color: color, reduceMotion: reduceMotion)+ .frame(maxWidth: .infinity, minHeight: 20, maxHeight: 20)+ .accessibilityLabel(statusText)+ round("Call settings", "gearshape") { settings = true }+ let muted = session?.muted == true+ round(muted ? "Unmute" : "Mute", muted ? "mic.slash" : "mic", on: muted) { session?.muted.toggle() }+ Button(action: close) {+ Image(systemName: "xmark")+ .font(.system(size: 17, weight: .semibold))+ .foregroundStyle(.white)+ .frame(width: 46, height: 46)+ .background(Palette.danger, in: Circle())}+ .buttonStyle(PressScale())+ .accessibilityLabel("End call")}+ .padding(.leading, 14)+ .padding(.trailing, 7)+ .padding(.vertical, 7)+ .glass(in: Capsule())+ .shadow(color: .black.opacity(0.08), radius: 16, y: 6)}- private var center: some View {- Button {- session?.interrupt()- } label: {- ZStack {- if let session, session.phase == .listening, !session.muted {- ThinkingOrb(state: .listening, size: 220, color: Palette.tertiary)- } else if bot?.isWorking == true, session?.phase != .speaking {- ThinkingOrb(state: .working, size: 220, color: Palette.tertiary)- }- if let bot { CharacterAvatar(bot: bot, size: 120) }+ /// The bot; tapping it while it talks cuts the reply short.+ private var avatar: some View {+ Button { session?.interrupt() } label: {+ Group {+ if let bot { CharacterAvatar(bot: bot, size: 34) }}- .frame(width: 240, height: 240)- .scaleEffect(session?.phase == .speaking && !reduceMotion ? 1.06 : 1)- .animation(.easeInOut(duration: 0.9).repeatForever(autoreverses: true), value: session?.phase == .speaking)- .contentShape(Circle())+ .scaleEffect(session?.phase == .speaking && !reduceMotion ? 1.1 : 1)+ .animation(reduceMotion ? nil : .easeInOut(duration: 0.6).repeatForever(autoreverses: true), value: session?.phase == .speaking)}.buttonStyle(.plain).disabled(session?.phase != .speaking).accessibilityLabel(session?.phase == .speaking ? "Interrupt" : bot?.name ?? "")}- @ViewBuilder private var caption: some View {+ private func round(_ label: String, _ symbol: String, on: Bool = false, action: @escaping () -> Void) -> some View {+ Button(action: action) {+ Image(systemName: symbol)+ .font(.system(size: 17, weight: .medium))+ .foregroundStyle(on ? Palette.onAccent : Palette.text)+ .contentTransition(.symbolEffect(.replace))+ .frame(width: 46, height: 46)+ .background(on ? Palette.accentFill : Palette.background, in: Circle())+ }+ .buttonStyle(PressScale())+ .accessibilityLabel(label)+ }++ private var statusText: String {switch session?.phase {- case .failed(let message):- Text(message)- .font(.callout)- .foregroundStyle(Palette.danger)- .multilineTextAlignment(.center)- case .speaking:- Text(session?.said ?? "")- .font(.body)- .foregroundStyle(Palette.text)- .multilineTextAlignment(.center)- .lineLimit(4)- .truncationMode(.head)- default:- Text(session?.heard ?? "")- .font(.title3)- .foregroundStyle(Palette.text)- .multilineTextAlignment(.center)- .lineLimit(3)- .truncationMode(.head)+ case .starting, nil: "Connecting"+ case .speaking: "Speaking"+ case .failed: "Can't listen"+ case .listening where session?.muted == true: "Muted"+ case .listening: bot?.isWorking == true ? "Working, listening" : "Listening"}}+}- private var controls: some View {- HStack(spacing: 56) {- let muted = session?.muted == true- Button {- session?.muted.toggle()- } label: {- Image(systemName: muted ? "mic.slash.fill" : "mic.fill")- .font(.system(size: 24, weight: .semibold))- .frame(width: 72, height: 72)- .background(muted ? Palette.accentFill : Palette.surface, in: Circle())- .foregroundStyle(muted ? Palette.onAccent : Palette.text)- .contentTransition(.symbolEffect(.replace))- }- .buttonStyle(PressScale())- .accessibilityLabel(muted ? "Unmute" : "Mute")- Button(action: close) {- Image(systemName: "phone.down.fill")- .font(.system(size: 26, weight: .semibold))- .frame(width: 72, height: 72)- .background(Palette.danger, in: Circle())- .foregroundStyle(.white)+/// The dotted line in the call bar: it follows your voice while listening, ripples while+/// the bot talks, breathes while it works, and rests as faint dots otherwise.+private struct CallLevelDots: View {+ let level: Float+ let speaking: Bool+ let working: Bool+ let color: Color+ let reduceMotion: Bool++ var body: some View {+ TimelineView(.animation(paused: reduceMotion)) { context in+ Canvas { canvas, size in+ let t = context.date.timeIntervalSinceReferenceDate+ let spacing: CGFloat = 8+ let count = max(1, Int(size.width / spacing))+ for i in 0..<count {+ let x = CGFloat(i) * spacing + spacing / 2+ let wave = (sin(Double(i) * 0.55 - t * 6) + 1) / 2+ let amount: Double = if speaking {+ 0.35 + 0.65 * wave+ } else if level > 0.05 {+ Double(level) * (0.4 + 0.6 * wave)+ } else if working {+ 0.25 * ((sin(t * 2.4) + 1) / 2)+ } else {+ 0+ }+ let height = 3 + CGFloat(amount) * (size.height - 3)+ let rect = CGRect(x: x - 1.5, y: (size.height - height) / 2, width: 3, height: height)+ canvas.fill(Path(roundedRect: rect, cornerRadius: 1.5), with: .color(color.opacity(0.3 + 0.7 * amount)))+ }}- .buttonStyle(PressScale())- .accessibilityLabel("End call")}- .animation(Motion.reduced(Motion.fade, reduceMotion), value: session?.muted)}+}- private func status(now: Date) -> String {- let seconds = Int(now.timeIntervalSince(startedAt))- let clock = String(format: "%d:%02d", seconds / 60, seconds % 60)- let state: String = switch session?.phase {- case .starting, nil: "Connecting…"- case .speaking: "Speaking"- case .failed: "Can't listen"- case .listening where session?.muted == true: "Muted"- case .listening: bot?.isWorking == true ? "Working · listening" : "Listening"+/// The call bar's gear: how long a pause sends what you said, and how fast replies are read.+private struct CallSettingsView: View {+ @AppStorage(CallSession.pauseKey) private var pause = 1.5+ @AppStorage(CallSession.rateKey) private var rate = Double(AVSpeechUtteranceDefaultSpeechRate)++ var body: some View {+ VStack(spacing: 0) {+ ModalHeader("Voice chat")+ CardForm {+ CardSection("Send after a pause of", footer: "Longer gives you time to think mid-sentence.") {+ SegmentedChoice(selection: $pause, options: [(1.0, "1 s"), (1.5, "1.5 s"), (2.5, "2.5 s")])+ }+ CardSection("Reading speed") {+ SegmentedChoice(selection: $rate, options: [+ (0.42, "Slower"), (Double(AVSpeechUtteranceDefaultSpeechRate), "Normal"), (0.56, "Faster"),+ ])+ }+ }}- return "\(state) · \(clock)"+ .background(Palette.background)}}#endifdiff --git a/kit/Sources/CodyncUI/Chrome.swift b/kit/Sources/CodyncUI/Chrome.swiftindex 0b147fcc..df7a4d94 100644--- a/kit/Sources/CodyncUI/Chrome.swift+++ b/kit/Sources/CodyncUI/Chrome.swift@@ -134,51 +134,6 @@ public struct ScreenHeader<Leading: View, Title: View, Trailing: View>: View {}}-/// A small connection state shown in the center of a screen header.-public struct ConnectingIndicator: View {- let isConnecting: Bool- @Environment(\.accessibilityReduceMotion) private var reduceMotion- @State private var isVisible = false- @State private var shownAt = Date.distantPast-- public init(isConnecting: Bool) { self.isConnecting = isConnecting }-- public var body: some View {- Group {- if isVisible {- HStack(spacing: 6) {- ThinkingOrb(state: .connecting, size: 14, color: Palette.secondary)- Text("Connecting")- .font(.system(size: 12, weight: .medium))- .foregroundStyle(Palette.secondary)- .lineLimit(1)- }- .transition(.opacity)- .accessibilityLabel("Connecting")- }- }- .task(id: isConnecting) {- if isConnecting {- if !isVisible {- // A reconnect that settles within 0.4 s never shows, so nothing flashes.- try? await Task.sleep(for: .milliseconds(400))- guard !Task.isCancelled else { return }- shownAt = .now- withAnimation(Motion.reduced(Motion.fade, reduceMotion)) { isVisible = true }- }- } else if isVisible {- let remainingMilliseconds = max(0, Int((0.7 - Date.now.timeIntervalSince(shownAt)) * 1_000))- if remainingMilliseconds > 0 {- try? await Task.sleep(for: .milliseconds(Int64(remainingMilliseconds)))- }- guard !Task.isCancelled else { return }- withAnimation(Motion.reduced(Motion.fade, reduceMotion)) { isVisible = false }- }- }- .frame(minWidth: 1, minHeight: 1)- }-}-/// The back button for a pushed screen.public struct BackButton: View {let action: () -> Void@@ -450,10 +405,15 @@ private struct ModalHostModifier: ViewModifier {.overlay {ZStack {ForEach(host.entries) { entry in- switch entry.chrome {- case .card: ModalCard(shown: entry.shown) { entry.content }- case .bare: entry.content.opacity(entry.shown ? 1 : 0).scaleEffect(entry.shown ? 1 : 0.98)+ Group {+ switch entry.chrome {+ case .card: ModalCard(shown: entry.shown) { entry.content }+ case .bare: entry.content.opacity(entry.shown ? 1 : 0).scaleEffect(entry.shown ? 1 : 0.98)+ }}+ // A menu above a sheet becomes the active accessibility surface.+ .accessibilityHidden(entry.id != host.entries.last?.id)+ .disabled(entry.id != host.entries.last?.id)}}}@@ -531,7 +491,11 @@ private struct CodyncOverlay<Layer: View>: ViewModifier {let layer: (_ close: @escaping () -> Void) -> Layerfunc body(content: Content) -> some View {- content.modifier(HostedPresentation(isPresented: $isPresented, chrome: .bare, layer: layer))+ content.modifier(HostedPresentation(isPresented: $isPresented, chrome: .bare) { close in+ layer(close)+ .accessibilityAddTraits(.isModal)+ .onExitCommand(perform: close)+ })}}diff --git a/kit/Sources/CodyncUI/Controls.swift b/kit/Sources/CodyncUI/Controls.swiftindex b54aab2f..5ba3e37d 100644--- a/kit/Sources/CodyncUI/Controls.swift+++ b/kit/Sources/CodyncUI/Controls.swift@@ -2,6 +2,8 @@ import CodyncKitimport SwiftUI#if os(macOS)import AppKit+#elseif os(iOS)+import UIKit#endif// Codync's own controls. Never use the stock ones (Menu, Picker, .switch toggles,@@ -157,11 +159,25 @@ public struct ReactionPick {}}+private struct MenuAvailableSizeKey: EnvironmentKey {+ static let defaultValue = CGSize(width: 320, height: 420)+}++private extension EnvironmentValues {+ var menuAvailableSize: CGSize {+ get { self[MenuAvailableSizeKey.self] }+ set { self[MenuAvailableSizeKey.self] = newValue }+ }+}+/// The floating panel of menu rows (used by every menu, popover or overlay).public struct MenuPanel: View {let items: [MenuItem]var reactions: ReactionPick?let dismiss: () -> Void+ @Environment(\.menuAvailableSize) private var availableSize+ @State private var contentHeight: CGFloat?+ @State private var positionedSelection = falsepublic init(items: [MenuItem], reactions: ReactionPick? = nil, dismiss: @escaping () -> Void) {self.items = items@@ -170,26 +186,47 @@ public struct MenuPanel: View {}public var body: some View {- VStack(alignment: .leading, spacing: 2) {- if let reactions {- ReactionStrip(pick: reactions, dismiss: dismiss)- .padding(.bottom, 4)- }- ForEach(items) { item in- if item.divider {- Rectangle().fill(Palette.text.opacity(0.1)).frame(height: 0.5)- .padding(.horizontal, 10).padding(.vertical, 4)- }- MenuRow(item: item) {- dismiss()- item.action()+ ScrollViewReader { proxy in+ ScrollView(.vertical) {+ VStack(alignment: .leading, spacing: 2) {+ if let reactions {+ ReactionStrip(pick: reactions, dismiss: dismiss)+ .padding(.bottom, 4)+ }+ ForEach(items) { item in+ if item.divider {+ Rectangle().fill(Palette.text.opacity(0.1)).frame(height: 0.5)+ .padding(.horizontal, 10).padding(.vertical, 4)+ }+ MenuRow(item: item) {+ dismiss()+ item.action()+ }+ .id(item.id)+ }}+ .padding(6)+ .fixedSize(horizontal: false, vertical: true)+ .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { contentHeight = $0 }+ }+ .scrollBounceBehavior(.basedOnSize)+ .frame(width: min(320, availableSize.width),+ height: min(contentHeight ?? estimatedHeight, availableSize.height))+ .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))+ .onChange(of: contentHeight) { _, height in+ guard height != nil, !positionedSelection,+ let selected = items.first(where: { $0.selected == true }) else { return }+ positionedSelection = true+ proxy.scrollTo(selected.id, anchor: .center)}}- .padding(6)- .frame(minWidth: InterfaceMetrics.value(mac: 180, mobile: 220))- .fixedSize()}++ private var estimatedHeight: CGFloat {+ CGFloat(items.count) * InterfaceMetrics.value(mac: 32, mobile: 46) + 12+ + (reactions == nil ? 0 : InterfaceMetrics.value(mac: 32, mobile: 46))+ }+}/// Quick-reaction buttons; a chosen one is highlighted and tapping it takes it back.@@ -256,7 +293,8 @@ private struct MenuRow: View {if let icon = item.icon {Image(systemName: icon).frame(width: 18)}- Text(item.title).lineLimit(1)+ // Wraps rather than truncates: a cut-off choice can't be read.+ Text(item.title).fixedSize(horizontal: false, vertical: true)Spacer(minLength: 16)if let selected = item.selected {Image(systemName: "checkmark").font(.caption.weight(.semibold)).opacity(selected ? 1 : 0)@@ -271,6 +309,7 @@ private struct MenuRow: View {}.buttonStyle(.plain).onHover { h in withAnimation(Motion.hover) { hovering = h } }+ .help(item.title).accessibilityAddTraits(item.selected == true ? .isSelected : [])}}@@ -341,23 +380,39 @@ struct AnchoredPanel<Panel: View>: View {let anchor: CGRectlet close: () -> Void@ViewBuilder let panel: () -> Panel+ #if os(macOS)+ @FocusState private var keyboardFocused: Bool+ #endifvar body: some View {GeometryReader { geo inlet space = geo.frame(in: .global)let a = anchor.offsetBy(dx: -space.minX, dy: -space.minY)- let below = a.maxY < space.height * 0.62+ let roomBelow = max(0, space.height - a.maxY - 14)+ let roomAbove = max(0, a.minY - 14)+ let below = roomBelow >= roomAbovelet leading = a.midX < space.width * 0.6+ let horizontalInset = max(8, space.width - min(320, space.width - 16) - 8)ZStack(alignment: Alignment(horizontal: leading ? .leading : .trailing, vertical: below ? .top : .bottom)) {Color.clear.contentShape(Rectangle()).onTapGesture(perform: close)panel()+ .environment(\.menuAvailableSize, CGSize(+ width: max(1, space.width - 16),+ height: max(1, min(420, below ? roomBelow : roomAbove))+ )).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 14, style: .continuous)).shadow(color: .black.opacity(0.25), radius: 20, y: 8)- .offset(x: leading ? max(8, a.minX) : -max(8, space.width - a.maxX),+ .offset(x: leading ? min(max(8, a.minX), horizontalInset) : -min(max(8, space.width - a.maxX), horizontalInset),y: below ? a.maxY + 6 : -(space.height - a.minY + 6))}}.ignoresSafeArea()+ #if os(macOS)+ .focusable()+ .focusEffectDisabled()+ .focused($keyboardFocused)+ .onAppear { keyboardFocused = true }+ #endif}}@@ -373,10 +428,37 @@ public struct DropdownMenu<Label: View>: View {}public var body: some View {+ #if os(iOS)+ // The system menu: it anchors correctly inside sheets and scroll views, where an overlay can't.+ Menu {+ ForEach(items()) { item in+ if item.divider { Divider() }+ Self.row(item)+ }+ } label: { label }+ .buttonStyle(.plain)+ .menuIndicator(.hidden)+ #elseButton { open.toggle() } label: { label }.buttonStyle(.plain).codyncMenu(isPresented: $open, items: items)+ #endif+ }++ #if os(iOS)+ @ViewBuilder private static func row(_ item: MenuItem) -> some View {+ let role: ButtonRole? = item.destructive ? .destructive : nil+ if let selected = item.selected {+ Toggle(isOn: Binding(get: { selected }, set: { _ in item.action() })) {+ if let icon = item.icon { SwiftUI.Label(item.title, systemImage: icon) } else { Text(item.title) }+ }+ } else if let icon = item.icon {+ Button(role: role, action: item.action) { SwiftUI.Label(item.title, systemImage: icon) }+ } else {+ Button(item.title, role: role, action: item.action)+ }}+ #endif}/// Picks one value: shows the current choice in a pill with a chevron, opens a Codync menu.@@ -384,11 +466,13 @@ public struct ChoicePicker<ID: Hashable>: View {@Binding var selection: IDlet options: [(id: ID, label: String)]var fill: Color+ var fitsAvailableWidth: Bool- public init(selection: Binding<ID>, options: [(id: ID, label: String)], fill: Color = Palette.bubbleUser) {+ public init(selection: Binding<ID>, options: [(id: ID, label: String)], fill: Color = Palette.bubbleUser, fitsAvailableWidth: Bool = false) {_selection = selectionself.options = optionsself.fill = fill+ self.fitsAvailableWidth = fitsAvailableWidth}public var body: some View {@@ -403,7 +487,8 @@ public struct ChoicePicker<ID: Hashable>: View {.foregroundStyle(Palette.text).pill(fill: fill)}- .fixedSize()+ .fixedSize(horizontal: !fitsAvailableWidth, vertical: true)+ .help(options.first { $0.id == selection }?.label ?? "Choose")}}@@ -644,9 +729,12 @@ public struct DialogAction: Identifiable {public extension View {/// A centered card over a dimmed screen with the actions and Cancel:/// the replacement for `confirmationDialog` and `alert`.+ /// Set `inPlace` only at the navigation root to keep underlying glass unchanged.func codyncDialog(_ title: String, isPresented: Binding<Bool>, message: String? = nil,- cancel: String? = "Cancel", actions: @escaping () -> [DialogAction]) -> some View {- modifier(CodyncDialog(title: title, message: message, cancel: cancel, isPresented: isPresented, actions: actions))+ cancel: String? = "Cancel", inPlace: Bool = false,+ actions: @escaping () -> [DialogAction]) -> some View {+ modifier(CodyncDialog(title: title, message: message, cancel: cancel, inPlace: inPlace,+ isPresented: isPresented, actions: actions))}}@@ -654,12 +742,36 @@ private struct CodyncDialog: ViewModifier {let title: Stringlet message: String?let cancel: String?+ /// Use only above the navigation container so the scrim also covers its toolbar.+ let inPlace: Bool@Binding var isPresented: Boollet actions: () -> [DialogAction]+ @Environment(\.accessibilityReduceMotion) private var reduceMotionfunc body(content: Content) -> some View {- content.codyncOverlay(isPresented: $isPresented) { close in- DialogCard(title: title, message: message, cancel: cancel, actions: actions(), dismiss: close)+ if inPlace {+ content+ .allowsHitTesting(!isPresented)+ .accessibilityHidden(isPresented)+ .overlay {+ if isPresented {+ DialogCard(title: title, message: message, cancel: cancel, actions: actions()) {+ isPresented = false+ }+ .transition(.opacity)+ #if os(iOS)+ .onAppear {+ UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder),+ to: nil, from: nil, for: nil)+ }+ #endif+ }+ }+ .animation(Motion.reduced(Motion.fade, reduceMotion), value: isPresented)+ } else {+ content.codyncOverlay(isPresented: $isPresented) { close in+ DialogCard(title: title, message: message, cancel: cancel, actions: actions(), dismiss: close)+ }}}}diff --git a/kit/Sources/CodyncUI/Marketplace/ComposioViews.swift b/kit/Sources/CodyncUI/Marketplace/ComposioViews.swiftindex ef26e480..9f3f53e2 100644--- a/kit/Sources/CodyncUI/Marketplace/ComposioViews.swift+++ b/kit/Sources/CodyncUI/Marketplace/ComposioViews.swift@@ -12,7 +12,8 @@ struct ComposioSection: View {let searchToken: Int@Environment(BotStore.self) private var model@State private var status: ComposioStatus?- @State private var apps: [ComposioApp] = []+ @State private var apps = MarketplacePage<ComposioApp>()+ @State private var loadRequest = UUID()@State private var loading = true@State private var error: String?@State private var settingUp = false@@ -42,7 +43,7 @@ struct ComposioSection: View {.foregroundStyle(Palette.secondary)} else {ItemGrid {- ForEach(apps) { app in+ ForEach(apps.visible) { app inMarketRow(title: app.name,subtitle: app.description ?? app.slug,@@ -56,6 +57,13 @@ struct ComposioSection: View {}}}+ if !loading, apps.hasHiddenItems, status?.configured == true {+ Button("Load more apps") {+ withAnimation(Motion.fade) { apps.revealMore() }+ }+ .buttonStyle(SecondaryButtonStyle())+ .frame(maxWidth: .infinity)+ }if let error {Text(error).font(.footnote).foregroundStyle(Palette.danger)}@@ -82,17 +90,24 @@ struct ComposioSection: View {private func load() async {guard let client = model.client else { return }+ let request = UUID()+ loadRequest = request+ let search = queryloading = true- defer { loading = false }+ defer { if loadRequest == request { loading = false } }do {let s = try await client.composioStatus()+ let page = s.configured ? try await client.composioApps(search: search) : []+ guard !Task.isCancelled, loadRequest == request else { return }status = s- apps = s.configured ? try await client.composioApps(search: query) : []+ apps.replace(with: page)error = nil} catch {+ guard !Task.isCancelled, loadRequest == request else { return }self.error = error.localizedDescription}}+}/// An app's logo from Composio, a letter tile until it loads.@@ -184,6 +199,7 @@ struct ComposioKeySheet: View {/// or a form for apps that use a key.struct ComposioConnectSheet: View {let app: ComposioApp+ var requestId: String? = nillet done: () -> Void@Environment(BotStore.self) private var model@Environment(\.dismissModal) private var dismiss@@ -275,7 +291,7 @@ struct ComposioConnectSheet: View {}.textFieldStyle(.plain).task { await start() }- .onDisappear { if connected { done() } }+ .onDisappear { values.removeAll(); if connected { done() } }}private func binding(_ name: String) -> Binding<String> {@@ -305,6 +321,11 @@ struct ComposioConnectSheet: View {guard let state = try? await client.composioConnection(id) else { continue }switch state.status {case "active":+ if let requestId {+ do { try await client.finishConnectionRequest(requestId, connectorId: "composio-\(app.slug)") }+ catch { self.error = error.localizedDescription; return }+ }+ values.removeAll()connected = truereturncase "failed", "expired":@@ -325,6 +346,8 @@ struct ComposioConnectSheet: View {do {let state = try await client.composioConnect(app.slug, mode: mode, fields: values.filter { !$0.value.isEmpty })if state.status == "active" {+ if let requestId { try await client.finishConnectionRequest(requestId, connectorId: "composio-\(app.slug)") }+ values.removeAll()connected = true} else {error = "\(app.name) says the connection is \(state.status)."diff --git a/kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift b/kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swiftnew file mode 100644index 00000000..43f41782--- /dev/null+++ b/kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift@@ -0,0 +1,197 @@+import CodyncKit+import SwiftUI++/// Credentials go through the setup API; only the request's state is a chat entry.+struct ConnectionRequestCard: View {+ let entry: Entry+ let request: ConnectionRequest+ @Environment(BotStore.self) private var model+ @Environment(\.webAuthenticationSession) private var webAuthenticationSession+ @Environment(\.openURL) private var openURL+ @State private var app: ComposioApp?+ @State private var item: MarketConnector?+ @State private var value = ""+ @State private var busy = false+ @State private var error: String?++ var body: some View {+ VStack(alignment: .leading, spacing: 12) {+ Label(request.title, systemImage: "lock.shield")+ .font(.headline)+ if let text = entry.data.text { Text(text).foregroundStyle(Palette.secondary) }+ if request.status == "pending" {+ if request.kind == "secret" {+ Text("\(request.field ?? "Credential") · \(request.location ?? "")")+ .font(.caption).foregroundStyle(Palette.secondary)+ SecureField("Credential or op:// reference", text: $value)+ .plainTextInput()+ Text("Saved securely on this computer. Never added to the conversation.")+ .font(.caption).foregroundStyle(Palette.secondary)+ }+ HStack {+ Button(request.kind == "secret" ? "Save and connect" : "Connect") { connect() }+ .buttonStyle(PrimaryButtonStyle())+ .disabled(busy || (request.kind == "secret" && value.isEmpty))+ Button("Cancel") { cancel() }.buttonStyle(SecondaryButtonStyle()).disabled(busy)+ if busy { Spinner() }+ }+ } else {+ Text(request.status == "ready" ? "Connected" : "Cancelled").foregroundStyle(Palette.secondary)+ }+ if let error { Text(error).font(.footnote).foregroundStyle(Palette.danger) }+ }+ .padding(16)+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 18))+ .textFieldStyle(.plain)+ .codyncSheet(item: $item) { item in+ InstallConnectorSheet(item: item, requestId: entry.id) { self.item = nil }+ }+ .codyncSheet(item: $app) { app in+ ComposioConnectSheet(app: app, requestId: entry.id) { self.app = nil }+ }+ .onDisappear { value = "" }+ }++ private func connect() {+ guard let client = model.client else { return }+ busy = true+ error = nil+ Task {+ defer { busy = false }+ do {+ if request.kind == "app", let toolkit = request.toolkit {+ withAnimation(Motion.layout) { app = ComposioApp(slug: toolkit, name: request.title) }+ } else if request.kind == "secret" {+ try await client.finishConnectionRequest(entry.id, value: value)+ value = ""+ } else if let id = request.connectorId {+ let connectors = try await client.connectors()+ if connectors.first(where: { $0.id == id })?.needsSignIn == true {+ try await ConnectorSignInFlow(model: model, webAuthenticationSession: webAuthenticationSession, openURL: openURL).signIn(id)+ }+ try await client.finishConnectionRequest(entry.id, connectorId: id)+ } else if let name = request.registryName {+ let loaded = try await client.connectorInfo(name)+ withAnimation(Motion.layout) { item = loaded }+ }+ } catch { self.error = error.localizedDescription }+ }+ }++ private func cancel() {+ guard let client = model.client else { return }+ busy = true+ Task {+ defer { busy = false }+ do { try await client.finishConnectionRequest(entry.id, cancel: true); value = "" }+ catch { self.error = error.localizedDescription }+ }+ }+}++struct CredentialsView: View {+ @Environment(BotStore.self) private var model+ @State private var selected: InstalledConnector?+ @State private var token = ""+ @State private var status: CredentialStatus?+ @State private var busy = false+ @State private var error: String?++ var body: some View {+ VStack(spacing: 0) {+ ModalHeader("Credentials") {}+ CardForm {+ CardSection("Storage") {+ Text(status?.provider ?? "System credential store")+ Text("Credentials are encrypted on the connected computer. Linux uses Secret Service; macOS uses Keychain.")+ .foregroundStyle(Palette.secondary)+ }+ CardSection("Saved connections") {+ ForEach(model.installedConnectors.filter { !$0.keys.isEmpty }) { connector in+ Button { withAnimation(Motion.layout) { selected = connector } } label: {+ HStack { Text(connector.name); Spacer(); Image(systemName: "chevron.right") }+ }+ .buttonStyle(.plain)+ }+ Text("Values stay hidden. Select a connection to replace its credentials.")+ .font(.caption).foregroundStyle(Palette.secondary)+ }+ CardSection("1Password", footer: "Use a service account with read access only to a dedicated shared vault. The 1Password CLI must be installed on the computer.") {+ Text(status?.onePasswordConnected == true ? "Connected" : "Connect a shared vault")+ SecureField("Service account token", text: $token).plainTextInput()+ Button("Connect") { save(token) }.buttonStyle(PrimaryButtonStyle()).disabled(busy || token.isEmpty)+ if status?.onePasswordConnected == true {+ Button("Disconnect") { save("") }.buttonStyle(SecondaryButtonStyle()).disabled(busy)+ }+ Text("Use op://vault/item/field in a connector's credential field. Codync retrieves the value when the connector runs.")+ .font(.footnote).foregroundStyle(Palette.secondary)+ }+ if busy { Spinner() }+ if let error { Text(error).foregroundStyle(Palette.danger) }+ }+ }+ .background(Palette.background)+ .textFieldStyle(.plain)+ .codyncSheet(item: $selected) { ConnectorCredentialEditor(connector: $0) }+ .task {+ await model.refreshPlugins()+ do { status = try await model.client?.credentialStatus() }+ catch { self.error = error.localizedDescription }+ }+ .onDisappear { token = "" }+ }++ private func save(_ value: String) {+ guard let client = model.client else { return }+ busy = true+ error = nil+ Task {+ defer { busy = false }+ do { status = try await client.setOnePasswordToken(value); token = "" }+ catch { self.error = error.localizedDescription }+ }+ }+}+++private struct ConnectorCredentialEditor: View {+ let connector: InstalledConnector+ @Environment(BotStore.self) private var model+ @Environment(\.dismissModal) private var dismiss+ @State private var fields: [String: String] = [:]+ @State private var saving = false+ @State private var error: String?++ var body: some View {+ VStack(spacing: 0) {+ ModalHeader(connector.name) {+ if saving { Spinner() }+ else { IconButton("Save credentials", systemImage: "checkmark") { save() }.disabled(fields.values.allSatisfy(\.isEmpty)) }+ }+ CardForm {+ CardSection(footer: "Enter only the values you want to replace. You can use an op:// reference.") {+ ForEach(connector.keys, id: \.self) { key in+ SecureField(key, text: Binding(get: { fields[key] ?? "" }, set: { fields[key] = $0 })).plainTextInput()+ }+ }+ if let error { Text(error).foregroundStyle(Palette.danger) }+ }+ }+ .background(Palette.background)+ .textFieldStyle(.plain)+ .onDisappear { fields.removeAll() }+ }+ private func save() {+ guard let client = model.client else { return }+ saving = true+ error = nil+ Task {+ defer { saving = false }+ do {+ try await client.updateConnectorCredentials(connector.id, fields: fields.filter { !$0.value.isEmpty })+ fields.removeAll()+ dismiss()+ } catch { self.error = error.localizedDescription }+ }+ }+}diff --git a/kit/Sources/CodyncUI/Marketplace/MarketplacePage.swift b/kit/Sources/CodyncUI/Marketplace/MarketplacePage.swiftnew file mode 100644index 00000000..8f688a99--- /dev/null+++ b/kit/Sources/CodyncUI/Marketplace/MarketplacePage.swift@@ -0,0 +1,24 @@+/// Keep fetched catalog metadata in memory, but create rows only as the user requests them.+struct MarketplacePage<Item: Identifiable> {+ private(set) var items: [Item] = []+ private(set) var visibleCount = 12++ var visible: ArraySlice<Item> { items.prefix(visibleCount) }+ var hasHiddenItems: Bool { items.count > visibleCount }+ var isEmpty: Bool { items.isEmpty }++ mutating func replace(with items: [Item]) {+ self.items = []+ visibleCount = 12+ append(items)+ }++ mutating func append(_ page: [Item]) {+ var known = Set(items.map(\.id))+ items += page.filter { known.insert($0.id).inserted }+ }++ mutating func revealMore() {+ visibleCount = min(items.count, visibleCount + 12)+ }+}diff --git a/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift b/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swiftindex 38121dc6..ceee396d 100644--- a/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift+++ b/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift@@ -6,14 +6,19 @@ import UIKitimport AppKit#endif/// The Marketplace (Grok Bot's layout): one page of agents, connectors and-/// skills for the bots on the paired computer. Installing happens on that+/// skills for the bots on one computer (the store in the environment). Installing happens on that/// computer; each bot turns connectors and skills on in its settings.public struct MarketplaceView: View {@Environment(BotStore.self) private var model@State private var search = ""/// Bumped on each submitted search, so every section searches again.@State private var searchToken = 0- @State private var connectors: [MarketConnector] = []+ @State private var connectors = MarketplacePage<MarketConnector>()+ @State private var connectorRequest = UUID()+ @State private var connectorQuery = ""+ /// The registry page after the ones shown; nil at the end.+ @State private var connectorCursor: String?+ @State private var loadingMore = false@State private var skills: [MarketSkill] = []@State private var loadingConnectors = true@State private var loadingSkills = true@@ -24,9 +29,18 @@ public struct MarketplaceView: View {@State private var writingSkill = false@State private var agent: Backend?@State private var showInstalled = false+ @State private var showCredentials = false@Environment(\.dismissModal) private var dismiss- public init() {}+ private let computers: [(id: ComputerID, label: String)]+ private let computer: Binding<ComputerID>?++ /// Each computer has its own marketplace; with `computer` set and more than one computer,+ /// the header switches between them (the caller swaps the `BotStore`).+ public init(computers: [(id: ComputerID, label: String)] = [], computer: Binding<ComputerID>? = nil) {+ self.computers = computers+ self.computer = computer+ }private var query: String { search.trimmingCharacters(in: .whitespaces) }@@ -65,6 +79,7 @@ public struct MarketplaceView: View {.codyncSheet(item: $installing) { item inInstallConnectorSheet(item: item) { Task { await loadConnectors() } }}+ .codyncSheet(isPresented: $showCredentials) { CredentialsView() }.codyncSheet(isPresented: $addingConnector) { CustomConnectorSheet() }.codyncSheet(isPresented: $writingSkill) { NewSkillSheet() }.codyncSheet(item: $agent) { b in AgentSheet(initial: b) }@@ -101,7 +116,7 @@ public struct MarketplaceView: View {.foregroundStyle(Palette.secondary)} else {ItemGrid {- ForEach(connectors) { c in+ ForEach(connectors.visible) { c inMarketRow(title: c.title, subtitle: c.description ?? c.name, added: c.installed) {ServiceLogo(website: c.website, name: c.title, registryName: c.name)} add: {@@ -109,6 +124,12 @@ public struct MarketplaceView: View {}}}+ if connectors.hasHiddenItems || connectorCursor != nil {+ Button(loadingMore ? "Loading…" : "Load more connectors") { Task { await loadMoreConnectors() } }+ .buttonStyle(SecondaryButtonStyle())+ .disabled(loadingMore)+ .frame(maxWidth: .infinity)+ }}}ComposioSection(query: query, searchToken: searchToken)@@ -132,6 +153,10 @@ public struct MarketplaceView: View {}}}+ Button { withAnimation(Motion.layout) { showCredentials = true } } label: {+ Label("Credentials", systemImage: "lock.shield")+ }+ .buttonStyle(SecondaryButtonStyle())MarketSection(title: "Make your own") {ItemGrid {MarketRow(title: "Custom connector", subtitle: "Any MCP server: a command or a URL", added: false, addLabel: "New") {@@ -169,12 +194,39 @@ public struct MarketplaceView: View {private var header: some View {HStack(alignment: .center) {- Text("Marketplace")- .font(.title2.weight(.semibold))- .foregroundStyle(Palette.text)+ // Everything here lives on one computer; say which.+ HStack(spacing: 10) {+ ComputerBadge(model.computer, size: 32)+ VStack(alignment: .leading, spacing: 0) {+ Text("Marketplace")+ .font(.title2.weight(.semibold))+ .foregroundStyle(Palette.text)+ if let computer, computers.count > 1 {+ DropdownMenu {+ computers.map { option in+ MenuItem(option.label, selected: option.id == computer.wrappedValue) { computer.wrappedValue = option.id }+ }+ } label: {+ HStack(spacing: 4) {+ Text(model.hostName)+ Image(systemName: "chevron.down").font(.caption2.weight(.semibold))+ }+ .font(.subheadline)+ .foregroundStyle(Palette.secondary)+ .contentShape(Rectangle())+ }+ .accessibilityLabel("Computer: \(model.hostName)")+ .help("Switch computer")+ } else {+ Text(model.hostName)+ .font(.subheadline)+ .foregroundStyle(Palette.secondary)+ }+ }.lineLimit(1).minimumScaleFactor(0.7)- .layoutPriority(1)+ }+ .layoutPriority(1)Spacer()if installedCount > 0 {Button { withAnimation(Motion.layout) { showInstalled = true } } label: {@@ -220,15 +272,51 @@ public struct MarketplaceView: View {}private func loadConnectors() async {+ let request = UUID()+ connectorRequest = request+ connectorQuery = queryloadingConnectors = true+ loadingMore = false+ defer { if connectorRequest == request { loadingConnectors = false } }do {- connectors = try await model.marketConnectors(search: query)+ let page = try await model.marketConnectors(search: connectorQuery)+ guard !Task.isCancelled, connectorRequest == request else { return }+ connectors.replace(with: page.items)+ connectorCursor = page.next+ error = nil+ } catch {+ guard !Task.isCancelled, connectorRequest == request else { return }+ connectors.replace(with: [])+ connectorCursor = nil+ self.error = error.localizedDescription+ }+ }++ private func loadMoreConnectors() async {+ guard !loadingMore, !loadingConnectors else { return }+ if connectors.hasHiddenItems {+ withAnimation(Motion.fade) { connectors.revealMore() }+ return+ }+ guard let cursor = connectorCursor else { return }+ let request = connectorRequest+ loadingMore = true+ defer { if connectorRequest == request { loadingMore = false } }+ do {+ let page = try await model.marketConnectors(search: connectorQuery, cursor: cursor)+ guard !Task.isCancelled, connectorRequest == request else { return }+ withAnimation(Motion.fade) {+ connectors.append(page.items)+ connectors.revealMore()+ }+ connectorCursor = page.next+ error = nil} catch {- connectors = []+ guard !Task.isCancelled, connectorRequest == request else { return }self.error = error.localizedDescription}- loadingConnectors = false}+}// MARK: - Installed@@ -934,8 +1022,9 @@ struct TileIcon: View {}}-private struct InstallConnectorSheet: View {+struct InstallConnectorSheet: View {let item: MarketConnector+ var requestId: String? = nillet done: () -> Void@Environment(BotStore.self) private var model@Environment(\.dismissModal) private var dismiss@@ -943,6 +1032,8 @@ private struct InstallConnectorSheet: View {@Environment(\.openURL) private var openURL@State private var optionId = ""@State private var values: [String: String] = [:]+ @State private var installed: InstalledConnector?+ @State private var started = false@State private var saving = false@State private var error: String?@@ -957,12 +1048,18 @@ private struct InstallConnectorSheet: View {Spinner()} else {IconButton("Add", systemImage: "plus") { install() }- .disabled(option?.inputs.contains { $0.required && (values[$0.name] ?? "").isEmpty } ?? true)+ .disabled(installed == nil && (option?.inputs.contains { $0.required && (values[$0.name] ?? $0.default ?? "").isEmpty } ?? true))}}form}.background(Palette.background)+ .task {+ guard !started else { return }+ started = true+ if item.options.count == 1 && item.options[0].inputs.isEmpty { install() }+ }+ .onDisappear { values.removeAll() }}private var form: some View {@@ -1027,10 +1124,23 @@ private struct InstallConnectorSheet: View {error = nilTask {do {- let c = try await model.installConnector(item, option: option.id, inputs: values)+ guard let client = model.client else { return }+ let c: InstalledConnector+ if let installed { c = try await client.connectors().first(where: { $0.id == installed.id }) ?? installed }+ else {+ c = try await model.installConnector(item, option: option.id, inputs: values)+ installed = c+ values.removeAll()+ }if c.needsSignIn {try await ConnectorSignInFlow(model: model, webAuthenticationSession: webAuthenticationSession, openURL: openURL).signIn(c.id)}+ if let requestId {+ try await client.finishConnectionRequest(requestId, connectorId: c.id)+ } else {+ try await client.verifyConnector(c.id)+ }+ await model.refreshPlugins()done()dismiss()} catch {@@ -1042,17 +1152,26 @@ private struct InstallConnectorSheet: View {}private struct CustomConnectorSheet: View {+ private enum Mode: Hashable { case command, url, config }+@Environment(BotStore.self) private var model@Environment(\.dismissModal) private var dismiss@Environment(\.webAuthenticationSession) private var webAuthenticationSession@Environment(\.openURL) private var openURL@State private var name = ""- @State private var remote = false+ @State private var mode = Mode.command@State private var target = ""@State private var envText = ""+ @State private var config = ""@State private var saving = false@State private var error: String?+ private var ready: Bool {+ mode == .config+ ? !config.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ : !name.trimmingCharacters(in: .whitespaces).isEmpty && !target.trimmingCharacters(in: .whitespaces).isEmpty+ }+var body: some View {VStack(spacing: 0) {ModalHeader("Custom connector") {@@ -1060,7 +1179,7 @@ private struct CustomConnectorSheet: View {Spinner()} else {IconButton("Add", systemImage: "plus") { save() }- .disabled(name.trimmingCharacters(in: .whitespaces).isEmpty || target.trimmingCharacters(in: .whitespaces).isEmpty)+ .disabled(!ready)}}form@@ -1068,23 +1187,38 @@ private struct CustomConnectorSheet: View {.background(Palette.background)}+ private var footer: String {+ switch mode {+ case .command: "Runs on \(model.hostName) in the bot's project folder. Quotes work like in a shell."+ case .url: "A remote MCP server, streamable HTTP or SSE."+ case .config: "Paste the MCP config from a README or another app (Claude, Cursor, VS Code). Every server in it is added. Saved on \(model.hostName) only."+ }+ }+private var form: some View {CardForm {- CardSection(footer: remote ? "A remote MCP server (streamable HTTP)." : "Runs on \(model.hostName) in the bot's project folder.") {- TextField("Name", text: $name)- SegmentedChoice(selection: $remote, options: [(id: false, label: "Command"), (id: true, label: "URL")])- TextField(remote ? "https://example.com/mcp" : "npx -y @scope/server", text: $target)- .font(.callout.monospaced())- .plainTextInput()+ CardSection(footer: footer) {+ SegmentedChoice(selection: $mode, options: [(id: .command, label: "Command"), (id: .url, label: "URL"), (id: .config, label: "Config")])+ if mode == .config {+ TextField("{ \"mcpServers\": { … } }", text: $config, axis: .vertical)+ .lineLimit(6...16)+ .font(.callout.monospaced())+ .plainTextInput()+ } else {+ TextField("Name", text: $name)+ TextField(mode == .url ? "https://example.com/mcp" : "npx -y @scope/server", text: $target)+ .font(.callout.monospaced())+ .plainTextInput()+ }}- if remote {+ if mode == .url {CardSection("Headers", footer: "Optional, one Name: value per line. Leave empty if the service has you sign in. Saved on \(model.hostName) only.") {TextField("Authorization: Bearer …", text: $envText, axis: .vertical).lineLimit(2...6).font(.callout.monospaced()).plainTextInput()}- } else {+ } else if mode == .command {CardSection("Environment", footer: "One KEY=value per line. Saved on \(model.hostName) only.") {TextField("API_KEY=…", text: $envText, axis: .vertical).lineLimit(2...6)@@ -1097,11 +1231,13 @@ private struct CustomConnectorSheet: View {}}.textFieldStyle(.plain)+ .animation(Motion.layout, value: mode)}private func save() {saving = trueerror = nil+ let remote = mode == .urlvar pairs: [String: String] = [:]for line in envText.split(separator: "\n") {let parts = line.split(separator: remote ? ":" : "=", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) }@@ -1109,12 +1245,15 @@ private struct CustomConnectorSheet: View {}Task {do {- let c = try await model.addConnector(- name: name, command: remote ? nil : target, url: remote ? target : nil,- env: remote ? [:] : pairs, headers: remote ? pairs : [:]- )- if c.needsSignIn {- try await ConnectorSignInFlow(model: model, webAuthenticationSession: webAuthenticationSession, openURL: openURL).signIn(c.id)+ let added = mode == .config+ ? try await model.importConnectors(config: config)+ : [try await model.addConnector(+ name: name, command: remote ? nil : target, url: remote ? target : nil,+ env: remote ? [:] : pairs, headers: remote ? pairs : [:]+ )]+ let signIn = ConnectorSignInFlow(model: model, webAuthenticationSession: webAuthenticationSession, openURL: openURL)+ for c in added where c.needsSignIn {+ try await signIn.signIn(c.id)}dismiss()} catch {diff --git a/kit/Sources/CodyncUI/Routines/RoutineCalendarFields.swift b/kit/Sources/CodyncUI/Routines/RoutineCalendarFields.swiftnew file mode 100644index 00000000..48bea298--- /dev/null+++ b/kit/Sources/CodyncUI/Routines/RoutineCalendarFields.swift@@ -0,0 +1,161 @@+import CodyncKit+import SwiftUI++/// Calendar controls compile to the same cron trigger the host executes.+struct RoutineCalendarFields: View {+ @Binding var schedule: RoutineScheduleDraft+ let preview: RoutineSchedulePreview?+ let previewError: String?+ let selectFrequency: (String) -> Void+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var showExpression = false++ private let frequencies = [("minutes", "Every few minutes"), ("hourly", "Hourly"),+ ("daily", "Daily"), ("weekdays", "Weekdays"), ("weekly", "Weekly"),+ ("days", "Selected days"), ("monthly", "Monthly"), ("custom", "Custom cron")]+ private let days = [(0, "Sun"), (1, "Mon"), (2, "Tue"), (3, "Wed"),+ (4, "Thu"), (5, "Fri"), (6, "Sat")]++ var body: some View {+ VStack(alignment: .leading, spacing: 18) {+ Field("Frequency") {+ ChoicePicker(selection: Binding(+ get: { schedule.calendarStyle },+ set: selectFrequency+ ), options: frequencies, fitsAvailableWidth: true)+ }+ if schedule.calendarStyle == "custom" {+ Field("Cron expression") {+ TextField("0 9 * * 1-5", text: $schedule.expression)+ .textFieldStyle(.plain).font(.body.monospaced())+ .padding(12).background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 12))+ }+ Text("Minute · Hour · Day of month · Month · Weekday")+ .font(.caption).foregroundStyle(Palette.secondary)+ Text("Example: 0 9 * * 1-5 runs at 09:00, Monday through Friday.")+ .font(.caption).foregroundStyle(Palette.secondary)+ } else if schedule.calendarStyle == "minutes" {+ Field("Repeat every") {+ ChoicePicker(selection: $schedule.minuteStep,+ options: [1, 5, 10, 15, 20, 30].map { ($0, "\($0) min") })+ }+ } else {+ if schedule.calendarStyle == "weekly" || schedule.calendarStyle == "days" {+ weekdayChoices+ }+ if schedule.calendarStyle == "monthly" {+ Field("Day of month") {+ ChoicePicker(selection: $schedule.monthDay, options: (1...31).map { ($0, "Day \($0)") })+ }+ if let warning = preview?.warning {+ Text(warning)+ .font(.caption).foregroundStyle(Palette.secondary)+ }+ }+ clockChoices+ }+ Field("Time zone") {+ TextField("Asia/Taipei", text: $schedule.zone)+ .textFieldStyle(.plain).padding(12)+ .background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 12))+ Button("Use this device’s time zone") { schedule.zone = TimeZone.current.identifier }+ .buttonStyle(.plain).font(.caption).foregroundStyle(Palette.secondary)+ }+ summary+ }+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: schedule.calendarStyle)+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: schedule.monthDay)+ }++ private var weekdayChoices: some View {+ Field(schedule.calendarStyle == "weekly" ? "Run on" : "Choose days") {+ LazyVGrid(columns: [GridItem(.adaptive(minimum: 56), spacing: 6)], spacing: 6) {+ ForEach(days, id: \.0) { day in+ let selected = schedule.calendarStyle == "weekly" ? schedule.weekday == day.0 : schedule.selectedDays.contains(day.0)+ Button {+ withAnimation(Motion.reduced(Motion.morph, reduceMotion)) {+ if schedule.calendarStyle == "weekly" { schedule.weekday = day.0 }+ else if selected { schedule.selectedDays.remove(day.0) }+ else { schedule.selectedDays.insert(day.0) }+ }+ } label: {+ Text(day.1).font(.callout.weight(selected ? .semibold : .regular))+ .frame(maxWidth: .infinity, minHeight: 44)+ .background(selected ? Palette.bubbleUser : Palette.bubbleAgent,+ in: RoundedRectangle(cornerRadius: 10))+ }+ .buttonStyle(.plain)+ .accessibilityAddTraits(selected ? .isSelected : [])+ .accessibilityLabel(Calendar.current.weekdaySymbols[day.0])+ }+ }+ }+ }++ private var clockChoices: some View {+ VStack(alignment: .leading, spacing: 12) {+ Text(schedule.calendarStyle == "hourly" ? "At minute" : "Time · 24-hour clock")+ .font(.caption.weight(.medium)).foregroundStyle(Palette.secondary)+ HStack(alignment: .firstTextBaseline, spacing: 12) {+ if schedule.calendarStyle != "hourly" {+ ChoicePicker(selection: $schedule.hour, options: (0...23).map { ($0, String(format: "%02d", $0)) })+ .accessibilityLabel("Hour")+ .accessibilityValue(String(format: "%02d", schedule.hour))+ Text(":").font(.title2).foregroundStyle(Palette.secondary)+ }+ ChoicePicker(selection: $schedule.minute, options: (0...59).map { ($0, String(format: "%02d", $0)) })+ .accessibilityLabel("Minute")+ .accessibilityValue(String(format: "%02d", schedule.minute))+ Spacer(minLength: 0)+ Image(systemName: "clock").foregroundStyle(Palette.secondary).accessibilityHidden(true)+ }+ .monospacedDigit()+ if schedule.calendarStyle != "hourly" {+ HStack(spacing: 8) {+ ForEach([9, 12, 18], id: \.self) { hour in+ Button(String(format: "%02d:00", hour)) {+ schedule.hour = hour+ schedule.minute = 0+ }+ .buttonStyle(.plain).font(.caption.monospacedDigit())+ .padding(.horizontal, 12).frame(minHeight: 44)+ .background(Palette.bubbleUser, in: Capsule())+ .accessibilityLabel("Set time to \(hour):00")+ }+ }+ }+ }+ .padding(16).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 14))+ }++ private var summary: some View {+ VStack(alignment: .leading, spacing: 8) {+ if let error = previewError {+ Label(error, systemImage: "exclamationmark.circle")+ .font(.caption).foregroundStyle(Palette.danger)+ } else {+ Label(preview?.summary ?? "Checking schedule…", systemImage: "calendar.badge.clock")+ .font(.callout.weight(.medium))+ if let next = preview?.nextRunAt {+ Text("Next: \(Date(timeIntervalSince1970: Double(next) / 1000).formatted(date: .abbreviated, time: .shortened)) · device time")+ .font(.caption).foregroundStyle(Palette.secondary)+ }+ if schedule.calendarStyle != "custom" {+ Button {+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { showExpression.toggle() }+ } label: {+ Label("Cron expression", systemImage: showExpression ? "chevron.up" : "chevron.down")+ .font(.caption)+ }+ .buttonStyle(.plain).foregroundStyle(Palette.secondary)+ .accessibilityValue(showExpression ? "Expanded" : "Collapsed")+ if showExpression, let expression = preview?.triggers.first?.expression {+ Text(expression).font(.callout.monospaced()).textSelection(.enabled)+ }+ }+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }++}diff --git a/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift b/kit/Sources/CodyncUI/Routines/RoutineEditorView.swiftindex 7cc76485..d42bbdc5 100644--- a/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift+++ b/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift@@ -14,17 +14,25 @@ struct RoutineEditorView: View {@State private var busy = false@State private var error: String?@State private var advanced = false+ @State private var loaded = false+ @State private var preview: RoutineSchedulePreview?+ @State private var previewError: String?+ @State private var checkedSchedule: RoutineScheduleDraft?private var options: [(String, String)] {- var values = [("interval", "Repeat at an interval"), ("cron", "Calendar schedule"),+ var values = [("cron", "Recurring schedule"),("once", "Run once"), ("webhook", "Webhook")]if routine != nil { values.insert(("keep", "Keep existing triggers"), at: 0) }+ if schedule.original.contains(where: { $0.type == "interval" }) {+ values.append(("interval", "Existing interval"))+ }return values}private var canSave: Bool {!name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty &&- !instruction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !model.isOffline && !busy+ !instruction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !model.isOffline && !busy &&+ loaded && checkedSchedule == schedule && previewError == nil}var body: some View {@@ -46,7 +54,8 @@ struct RoutineEditorView: View {LazyVGrid(columns: [GridItem(.adaptive(minimum: 180), spacing: 8)], spacing: 8) {ForEach(options, id: \.0) { option in triggerChoice(option) }}- triggerFields+ if loaded { triggerFields }+ else { Label("Loading schedule…", systemImage: "clock").foregroundStyle(Palette.secondary) }}VStack(alignment: .leading, spacing: 12) {Button {@@ -72,19 +81,69 @@ struct RoutineEditorView: View {.padding(20).frame(maxWidth: .infinity, alignment: .leading)}- .disabled(busy)+ .disabled(busy || !loaded)footer}.font(.system(size: InterfaceMetrics.value(mac: 13, mobile: 16))).foregroundStyle(Palette.text).background(Palette.background)- .onAppear {+ .task {if let routine {name = routine.nameinstruction = routine.instructiontimeout = String(routine.timeoutSeconds ?? 3600)- schedule = RoutineScheduleDraft(triggers: routine.triggers)}+ await loadSchedule()+ }+ .task(id: schedule) {+ guard loaded else { return }+ do { try await Task.sleep(for: .milliseconds(300)) }+ catch { return }+ await checkSchedule()+ }+ }++ private func checkSchedule() async {+ let requested = schedule+ preview = nil+ previewError = nil+ checkedSchedule = nil+ do {+ guard let client = model.client else { throw URLError(.notConnectedToInternet) }+ let result = try await client.routineSchedule(draft: requested)+ try Task.checkCancellation()+ guard schedule == requested else { return }+ preview = result+ checkedSchedule = requested+ } catch {+ guard !Task.isCancelled, schedule == requested else { return }+ previewError = error.localizedDescription+ }+ }++ private func loadSchedule() async {+ guard let client = model.client else { error = "Connect to this computer to load the schedule."; return }+ do {+ let result = try await client.routineSchedule(triggers: routine?.triggers ?? [], timeZone: TimeZone.current.identifier)+ schedule = result.draft+ preview = result+ checkedSchedule = result.draft+ loaded = true+ error = nil+ } catch { self.error = error.localizedDescription }+ }++ private func selectFrequency(_ style: String) {+ guard style == "custom" else { schedule.calendarStyle = style; return }+ let requested = schedule+ Task {+ do {+ guard let client = model.client else { return }+ let result = try await client.routineSchedule(draft: requested)+ guard requested == schedule else { return }+ schedule.expression = result.triggers.first?.expression ?? ""+ schedule.calendarStyle = style+ } catch { previewError = error.localizedDescription }}}@@ -121,27 +180,14 @@ struct RoutineEditorView: View {@ViewBuilder private var triggerFields: some View {switch schedule.kind {case "interval":+ Text("This saved interval keeps its original cadence. Choose Recurring schedule to replace it with a clock-based schedule.")+ .font(.caption).foregroundStyle(Palette.secondary)Field("Repeat every") {TextField("Interval", text: $schedule.amount).routineInput()SegmentedChoice(selection: $schedule.unit, options: [(1, "Seconds"), (60, "Minutes"), (3600, "Hours"), (86400, "Days")])}case "cron":- SegmentedChoice(selection: $schedule.calendarStyle, options: [("daily", "Daily"), ("weekdays", "Weekdays"), ("weekly", "Weekly"), ("custom", "Custom")])- if schedule.calendarStyle == "custom" {- Field("Cron expression") {- TextField("0 9 * * *", text: $schedule.expression).routineInput().font(.callout.monospaced())- }- Text("For example, 0 9 * * * runs every day at 9 AM.")- .font(.caption).foregroundStyle(Palette.secondary)- } else {- if schedule.calendarStyle == "weekly" {- SegmentedChoice(selection: $schedule.weekday, options: [(0, "Sun"), (1, "Mon"), (2, "Tue"), (3, "Wed"), (4, "Thu"), (5, "Fri"), (6, "Sat")])- }- DatePicker("At", selection: $schedule.timeOfDay, displayedComponents: .hourAndMinute)- .environment(\.timeZone, TimeZone(identifier: "GMT") ?? .current)- .padding(12).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 12))- }- Field("Time zone") { TextField("Asia/Taipei", text: $schedule.zone).routineInput() }+ RoutineCalendarFields(schedule: $schedule, preview: checkedSchedule == schedule ? preview : nil, previewError: previewError, selectFrequency: selectFrequency)case "once":DatePicker("Run at", selection: $schedule.date).padding(12).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 12))@@ -163,6 +209,16 @@ struct RoutineEditorView: View {private var footer: some View {VStack(alignment: .leading, spacing: 12) {+ if previewError != nil {+ Button("Check schedule again") { Task { await checkSchedule() } }+ .buttonStyle(.plain).disabled(model.isOffline)+ }+ if !loaded, error != nil {+ Button("Retry loading schedule") { Task { await loadSchedule() } }.buttonStyle(.plain)+ }+ if schedule.kind != "cron", let previewError {+ Text(previewError).font(.caption).foregroundStyle(Palette.danger)+ }if let error {Label(error, systemImage: "exclamationmark.circle").font(.callout).foregroundStyle(Palette.danger).textSelection(.enabled)@@ -203,20 +259,13 @@ struct RoutineEditorView: View {private func save() {guard let client = model.client, canSave else { return }- guard let timeoutValue = Int(timeout), (1...86400).contains(timeoutValue) else {- error = "Timeout must be 1 to 86400 seconds."- return- }- let triggers: [RoutineTrigger]- do { triggers = try schedule.triggers() }- catch { self.error = error.localizedDescription; return }busy = trueerror = nilTask {defer { busy = false }do {let result = try await client.saveRoutine(botId: botId, id: routine?.id, name: name,- instruction: instruction, triggers: triggers, timeoutSeconds: timeoutValue)+ instruction: instruction, schedule: schedule, timeoutSeconds: timeout)saved(result)} catch { self.error = error.localizedDescription }}diff --git a/kit/Sources/CodyncUI/Screen/ScreenCanvas.swift b/kit/Sources/CodyncUI/Screen/ScreenCanvas.swiftindex 995cca47..b9d89d9a 100644--- a/kit/Sources/CodyncUI/Screen/ScreenCanvas.swift+++ b/kit/Sources/CodyncUI/Screen/ScreenCanvas.swift@@ -216,7 +216,8 @@ final class ScreenCanvas: UIView, UIGestureRecognizerDelegate {/// Long-press then move: drag (select text, move windows).@objc private func press(_ g: UILongPressGestureRecognizer) {- guard interactive else { return }+ // A drag that began while interactive still lifts the button, or it stays held on the computer.+ guard interactive || dragging else { return }switch g.state {case .began:let p = point(for: g)diff --git a/kit/Sources/CodyncUI/Screen/ScreenView.swift b/kit/Sources/CodyncUI/Screen/ScreenView.swiftindex 6a2739f5..44454037 100644--- a/kit/Sources/CodyncUI/Screen/ScreenView.swift+++ b/kit/Sources/CodyncUI/Screen/ScreenView.swift@@ -23,6 +23,7 @@ public struct ScreenView: View {@State private var zoomed = false@State private var resetToken = 0@State private var tookOver = false+ @State private var portrait = falsepublic init(watching: String? = nil, close: (() -> Void)? = nil) {self.watching = watching@@ -39,13 +40,16 @@ public struct ScreenView: View {ScreenCanvasView(session: session, display: display, mode: mode, interactive: interactive,keyboard: keyboard, armed: $armed, zoomed: $zoomed, resetToken: resetToken).ignoresSafeArea(.container)- .ignoresSafeArea(.keyboard)+ // Portrait: the screen moves above the keyboard. Landscape: the keyboard+ // overlays it, since shrinking there would leave the screen too small.+ .ignoresSafeArea(portrait ? [] : .keyboard)status(session)} else {unavailable}}.overlay(alignment: .top) { topBar }+ .onGeometryChange(for: Bool.self) { $0.size.height > $0.size.width } action: { portrait = $0 }.safeAreaInset(edge: .bottom) {if keyboard && interactive {ModifierBar(armed: $armed) { session?.send(["type": "key", "key": $0, "modifiers": armed]); armed = [] }@@ -55,8 +59,14 @@ public struct ScreenView: View {.statusBarHidden().persistentSystemOverlays(.hidden).preferredColorScheme(.dark)- .onAppear(perform: start)- .onDisappear(perform: stop)+ .onAppear {+ OrientationLock.viewerAppeared()+ start()+ }+ .onDisappear {+ stop()+ OrientationLock.viewerDisappeared()+ }.onChange(of: screen?.available) { _, available inif available == true, session == nil { start() }}@@ -64,8 +74,8 @@ public struct ScreenView: View {// MARK: lifecycle+ /// Also runs when the screen becomes available after opening, so it leaves orientation alone.private func start() {- OrientationLock.set(.allButUpsideDown, prefer: .landscapeRight)guard session == nil, let client = model.client, let screen, screen.available, let d = display ?? screen.mainDisplay else { return }display = dlet s = ScreenSession(client: client, display: d)@@ -80,7 +90,6 @@ public struct ScreenView: View {session = nilif tookOver { model.screenTakeover(false) }tookOver = false- OrientationLock.set(.portrait, prefer: .portrait)}private func setInteractive(_ on: Bool) {@@ -100,12 +109,16 @@ public struct ScreenView: View {if let agent, !interactive {Label("\(agent.name) is using the computer", systemImage: "cursorarrow.motionlines").font(.caption.weight(.medium))+ .lineLimit(1).padding(.horizontal, 10).padding(.vertical, 6).background(.ultraThinMaterial, in: Capsule()).transition(.opacity)}Spacer()+ // Turning the phone does nothing while iOS rotation lock is on, and a phone held+ // upright stays in the landscape the viewer opened in until it is turned.+ OverlayButton("Rotate", "rotate.right") { OrientationLock.toggle() }if session != nil {if interactive {OverlayButton(keyboard ? "Hide keyboard" : "Keyboard", keyboard ? "keyboard.chevron.compact.down" : "keyboard") { animate { keyboard.toggle() } }@@ -305,23 +318,56 @@ private struct ModifierBar: View {@MainActorpublic enum OrientationLock {public static var mask: UIInterfaceOrientationMask = UIDevice.current.userInterfaceIdiom == .pad ? .all : .portrait+ /// Open viewers: a viewer replaced in place (`.id` change) may appear before the old one disappears.+ private static var viewers = 0+ /// The delayed rotate from the last open or close; a newer request or a rotate tap cancels it.+ private static var pending: Task<Void, Never>?++ /// The first open viewer allows every orientation and turns to landscape, once per presentation.+ static func viewerAppeared() {+ viewers += 1+ if viewers == 1 { set(.allButUpsideDown, prefer: .landscapeRight) }+ }- static func set(_ newMask: UIInterfaceOrientationMask, prefer: UIInterfaceOrientationMask) {+ /// The last viewer to close brings the app back to portrait.+ static func viewerDisappeared() {+ viewers = max(0, viewers - 1)+ if viewers == 0 { set(.portrait, prefer: .portrait) }+ }++ private static func set(_ newMask: UIInterfaceOrientationMask, prefer: UIInterfaceOrientationMask) {guard UIDevice.current.userInterfaceIdiom == .phone else { return }mask = newMask+ pending?.cancel()// Once the full-screen cover is up: every controller in the chain re-reads the mask, then rotate.- Task { @MainActor in- try? await Task.sleep(for: .milliseconds(100))- for case let scene as UIWindowScene in UIApplication.shared.connectedScenes {- var vc = scene.keyWindow?.rootViewController- while let current = vc {- current.setNeedsUpdateOfSupportedInterfaceOrientations()- vc = current.presentedViewController- }- try? await Task.sleep(for: .milliseconds(150))- // Best effort: turning the phone always works once the mask allows it.- scene.requestGeometryUpdate(.iOS(interfaceOrientations: prefer))- }+ pending = Task { @MainActor in+ guard (try? await Task.sleep(for: .milliseconds(100))) != nil else { return }+ let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }+ scenes.forEach(reloadMask)+ guard (try? await Task.sleep(for: .milliseconds(150))) != nil else { return }+ // Best effort: turning the phone always works once the mask allows it.+ for scene in scenes { scene.requestGeometryUpdate(.iOS(interfaceOrientations: prefer)) }+ }+ }++ /// Flip between portrait and landscape inside the screen viewer. A programmatic request+ /// works with iOS rotation lock on; the phone keeps it until it is physically turned.+ static func toggle() {+ guard UIDevice.current.userInterfaceIdiom == .phone, viewers > 0 else { return }+ pending?.cancel()+ let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }+ guard let scene = scenes.first(where: { $0.activationState == .foregroundActive }) ?? scenes.first else { return }+ reloadMask(scene)+ let bounds = scene.coordinateSpace.bounds+ scene.requestGeometryUpdate(.iOS(interfaceOrientations: bounds.width > bounds.height ? .portrait : .landscapeRight))+ }++ /// Every controller in the presentation chain re-reads `mask`.+ private static func reloadMask(_ scene: UIWindowScene) {+ var vc = scene.keyWindow?.rootViewController+ while let current = vc {+ current.setNeedsUpdateOfSupportedInterfaceOrientations()+ vc = current.presentedViewController}}}diff --git a/kit/Sources/CodyncUI/Store/AccountStore.swift b/kit/Sources/CodyncUI/Store/AccountStore.swiftindex baf20657..f63222a1 100644--- a/kit/Sources/CodyncUI/Store/AccountStore.swift+++ b/kit/Sources/CodyncUI/Store/AccountStore.swift@@ -155,6 +155,16 @@ public final class AccountStore {refreshList()}+ /// Moves a computer (and its bots in the roster) to `target`'s place; saved on this device.+ /// Attached computers (the Mac's own host, SSH tunnels) stay first.+ public func move(_ id: ComputerID, to target: ComputerID) {+ guard id != target, let from = saved.firstIndex(where: { $0.id == id }),+ let to = saved.firstIndex(where: { $0.id == target }) else { return }+ saved.insert(saved.remove(at: from), at: to)+ persist()+ refreshList()+ }+// MARK: account (§4.2 B)public func refreshCloud() async {diff --git a/kit/Sources/CodyncUI/Store/BotStore.swift b/kit/Sources/CodyncUI/Store/BotStore.swiftindex 63cc2387..663f3736 100644--- a/kit/Sources/CodyncUI/Store/BotStore.swift+++ b/kit/Sources/CodyncUI/Store/BotStore.swift@@ -41,6 +41,10 @@ public final class BotStore {public private(set) var computer: Computerpublic let route: Routepublic private(set) var connection: Connection = .connecting+ private static let dropGrace: Duration = .seconds(5)+ private static let initialConnectionGrace: Duration = .seconds(1)+ private var heldDrop: Connection?+ private var dropTimer: Task<Void, Never>?public private(set) var hostRoute: HostRoute?public private(set) var client: HostClient?public private(set) var hello: Hello?@@ -86,6 +90,8 @@ public final class BotStore {private let makeTransport: @MainActor () async throws -> any HostTransportprivate var transport: (any HostTransport)?private var retired = false+ /// Files of messages not delivered yet (by client nonce), kept for a retry.+ @ObservationIgnored private var outgoingFiles: [String: [OutgoingFile]] = [:]private var rev: Int64 = 0private var hostId: String?@@ -129,7 +135,8 @@ public final class BotStore {/// Offline, but sends can wait in the relay mailbox until the computer is back.public var canQueue: Bool {- if case .computerOffline = connection { computer.boxKey != nil && transport is any RemoteTransport } else { false }+ // Only the warning is delayed; relay delivery can queue during that grace.+ if case .computerOffline = heldDrop ?? connection { computer.boxKey != nil && transport is any RemoteTransport } else { false }}public var hostName: String { hello?.name ?? computer.name }@@ -192,6 +199,7 @@ public final class BotStore {setActive(false)retired = truesaveTask?.cancel()+ dropTimer?.cancel()onConnected = nilonBotUpdated = nilonUsageChanged = nil@@ -229,6 +237,9 @@ public final class BotStore {streamTask = nileventsTask?.cancel()eventsTask = nil+ dropTimer?.cancel()+ dropTimer = nil+ heldDrop = nilif let remote = transport as? any RemoteTransport {Task { await remote.shutdown() }}@@ -295,9 +306,37 @@ public final class BotStore {}/// Connection changes animate wherever they show (banners, headers, captions, rows).+ /// Give initial connection failures a second to recover and online drops five seconds.+ /// Relay presence can lag a reconnect, so "computer offline" gets the same grace.+ /// Authorization failures still show immediately.private func setConnection(_ new: Connection) {- guard new != connection else { return }- Motion.animate { connection = new }+ let transient = switch new {+ case .connecting, .offline, .computerOffline: true+ default: false+ }+ let recovering = new == .online && (connection != .online || heldDrop != nil)+ let initialFailure = connection == .connecting && transient && new != .connecting+ if transient && (connection == .online || initialFailure) {+ let grace = connection == .online ? Self.dropGrace : Self.initialConnectionGrace+ heldDrop = new+ if dropTimer == nil {+ dropTimer = Task { [weak self] in+ try? await Task.sleep(for: grace)+ guard !Task.isCancelled, let self, let held = self.heldDrop else { return }+ self.dropTimer = nil+ self.heldDrop = nil+ Motion.animate { self.connection = held }+ }+ }+ return+ }+ dropTimer?.cancel()+ dropTimer = nil+ heldDrop = nil+ if new != connection { Motion.animate { connection = new } }+ if recovering {+ for scope in Set(readingViews.values) { markRead(scope.botId, thread: scope.thread) }+ }}private func setHostRoute(_ new: HostRoute?) {@@ -404,6 +443,7 @@ public final class BotStore {bump(bot.rev)onBotUpdated?(bot)onRosterChanged?()+ if bot.unread > 0 { acknowledgeVisibleConversations(bot.id) }case let .botDeleted(id, r):bots[id] = nilentries[id] = nil@@ -413,6 +453,7 @@ public final class BotStore {case let .entry(e):upsert(e)bump(e.rev)+ acknowledgeVisibleConversations(e.botId, entry: e)case let .usage(u):setUsage(u)case let .screen(s):@@ -480,21 +521,26 @@ public final class BotStore {}/// `thread`: reply in the thread on that main-chat message.- public func send(_ text: String, to botId: String, thread: String? = nil) {- send(text, to: botId, thread: thread, nonce: UUID().uuidString)+ public func send(_ text: String, to botId: String, thread: String? = nil, files: [OutgoingFile] = []) {+ send(text, to: botId, thread: thread, nonce: UUID().uuidString, files: files)}- private func send(_ text: String, to botId: String, thread: String?, nonce: String) {+ private func send(_ text: String, to botId: String, thread: String?, nonce: String, files: [OutgoingFile] = []) {let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)- guard !trimmed.isEmpty, !retired else { return }+ guard !trimmed.isEmpty || !files.isEmpty, !retired else { return }+ var data = EntryData(text: trimmed, status: "sending", clientNonce: nonce)+ if !files.isEmpty {+ data.attachments = files.map { Attachment(id: $0.id.uuidString, name: $0.name, size: Int64($0.data.count)) }+ outgoingFiles[nonce] = files+ }let local = Entry(id: "local-\(nonce)", seq: Int64.max, botId: botId, threadId: thread, rev: 0, kind: "user",- turn: 0, data: EntryData(text: trimmed, status: "sending", clientNonce: nonce),- createdAt: Int64(Date.now.timeIntervalSince1970 * 1000), updatedAt: 0+ turn: 0, data: data, createdAt: Int64(Date.now.timeIntervalSince1970 * 1000), updatedAt: 0)upsert(local)storage.lastComputerId = computer.id- if canQueue, let remote = transport as? any RemoteTransport {+ // The relay mailbox holds text only: files wait for the computer.+ if canQueue, files.isEmpty, let remote = transport as? any RemoteTransport {enqueue(remote, text: trimmed, botId: botId, thread: thread, nonce: nonce)return}@@ -504,10 +550,24 @@ public final class BotStore {private func deliver(_ text: String, botId: String, thread: String?, nonce: String) {Task {do {- let e = try await require().send(botId: botId, text: text, clientNonce: nonce, threadId: thread)+ let client = try require()+ var ids: [String]?+ if let files = outgoingFiles[nonce] {+ // A fresh upload per attempt: a retry never appends to a half-sent file.+ ids = []+ for file in files {+ let id = UUID().uuidString+ try await client.upload(botId: botId, id: id, name: file.name, data: file.data)+ Self.cacheAttachment(id, file.data)+ ids?.append(id)+ }+ }+ let e = try await client.send(botId: botId, text: text, clientNonce: nonce, threadId: thread, attachments: ids)+ outgoingFiles[nonce] = nilupsert(e)if let bot = bots[botId] { onSent?(bot) }} catch {+ if outgoingFiles[nonce] != nil { lastError = "Couldn't send the files: \(error.localizedDescription)" }markLocal(nonce: nonce, botId: botId, status: "failed")}}@@ -580,14 +640,36 @@ public final class BotStore {}public func retry(_ entry: Entry) {- guard let text = entry.data.text else { return }+ let files = entry.data.clientNonce.flatMap { outgoingFiles[$0] } ?? []+ guard let text = entry.data.text, !text.isEmpty || !files.isEmpty else { return }entries[entry.botId]?.removeAll { $0.id == entry.id }// The same clientNonce: if the computer got it after all, it won't run twice (the host// skips a nonce it has). Every seal still takes a fresh ephemeral key (§6.4).- send(text, to: entry.botId, thread: entry.threadId, nonce: entry.data.clientNonce ?? UUID().uuidString)+ send(text, to: entry.botId, thread: entry.threadId, nonce: entry.data.clientNonce ?? UUID().uuidString, files: files)+ }++ /// A sent file's bytes: on disk after the first fetch (sent files never change).+ public func attachmentData(_ file: Attachment, bot botId: String) async -> Data? {+ guard let url = Self.attachmentCache(file.id) else { return nil }+ if let data = try? Data(contentsOf: url) { return data }+ guard let client = try? require(), let data = try? await client.readUpload(botId: botId, id: file.id) else { return nil }+ Self.cacheAttachment(file.id, data)+ return data+ }++ private static func attachmentCache(_ id: String) -> URL? {+ guard let uuid = UUID(uuidString: id) else { return nil }+ return URL.cachesDirectory.appending(path: "codync-attachments").appending(path: uuid.uuidString)+ }++ private static func cacheAttachment(_ id: String, _ data: Data) {+ guard let url = attachmentCache(id) else { return }+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try? data.write(to: url)}public func discard(_ entry: Entry) {+ if let nonce = entry.data.clientNonce { outgoingFiles[nonce] = nil }entries[entry.botId]?.removeAll { $0.id == entry.id }}@@ -598,6 +680,7 @@ public final class BotStore {}public func stop(_ botId: String) { perform { try await $0.stop(botId) } }+ public func logCall(_ botId: String, seconds: Int) { perform { try await $0.logCall(botId, seconds: seconds) } }public func newSession(_ botId: String) { perform { try await $0.newSession(botId) } }// MARK: remote screen@@ -631,11 +714,53 @@ public final class BotStore {perform { try await $0.respondPermission(entryId: entry.id, optionId: option) }}+ struct ReadingScope: Hashable {+ let botId: String+ let thread: String?+ }++ @ObservationIgnored private var readingViews: [UUID: ReadingScope] = [:]++ /// Views register only while visible in an active scene. Multiple windows may+ /// read the same conversation without unregistering each other.+ func setReading(_ token: UUID, botId: String, thread: String?, active: Bool) {+ if active {+ let scope = ReadingScope(botId: botId, thread: thread)+ readingViews[token] = scope+ if connection == .online { markRead(botId, thread: thread) }+ } else {+ readingViews[token] = nil+ }+ }++ private func acknowledgeVisibleConversations(_ botId: String, entry: Entry? = nil) {+ guard connection == .online else { return }+ for scope in Set(readingViews.values) where scope.botId == botId {+ if let entry, (!entry.isChat || entry.threadId != scope.thread) { continue }+ markRead(botId, thread: scope.thread)+ }+ }+/// The main chat on screen (or the thread on `thread`) is read; the host ignores it/// when nothing there is unread.public func markRead(_ botId: String, thread: String? = nil) {- guard (bots[botId]?.unread ?? 0) > 0 else { return }- perform { try await $0.markRead(botId, threadId: thread) }+ // Entry events may arrive before the roster's unread count. The host is+ // authoritative and treats a redundant scoped acknowledgement as a no-op.+ Task {+ // Opening a cached conversation can race the foreground reconnect.+ // This background acknowledgement must never interrupt the conversation.+ if connection != .online || heldDrop != nil {+ try? await Task.sleep(for: Self.initialConnectionGrace)+ }+ guard !Task.isCancelled, !retired, isActive, heldDrop == nil,+ let client = try? require() else { return }+ do {+ try await client.markRead(botId, threadId: thread)+ } catch {+ // The visible scope is acknowledged again when the link recovers.+ log.debug("read acknowledgement deferred: \(error.localizedDescription)")+ }+ }}/// The roster's "Mark as read": the chat and all its threads.@@ -701,8 +826,8 @@ public final class BotStore {if let s = try? await s { installedSkills = s }}- public func marketConnectors(search: String) async throws -> [MarketConnector] {- try await require().marketConnectors(search: search)+ public func marketConnectors(search: String, cursor: String? = nil) async throws -> (items: [MarketConnector], next: String?) {+ try await require().marketConnectors(search: search, cursor: cursor)}public func marketSkills() async throws -> [MarketSkill] {@@ -723,6 +848,12 @@ public final class BotStore {return c}+ public func importConnectors(config: String) async throws -> [InstalledConnector] {+ let added = try await require().importConnectors(config: config)+ await refreshPlugins()+ return added+ }+public func connectorSignIn(_ id: String) async throws -> ConnectorSignIn {try await require().connectorSignIn(id)}@@ -847,3 +978,18 @@ public final class BotStore {}}}++/// A file picked in the composer, sent with the next message.+public struct OutgoingFile: Identifiable, Sendable {+ public let id = UUID()+ public let name: String+ public let data: Data++ public init(name: String, data: Data) {+ self.name = name+ self.data = data+ }++ /// Anything larger is refused by the computer.+ public static let maxSize = 100 * 1024 * 1024+}diff --git a/kit/Sources/CodyncUI/Store/ComputerSelection.swift b/kit/Sources/CodyncUI/Store/ComputerSelection.swiftnew file mode 100644index 00000000..7e95cd22--- /dev/null+++ b/kit/Sources/CodyncUI/Store/ComputerSelection.swift@@ -0,0 +1,50 @@+import CodyncKit++/// An empty exclusion list means all computers, including newly paired computers.+public struct ComputerSelection: Equatable, Sendable {+ public let all: [ComputerID]+ private let hidden: Set<ComputerID>++ public init(all: [ComputerID], hidden: String) {+ self.all = all+ self.hidden = Set(hidden.split(separator: ",").map(String.init))+ }++ public var shown: [ComputerID] {+ let visible = all.filter { !hidden.contains($0) }+ return visible.isEmpty ? all : visible+ }++ public func toggling(_ id: ComputerID) -> String {+ guard all.contains(id) else { return encoded(Set(all).subtracting(shown)) }+ var visible = Set(shown)+ if visible.contains(id) {+ if visible.count > 1 { visible.remove(id) }+ } else {+ visible.insert(id)+ }+ return encoded(Set(all).subtracting(visible))+ }++ public func only(_ id: ComputerID) -> String {+ guard all.contains(id) else { return "" }+ return encoded(Set(all).subtracting([id]))+ }++ private func encoded(_ ids: Set<ComputerID>) -> String { ids.sorted().joined(separator: ",") }+}++struct ConnectionSummary {+ let connections: [BotStore.Connection]++ var text: String {+ guard !connections.isEmpty else { return "Computers" }+ let online = connections.filter { $0 == .online }.count+ if online == connections.count { return "\(online) connected" }+ if online > 0 { return "\(online)/\(connections.count) connected" }+ if connections.contains(.connecting) { return "Connecting…" }+ if connections.allSatisfy({ if case .unauthorized = $0 { true } else { false } }) { return "No access" }+ if connections.allSatisfy({ $0 == .unpaired }) { return "Not paired" }+ return "\(connections.count) offline"+ }+}diff --git a/kit/Sources/CodyncUI/Thread/Attachments.swift b/kit/Sources/CodyncUI/Thread/Attachments.swiftnew file mode 100644index 00000000..54e0dc7e--- /dev/null+++ b/kit/Sources/CodyncUI/Thread/Attachments.swift@@ -0,0 +1,177 @@+import CodyncKit+import ImageIO+import SwiftUI+import UniformTypeIdentifiers++/// Files in messages: preparing picked, pasted and dropped files, and showing sent ones.++extension OutgoingFile {+ /// Images the agents can't all read (HEIC, TIFF, BMP…) become JPEG, upright.+ static func prepared(name: String, data: Data) -> OutgoingFile {+ let ext = (name as NSString).pathExtension.lowercased()+ guard ["heic", "heif", "tif", "tiff", "bmp"].contains(ext) || (ext.isEmpty && ImageData.isImage(data)),+ let jpeg = ImageData.jpeg(data) else { return OutgoingFile(name: name, data: data) }+ let base = (name as NSString).deletingPathExtension+ return OutgoingFile(name: (base.isEmpty ? "image" : base) + ".jpg", data: jpeg)+ }++ /// A name for a file that came without one (pasted or dragged image data).+ static func unnamed(_ ext: String) -> String {+ "pasted-\(Int(Date.now.timeIntervalSince1970)).\(ext)"+ }+}++/// Anything dropped or pasted: a file, or bare image data.+struct PickedFile: Transferable {+ let file: OutgoingFile++ static var transferRepresentation: some TransferRepresentation {+ FileRepresentation(importedContentType: .item) { received in+ PickedFile(file: .prepared(name: received.file.lastPathComponent, data: try Data(contentsOf: received.file)))+ }+ DataRepresentation(importedContentType: .image) { data in+ PickedFile(file: .prepared(name: OutgoingFile.unnamed(ImageData.isPNG(data) ? "png" : "jpg"), data: data))+ }+ }++ /// Loads what item providers (pasteboard, drops) carry.+ @MainActor static func load(_ providers: [NSItemProvider]) async -> [OutgoingFile] {+ var files: [OutgoingFile] = []+ for provider in providers {+ let file: OutgoingFile? = await withCheckedContinuation { done in+ _ = provider.loadTransferable(type: PickedFile.self) { done.resume(returning: try? $0.get().file) }+ }+ if let file { files.append(file) }+ }+ return files+ }+}++/// ImageIO works the same on iPhone and Mac.+enum ImageData {+ static func isImage(_ data: Data) -> Bool {+ CGImageSourceCreateWithData(data as CFData, nil).map { CGImageSourceGetCount($0) > 0 } ?? false+ }++ static func isPNG(_ data: Data) -> Bool { data.starts(with: [0x89, 0x50, 0x4E, 0x47]) }++ /// A downscaled, upright image (`maxPixels` on the long side).+ static func thumbnail(_ data: Data, maxPixels: Int) -> CGImage? {+ guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }+ let options: [CFString: Any] = [+ kCGImageSourceCreateThumbnailFromImageAlways: true,+ kCGImageSourceCreateThumbnailWithTransform: true,+ kCGImageSourceThumbnailMaxPixelSize: maxPixels,+ ]+ return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary)+ }++ static func jpeg(_ data: Data) -> Data? {+ guard let image = thumbnail(data, maxPixels: 4096) else { return nil }+ let out = NSMutableData()+ guard let dest = CGImageDestinationCreateWithData(out, UTType.jpeg.identifier as CFString, 1, nil) else { return nil }+ CGImageDestinationAddImage(dest, image, [kCGImageDestinationLossyCompressionQuality: 0.85] as CFDictionary)+ return CGImageDestinationFinalize(dest) ? out as Data : nil+ }+}++/// The symbol for a file by its extension.+enum AttachmentIcon {+ static func symbol(_ name: String) -> String {+ switch (name as NSString).pathExtension.lowercased() {+ case "png", "jpg", "jpeg", "heic", "gif", "webp", "tiff", "bmp": "photo"+ case "pdf": "doc.richtext"+ case "zip", "gz", "tar", "7z": "doc.zipper"+ case "mov", "mp4", "m4v": "film"+ case "mp3", "m4a", "wav", "aac": "waveform"+ default: "doc"+ }+ }+}++/// Files sent with a message, on the sender's side: images as pictures (tap for full size),+/// other files as cards.+struct AttachmentList: View {+ let attachments: [Attachment]+ let botId: String+ @State private var viewing: Attachment?++ var body: some View {+ VStack(alignment: .trailing, spacing: 4) {+ ForEach(attachments) { file in+ if file.isImage {+ AttachmentImage(file: file, botId: botId, maxPixels: 720)+ .frame(maxWidth: 220, maxHeight: 280)+ .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))+ .contentShape(Rectangle())+ .onTapGesture { viewing = file }+ .accessibilityLabel(file.name)+ .accessibilityAddTraits(.isButton)+ } else {+ card(file)+ }+ }+ }+ .codyncSheet(item: $viewing) { file in+ VStack(spacing: 0) {+ ModalHeader(file.name)+ AttachmentImage(file: file, botId: botId, maxPixels: 4096)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .padding(12)+ }+ .background(Palette.background)+ #if os(macOS)+ .frame(width: 720, height: 560)+ #endif+ }+ }++ private func card(_ file: Attachment) -> some View {+ HStack(spacing: 8) {+ Image(systemName: AttachmentIcon.symbol(file.name))+ .font(.system(size: 16))+ .foregroundStyle(Palette.secondary)+ VStack(alignment: .leading, spacing: 1) {+ Text(file.name)+ .font(.subheadline)+ .foregroundStyle(Palette.text)+ .lineLimit(1)+ .truncationMode(.middle)+ Text(ByteCountFormatter.string(fromByteCount: file.size, countStyle: .file))+ .font(.caption2)+ .foregroundStyle(Palette.tertiary)+ }+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ .background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 16, style: .continuous))+ .accessibilityElement(children: .combine)+ }+}++/// A sent image, fetched from the computer once and then read from the cache.+private struct AttachmentImage: View {+ let file: Attachment+ let botId: String+ let maxPixels: Int+ @Environment(BotStore.self) private var model+ @State private var image: CGImage?++ var body: some View {+ Group {+ if let image {+ Image(decorative: image, scale: 1).resizable().aspectRatio(contentMode: .fit)+ } else {+ RoundedRectangle(cornerRadius: 16, style: .continuous)+ .fill(Palette.bubbleUser)+ .frame(width: 160, height: 120)+ .overlay { Image(systemName: "photo").foregroundStyle(Palette.tertiary) }+ }+ }+ .task(id: file.id) {+ guard let data = await model.attachmentData(file, bot: botId) else { return }+ let size = maxPixels+ image = await Task.detached { ImageData.thumbnail(data, maxPixels: size) }.value+ }+ }+}diff --git a/kit/Sources/CodyncUI/Thread/ChatRows.swift b/kit/Sources/CodyncUI/Thread/ChatRows.swiftindex 93e8c8b2..edb10783 100644--- a/kit/Sources/CodyncUI/Thread/ChatRows.swift+++ b/kit/Sources/CodyncUI/Thread/ChatRows.swift@@ -47,7 +47,11 @@ struct ChatRow: View {}.padding(.top, 12)default:- NoticeRow(entry: entry).padding(.top, 10)+ if let request = entry.data.connectionRequest {+ ConnectionRequestCard(entry: entry, request: request).padding(.top, 12)+ } else {+ NoticeRow(entry: entry).padding(.top, 10)+ }}}@@ -128,18 +132,10 @@ struct UserBubble: View {var body: some View {VStack(alignment: .trailing, spacing: 4) {- Text(entry.data.text ?? "")- .font(InterfaceMetrics.body)- .foregroundStyle(Palette.text)- .textSelection(.enabled)- .padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 16))- .padding(.vertical, InterfaceMetrics.value(mac: 8, mobile: 10))- .background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 22, style: .continuous))- .contextActions(reactions: model.reactionPick(entry)) {- var items = [MenuItem("Copy", icon: "square.on.square") { Pasteboard.copy(entry.data.text) }]- if let reply { items.append(MenuItem("Reply in thread", icon: "arrowshape.turn.up.left", action: reply)) }- return items- }+ if let attachments = entry.data.attachments, !attachments.isEmpty {+ AttachmentList(attachments: attachments, botId: entry.botId)+ }+ if !(entry.data.text ?? "").isEmpty { text }#if os(macOS)HStack(spacing: 6) {if hovering, entry.data.status == nil || entry.data.status == "sent" {@@ -157,6 +153,21 @@ struct UserBubble: View {.padding(.leading, 56)}+ private var text: some View {+ Text(entry.data.text ?? "")+ .font(InterfaceMetrics.body)+ .foregroundStyle(Palette.text)+ .textSelection(.enabled)+ .padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 16))+ .padding(.vertical, InterfaceMetrics.value(mac: 8, mobile: 10))+ .background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 22, style: .continuous))+ .contextActions(reactions: model.reactionPick(entry)) {+ var items = [MenuItem("Copy", icon: "square.on.square") { Pasteboard.copy(entry.data.text) }]+ if let reply { items.append(MenuItem("Reply in thread", icon: "arrowshape.turn.up.left", action: reply)) }+ return items+ }+ }+@ViewBuilder private var status: some View {switch entry.data.status {case "sending":@@ -245,6 +256,17 @@ struct NoticeRow: View {var body: some View {let text = entry.data.text ?? ""+ if let seconds = entry.data.callSeconds {+ Label("\(text) · \(String(format: "%02d:%02d", seconds / 60, seconds % 60))", systemImage: "waveform")+ .font(.footnote.monospacedDigit())+ .foregroundStyle(Palette.secondary)+ .frame(maxWidth: .infinity)+ } else {+ styled(text)+ }+ }++ @ViewBuilder private func styled(_ text: String) -> some View {switch entry.data.style {case "divider":HStack(spacing: 10) {diff --git a/kit/Sources/CodyncUI/Thread/Composer.swift b/kit/Sources/CodyncUI/Thread/Composer.swiftindex 5ab9dcb0..b68cdb58 100644--- a/kit/Sources/CodyncUI/Thread/Composer.swift+++ b/kit/Sources/CodyncUI/Thread/Composer.swift@@ -1,5 +1,7 @@import CodyncKit+import PhotosUIimport SwiftUI+import UniformTypeIdentifiers/// The message box under a chat or a thread: send, or stop while the bot (or the/// group) is working there. In a group, typing `@` suggests its bots.@@ -7,23 +9,45 @@ struct Composer: View {let botId: String/// Replies go to the thread on this message.var thread: String?+ /// Starts a voice call; while the box is empty it takes the send button's place.+ var onCall: (() -> Void)?@Environment(BotStore.self) private var model@State private var draft = ""+ /// Files going out with the next message.+ @State private var files: [OutgoingFile] = []+ @State private var addMenu = false+ @State private var pickingFiles = false+ @State private var pickingPhotos = false+ @State private var photoItems: [PhotosPickerItem] = []+ #if os(iOS)+ /// The clipboard's `changeCount` last pasted (or passed on), so one copy is offered once.+ @State private var pasteCount = -1+ @State private var clipboardTick = 0+ #else+ @State private var pasteMonitor: Any?+ #endif@FocusState private var focused: Bool+ /// One line of the field's text, following Dynamic Type: the send button centers on the last line.+ @ScaledMetric(relativeTo: .body) private var lineHeight = InterfaceMetrics.value(mac: 15, mobile: 22)private var bot: Bot? { model.bots[botId] }private var working: Bool { bot?.isWorking(in: botId, thread: thread) == true }+ private var isEmpty: Bool { draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && files.isEmpty }+private var canSend: Bool {- // Offline computers still take messages when the relay can hold them for it.- !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && (model.connection == .online || model.canQueue)+ // Offline computers still take messages when the relay can hold them for it (text only).+ !isEmpty && (model.connection == .online || (model.canQueue && files.isEmpty))}+ /// Groups have no folder of their own to put files in.+ private var canAttach: Bool { bot?.isGroup == false }+private var placeholder: String {let name = bot?.name ?? ""if thread != nil { return "Reply…" }if bot?.isGroup == true { return "Message \(name) · @ to ask one bot" }- return working ? "Queue a message for \(name)" : "Message \(name)"+ return working ? "Queue a message for \(name)" : "Ask \(name)"}/// The `@partial` being typed at the end, if any.@@ -68,15 +92,72 @@ struct Composer: View {.animation(Motion.layout, value: suggestions.map(\.id))}+ private var fieldPadding: CGFloat { InterfaceMetrics.value(mac: 7, mobile: 10) }+ private var buttonSize: CGFloat { InterfaceMetrics.value(mac: 28, mobile: 34) }+private var field: some View {+ HStack(alignment: .bottom, spacing: 8) {+ if canAttach { addButton }+ VStack(alignment: .leading, spacing: 0) {+ #if os(iOS)+ let _ = clipboardTick+ if clipboardOffer { pasteOffer.transition(.move(edge: .bottom).combined(with: .opacity)) }+ #endif+ if !files.isEmpty {+ fileChips.transition(.move(edge: .bottom).combined(with: .opacity))+ }+ box+ }+ .composerSurface(in: RoundedRectangle(cornerRadius: 24, style: .continuous))+ }+ .animation(Motion.layout, value: files.map(\.id))+ #if os(iOS)+ // The clipboard isn't observable: look again when typing starts or the app comes back.+ .onChange(of: focused) { _, _ in clipboardTick += 1 }+ .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in clipboardTick += 1 }+ .onReceive(NotificationCenter.default.publisher(for: UIPasteboard.changedNotification)) { _ in clipboardTick += 1 }+ #else+ .onAppear(perform: installPasteMonitor)+ .onDisappear {+ if let pasteMonitor { NSEvent.removeMonitor(pasteMonitor) }+ pasteMonitor = nil+ }+ #endif+ .dropDestination(for: PickedFile.self) { picked, _ in+ guard canAttach else { return false }+ append(picked.map(\.file))+ return true+ }+ .fileImporter(isPresented: $pickingFiles, allowedContentTypes: [.item], allowsMultipleSelection: true) { result in+ if case .success(let urls) = result { add(urls) }+ }+ #if os(iOS)+ .photosPicker(isPresented: $pickingPhotos, selection: $photoItems, maxSelectionCount: 10, matching: .images)+ .onChange(of: photoItems) { _, items in+ guard !items.isEmpty else { return }+ photoItems = []+ Task { await addPhotos(items) }+ }+ #endif+ .padding(.horizontal, 16)+ .padding(.top, 6)+ .padding(.bottom, 16)+ #if os(macOS)+ .frame(maxWidth: 820)+ .frame(maxWidth: .infinity)+ #endif+ }++ private var box: some View {HStack(alignment: .bottom, spacing: 8) {TextField(placeholder, text: $draft, axis: .vertical).lineLimit(1...8).font(InterfaceMetrics.body).textFieldStyle(.plain).focused($focused)- .padding(.vertical, InterfaceMetrics.value(mac: 7, mobile: 10))+ .padding(.vertical, fieldPadding).sendOnReturn(submit)+ Group {if working && draft.isEmpty {Button {model.stop(botId)@@ -90,6 +171,18 @@ struct Composer: View {.buttonStyle(.plain).accessibilityLabel("Stop").help("Stop")+ } else if let onCall, draft.isEmpty, files.isEmpty {+ Button(action: onCall) {+ Image(systemName: "waveform")+ .font(.system(size: 15, weight: .bold))+ .frame(width: buttonSize * 1.35, height: buttonSize)+ .background(Palette.accentFill, in: Capsule())+ .foregroundStyle(Palette.onAccent)+ }+ .buttonStyle(.plain)+ .transition(.opacity)+ .accessibilityLabel("Call")+ .help("Call")} else {Button(action: submit) {Image(systemName: "arrow.up")@@ -103,6 +196,9 @@ struct Composer: View {.accessibilityLabel("Send").help("Send")}+ }+ .padding(.bottom, max(0, (lineHeight + 2 * fieldPadding - buttonSize) / 2))+ .animation(Motion.layout, value: isEmpty)}.padding(.leading, InterfaceMetrics.value(mac: 14, mobile: 18)).padding(.trailing, 6)@@ -113,16 +209,169 @@ struct Composer: View {model.routineDrafts.removeValue(forKey: botId)focused = true}- .composerSurface(in: RoundedRectangle(cornerRadius: 24, style: .continuous))- .padding(.horizontal, 16)- .padding(.top, 6)- .padding(.bottom, 16)- #if os(macOS)- .frame(maxWidth: 820)- .frame(maxWidth: .infinity)+ }++ /// Photos or files (iPhone), files (Mac); dropping files on the box works too.+ private var addButton: some View {+ Button {+ #if os(iOS)+ addMenu = true+ #else+ pickingFiles = true+ #endif+ } label: {+ Image(systemName: "plus")+ .font(.system(size: InterfaceMetrics.value(mac: 13, mobile: 18), weight: .medium))+ .foregroundStyle(Palette.text)+ .frame(width: buttonSize + 2 * InterfaceMetrics.value(mac: 4, mobile: 6),+ height: buttonSize + 2 * InterfaceMetrics.value(mac: 4, mobile: 6))+ .composerSurface(in: Circle())+ .contentShape(Circle())+ }+ .buttonStyle(PressScale())+ .accessibilityLabel("Add files")+ .help("Add files")+ .codyncMenu(isPresented: $addMenu) {+ var items = [MenuItem("Photos", icon: "photo.on.rectangle") { pickingPhotos = true },+ MenuItem("Files", icon: "folder") { pickingFiles = true }]+ #if os(iOS)+ if UIPasteboard.general.hasImages || UIPasteboard.general.hasURLs {+ items.append(MenuItem("Paste", icon: "doc.on.clipboard") { pasteFiles() })+ }+ #endif+ return items+ }+ }++ #if os(iOS)+ private var pasteOffer: some View {+ HStack(spacing: 6) {+ Button(action: pasteFiles) {+ Label("Paste image", systemImage: "doc.on.clipboard")+ .font(.footnote.weight(.medium))+ .foregroundStyle(Palette.text)+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ .background(Palette.surface, in: Capsule())+ }+ .buttonStyle(PressScale())+ Button { pasteCount = UIPasteboard.general.changeCount } label: {+ Image(systemName: "xmark").font(.system(size: 10, weight: .bold)).foregroundStyle(Palette.secondary)+ }+ .buttonStyle(.plain)+ .accessibilityLabel("Don't paste")+ }+ .padding(.horizontal, 10)+ .padding(.top, 8)+ }+ #endif++ private var fileChips: some View {+ ScrollView(.horizontal, showsIndicators: false) {+ HStack(spacing: 6) {+ ForEach(files) { file in+ HStack(spacing: 6) {+ Image(systemName: AttachmentIcon.symbol(file.name))+ .foregroundStyle(Palette.secondary)+ Text(file.name)+ .font(.footnote)+ .foregroundStyle(Palette.text)+ .lineLimit(1)+ .truncationMode(.middle)+ .frame(maxWidth: 160, alignment: .leading)+ Button {+ files.removeAll { $0.id == file.id }+ } label: {+ Image(systemName: "xmark").font(.system(size: 10, weight: .bold)).foregroundStyle(Palette.secondary)+ }+ .buttonStyle(.plain)+ .accessibilityLabel("Remove \(file.name)")+ .help("Remove")+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ .background(Palette.surface, in: Capsule())+ }+ }+ .padding(.horizontal, 10)+ .padding(.top, 8)+ }+ }++ private func add(_ urls: [URL]) {+ append(urls.compactMap { url in+ let scoped = url.startAccessingSecurityScopedResource()+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }+ return (try? Data(contentsOf: url, options: .mappedIfSafe)).map { OutgoingFile.prepared(name: url.lastPathComponent, data: $0) }+ })+ }++ private func append(_ new: [OutgoingFile]) {+ guard canAttach else { return }+ for file in new {+ guard file.data.count <= OutgoingFile.maxSize else {+ model.lastError = "\(file.name) is larger than 100 MB."+ continue+ }+ files.append(file)+ }+ }++ /// Images (or files) on the clipboard become attachments.+ private func pasteFiles() {+ #if os(iOS)+ let providers = UIPasteboard.general.itemProviders+ pasteCount = UIPasteboard.general.changeCount+ #else+ let providers = (NSPasteboard.general.pasteboardItems ?? []).compactMap { item -> NSItemProvider? in+ if let url = item.string(forType: .fileURL).flatMap(URL.init(string:)) { return NSItemProvider(contentsOf: url) }+ for type in [NSPasteboard.PasteboardType.png, .tiff] {+ if let data = item.data(forType: type) {+ return NSItemProvider(item: data as NSData, typeIdentifier: type == .png ? UTType.png.identifier : UTType.tiff.identifier)+ }+ }+ return nil+ }#endif+ Task { append(await PickedFile.load(providers)) }}+ #if os(iOS)+ /// Photos go out as JPEG: HEIC isn't something every agent can read.+ private func addPhotos(_ items: [PhotosPickerItem]) async {+ let stamp = Int(Date.now.timeIntervalSince1970)+ var picked: [OutgoingFile] = []+ for (i, item) in items.enumerated() {+ guard let data = try? await item.loadTransferable(type: Data.self),+ let jpeg = ImageData.jpeg(data) else { continue }+ picked.append(OutgoingFile(name: "photo-\(stamp)-\(i + 1).jpg", data: jpeg))+ }+ append(picked)+ }++ /// A copied image not offered yet: shown as a "Paste image" chip while typing.+ private var clipboardOffer: Bool {+ canAttach && focused && UIPasteboard.general.hasImages && UIPasteboard.general.changeCount != pasteCount+ }+ #else+ /// ⌘V with a copied image or file (the text field alone would paste nothing, or just+ /// the file's name).+ private func installPasteMonitor() {+ guard pasteMonitor == nil else { return }+ pasteMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in+ let consumed = MainActor.assumeIsolated {+ guard focused, canAttach, event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command,+ event.charactersIgnoringModifiers == "v" else { return false }+ let types = NSPasteboard.general.types ?? []+ guard types.contains(.fileURL) || (!types.contains(.string) && (types.contains(.png) || types.contains(.tiff))) else { return false }+ pasteFiles()+ return true+ }+ return consumed ? nil : event+ }+ }+ #endif+private func mention(_ member: Bot) {guard let at = draft.lastIndex(of: "@") else { return }draft = String(draft[..<at]) + "@\(member.name) "@@ -131,7 +380,9 @@ struct Composer: View {private func submit() {guard canSend else { return }- model.send(draft, to: botId, thread: thread)+ model.send(draft, to: botId, thread: thread, files: files)draft = ""+ files = []}}+diff --git a/kit/Sources/CodyncUI/Thread/ReadingConversation.swift b/kit/Sources/CodyncUI/Thread/ReadingConversation.swiftnew file mode 100644index 00000000..f3ba401e--- /dev/null+++ b/kit/Sources/CodyncUI/Thread/ReadingConversation.swift@@ -0,0 +1,32 @@+import SwiftUI++extension View {+ func readingConversation(_ botId: String, thread: String? = nil) -> some View {+ modifier(ReadingConversation(botId: botId, thread: thread))+ }+}++/// A scoped read receipt follows view visibility, rather than roster selection.+private struct ReadingConversation: ViewModifier {+ let botId: String+ let thread: String?+ @Environment(BotStore.self) private var model+ @Environment(\.scenePhase) private var scenePhase+ @State private var token = UUID()+ @State private var visible = false++ func body(content: Content) -> some View {+ content+ .onAppear { visible = true; update() }+ .onDisappear { visible = false; update() }+ .onChange(of: scenePhase) { _, _ in update() }+ .onChange(of: botId) { _, _ in update() }+ .onChange(of: thread) { _, _ in update() }+ .onChange(of: model.connection) { _, _ in update() }+ }++ private func update() {+ model.setReading(token, botId: botId, thread: thread,+ active: visible && scenePhase == .active)+ }+}diff --git a/kit/Sources/CodyncUI/Thread/RepliesView.swift b/kit/Sources/CodyncUI/Thread/RepliesView.swiftindex eb56cd9e..805b109e 100644--- a/kit/Sources/CodyncUI/Thread/RepliesView.swift+++ b/kit/Sources/CodyncUI/Thread/RepliesView.swift@@ -65,8 +65,7 @@ struct RepliesView: View {.background(Palette.background).task(id: rootId) { await model.loadThread(botId, root: rootId) }// A thread is read on its own: having it open reads its replies.- .onAppear { model.markRead(botId, thread: rootId) }- .onChange(of: replies.last?.id) { _, _ in model.markRead(botId, thread: rootId) }+ .readingConversation(botId, thread: rootId).codyncSheet(isPresented: $showTrace) {TraceView(botId: botId, thread: rootId)#if os(macOS)diff --git a/kit/Sources/CodyncUI/Thread/ThreadView.swift b/kit/Sources/CodyncUI/Thread/ThreadView.swiftindex af4d553a..3536176d 100644--- a/kit/Sources/CodyncUI/Thread/ThreadView.swift+++ b/kit/Sources/CodyncUI/Thread/ThreadView.swift@@ -23,7 +23,6 @@ public struct ThreadView: View {@State private var availableWidth: CGFloat = 800@State private var compactDetails = false@State private var calling = false- @State private var showMenu = false@State private var showRoutines = false@State private var routineId: String?@State private var routineRequest = UUID()@@ -119,9 +118,9 @@ public struct ThreadView: View {}.defaultScrollAnchor(.bottom).scrollDismissesKeyboard(.interactively)+ .conversationScrollEdges().onChange(of: items.last?.id) { _, _ inwithAnimation(.snappy) { proxy.scrollTo("bottom", anchor: .bottom) }- model.markRead(botId)}.onChange(of: bot?.isWorking) { _, _ inwithAnimation(.snappy) { proxy.scrollTo("bottom", anchor: .bottom) }@@ -131,46 +130,43 @@ public struct ThreadView: View {.safeAreaInset(edge: .bottom) {VStack(spacing: 6) {#if os(iOS)- ConnectionBanner().padding(.horizontal, 14)+ Composer(botId: botId, onCall: bot?.isGroup == false ? { calling = true } : nil)+ #else+ Composer(botId: botId)#endif- Composer(botId: botId)}}#if os(iOS).navigationBarTitleDisplayMode(.inline).toolbar(.visible, for: .navigationBar)+ .toolbarBackground(.hidden, for: .navigationBar).toolbar {ToolbarItem(placement: .principal) {VStack(spacing: 0) {header- ConnectingIndicator(isConnecting: model.connection == .connecting)+ connectionSubtitle}}- if model.screen?.agentBot == botId {- ToolbarItem(placement: .topBarTrailing) {- // The bot is operating the computer: watch it live (and take over from there).- Button("Watch the screen", systemImage: "cursorarrow.motionlines") {- model.screenRequest = ScreenRequest(watching: botId)- }- .symbolEffect(.pulse, options: .repeating)- }+ if model.screen != nil {+ ToolbarItem(placement: .topBarTrailing) { computerButton }}- if bot?.isGroup != true {- ToolbarItem(placement: .topBarTrailing) {- Button("Call", systemImage: "phone") { calling = true }- }- }- ToolbarItem(placement: .topBarTrailing) { menu }}- .codyncOverlay(isPresented: $calling) { close in- CallView(botId: botId, close: close)+ // Grok Bot's call: a bar floating over the chat, which stays readable and usable.+ .overlay(alignment: .top) {+ if calling {+ CallView(botId: botId) { withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { calling = false } }+ .padding(.top, 4)+ .transition(.move(edge: .top).combined(with: .opacity))+ }}+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: calling)#endif#if os(macOS).safeAreaInset(edge: .top, spacing: 0) {VStack(spacing: 0) {HStack {header+ connectionSubtitleSpacer(minLength: 8)if let bot, !bot.isGroup {IconButton("Create template", systemImage: "square.and.arrow.up") {@@ -186,7 +182,6 @@ public struct ThreadView: View {.padding(.horizontal, 16).frame(height: 44)Rectangle().fill(Palette.border).frame(height: 0.5)- ConnectionBanner().padding(.horizontal, 16).padding(.top, model.isOffline ? 8 : 0)}.background(Palette.background)}@@ -194,7 +189,7 @@ public struct ThreadView: View {if bot?.name == "New Bot", model.chat(botId).isEmpty { editingDetails = true }}#endif- .onAppear { model.markRead(botId) }+ .readingConversation(botId).codyncSheet(isPresented: $showTrace) {TraceView(botId: botId)#if os(macOS)@@ -261,29 +256,102 @@ public struct ThreadView: View {// MARK: chrome+ private var connectionSubtitle: some View {+ HStack(spacing: 6) {+ Image(systemName: connectionSymbol)+ .font(.system(size: 8, weight: .medium))+ .frame(width: 12)+ .accessibilityHidden(true)+ Text(model.connectionLabel)+ .lineLimit(1)+ .truncationMode(.middle)+ }+ .font(.system(size: 10, weight: .medium))+ .foregroundStyle(Palette.secondary)+ .accessibilityElement(children: .ignore)+ .accessibilityLabel("\(model.hostName), \(connectionDescription)")+ .help("\(model.hostName) · \(connectionDescription)")+ }++ private var connectionSymbol: String {+ guard model.connection == .online else {+ return model.connection == .connecting ? "arrow.triangle.2.circlepath" : "wifi.slash"+ }+ switch model.hostRoute {+ case .relay: return "cloud"+ case .direct: return "wifi"+ case .loopback: return "desktopcomputer"+ case nil: return "network"+ }+ }++ private var connectionDescription: String {+ switch model.connection {+ case .connecting: return "Connecting"+ case .computerOffline, .offline: return "Offline"+ case .unauthorized: return "No access"+ case .unpaired: return "Not paired"+ case .online: break+ }+ switch model.hostRoute {+ case .relay: return "Connected through Cloudflare"+ case .direct: return "Connected over Wi-Fi or Tailscale"+ case .loopback: return "Connected locally"+ case nil: return "Connected"+ }+ }+private var header: some View {- Button {- #if os(macOS)- toggleDetails()- #else- if bot?.isGroup == true { editingGroup = true } else if let bot { editing = EditorRequest(BotDraft(bot)) }- #endif- } label: {- HStack(spacing: 7) {- if let bot {- if bot.isGroup { GroupAvatar(members: model.members(of: bot), size: 22) } else { CharacterAvatar(bot: bot, size: 22) }+ #if os(iOS)+ // Like Grok Bot: the title pill holds the bot's actions; the corner is the computer.+ Menu {+ Text("\(model.hostName) · \(model.connectionLabel)")+ Button("Reconnect", systemImage: "arrow.clockwise") { model.restartStream() }+ Divider()+ Button("Details", systemImage: "info.circle", action: openDetails)+ ForEach(menuItems) { item in+ if item.divider { Divider() }+ Button(role: item.destructive ? .destructive : nil, action: item.action) {+ if let icon = item.icon { Label(item.title, systemImage: icon) } else { Text(item.title) }+ }}- Text(bot?.name ?? "")- .font(.system(size: 13, weight: .semibold))- .foregroundStyle(Palette.text)- .lineLimit(1)+ } label: {+ title}- }- #if os(macOS)- .buttonStyle(.plain)+ .accessibilityLabel("\(bot?.name ?? "Conversation") actions")+ #else+ Button(action: toggleDetails) { title }+ .buttonStyle(.plain)+ .accessibilityLabel("View conversation details")+ .help("View conversation details")#endif- .accessibilityLabel("View conversation details")- .help("View conversation details")+ }++ #if os(iOS)+ private func openDetails() {+ if bot?.isGroup == true { editingGroup = true } else if let bot { editing = EditorRequest(BotDraft(bot)) }+ }++ /// Opens the computer's screen; pulses while this bot is operating it (watch, then take over).+ private var computerButton: some View {+ let operating = model.screen?.agentBot == botId+ return Button("Computer", systemImage: "desktopcomputer") {+ model.screenRequest = operating ? ScreenRequest(watching: botId) : ScreenRequest()+ }+ .symbolEffect(.pulse, options: .repeating, isActive: operating)+ }+ #endif++ private var title: some View {+ HStack(spacing: 7) {+ if let bot {+ if bot.isGroup { GroupAvatar(members: model.members(of: bot), size: 22) } else { CharacterAvatar(bot: bot, size: 22) }+ }+ Text(bot?.name ?? "")+ .font(.system(size: 13, weight: .semibold))+ .foregroundStyle(Palette.text)+ .lineLimit(1)+ }}#if os(macOS)@@ -349,23 +417,6 @@ public struct ThreadView: View {items.append(MenuItem("Delete bot", icon: "trash", destructive: true, divider: true) { confirmDelete = bot })return items}-- private var menu: some View {- #if os(iOS)- Button("More", systemImage: "ellipsis") { showMenu = true }- .codyncMenu(isPresented: $showMenu) { menuItems }- #else- DropdownMenu { menuItems } label: {- Image(systemName: "ellipsis.circle")- .font(.system(size: 14, weight: .medium))- .foregroundStyle(Palette.secondary)- .frame(width: 28, height: 28)- .contentShape(Rectangle())- }- .accessibilityLabel("More")- .help("More")- #endif- }}// MARK: - Chat model@@ -472,7 +523,7 @@ private struct IntroCard: View {VStack(spacing: 12) {CharacterAvatar(bot: bot, size: 72)Text(bot.name).font(.title2.weight(.semibold)).foregroundStyle(Palette.text)- Text("\(model.backendName(bot.backend)) in \(bot.cwd)")+ Text(bot.managedWorkspace ? "\(model.backendName(bot.backend)) · Personal workspace" : "\(model.backendName(bot.backend)) in \(bot.cwd)").font(.footnote.monospaced()).foregroundStyle(Palette.tertiary).multilineTextAlignment(.center)@@ -583,10 +634,12 @@ private struct DetailsPanel: View {.foregroundStyle(Palette.secondary)}}- Label(computerStatus, systemImage: computerStatusSymbol)- .font(.system(size: 12, weight: .medium))- .foregroundStyle(Palette.text)- .fixedSize(horizontal: false, vertical: true)+ if !model.isOffline {+ Label(computerStatus, systemImage: computerStatusSymbol)+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(Palette.text)+ .fixedSize(horizontal: false, vertical: true)+ }if screenReady {Text("View and control this Mac from your iPhone.").font(.system(size: 11))@@ -612,11 +665,11 @@ private struct DetailsPanel: View {}.font(.system(size: 12))VStack(alignment: .leading, spacing: 6) {- Label("Working folder", systemImage: "folder")+ Label(bot.managedWorkspace ? "Workspace" : "Project folder", systemImage: "folder").font(.system(size: 11)).foregroundStyle(Palette.secondary)- Text(bot.cwd)- .font(.system(size: 11, design: .monospaced))+ Text(bot.managedWorkspace ? "Personal · managed by Codync" : bot.cwd)+ .font(.system(size: 11)).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)@@ -636,7 +689,6 @@ private struct DetailsPanel: View {}private var computerStatusSymbol: String {- if model.isOffline { return "wifi.slash" }guard let screen = model.screen, screen.enabled else { return "power" }if !screen.connected { return "arrow.triangle.2.circlepath" }if !screen.capture { return "exclamationmark.circle" }@@ -644,7 +696,6 @@ private struct DetailsPanel: View {}private var computerStatus: String {- guard !model.isOffline else { return "Computer is offline" }guard let screen = model.screen, screen.enabled else { return "Remote screen is off" }guard screen.connected else { return "Connecting to computer…" }guard screen.capture else { return "Screen recording permission needed" }@@ -652,3 +703,17 @@ private struct DetailsPanel: View {}}#endif++private extension View {+ @ViewBuilder func conversationScrollEdges() -> some View {+ if #available(iOS 26, macOS 26, *) {+ #if os(iOS)+ scrollEdgeEffectHidden(true, for: .top)+ #else+ self+ #endif+ } else {+ self+ }+ }+}diff --git a/kit/Tests/CodyncKitTests/ConnectionRequestTests.swift b/kit/Tests/CodyncKitTests/ConnectionRequestTests.swiftnew file mode 100644index 00000000..eb7eec2f--- /dev/null+++ b/kit/Tests/CodyncKitTests/ConnectionRequestTests.swift@@ -0,0 +1,16 @@+import Foundation+import Testing+@testable import CodyncKit++@Test func secureConnectionRequestIsChatVisibleWithoutCredentialValues() throws {+ let wire = #"{"id":"request","seq":1,"botId":"bot","rev":1,"kind":"notice","turn":1,"createdAt":0,"updatedAt":0,"data":{"text":"Connect the service","connectionRequest":{"kind":"secret","status":"pending","title":"Example","botId":"bot","connectorId":"example","field":"API_KEY","location":"env"}}}"#+ let entry = try JSONDecoder().decode(Entry.self, from: Data(wire.utf8))+ #expect(entry.isChat)+ #expect(entry.data.connectionRequest?.field == "API_KEY")+ #expect(entry.data.connectionRequest?.status == "pending")+ let encoded = try JSONEncoder().encode(entry)+ let object = try JSONSerialization.jsonObject(with: encoded) as? [String: Any]+ let data = object?["data"] as? [String: Any]+ let request = data?["connectionRequest"] as? [String: Any]+ #expect(request?["value"] == nil)+}diff --git a/kit/Tests/CodyncKitTests/RoutineTests.swift b/kit/Tests/CodyncKitTests/RoutineTests.swiftindex 3a2bf6cc..54665eb0 100644--- a/kit/Tests/CodyncKitTests/RoutineTests.swift+++ b/kit/Tests/CodyncKitTests/RoutineTests.swift@@ -19,44 +19,20 @@ import Testing#expect(restored.runId == "run")}-@Test func routineScheduleEditsKeepExactIntervalsAndCalendarTimes() throws {- let interval = RoutineTrigger(type: "interval", seconds: 5400)- let draft = RoutineScheduleDraft(triggers: [interval])- #expect(draft.amount == "90")- #expect(draft.unit == 60)- #expect(try draft.triggers() == [interval])- let weekly = RoutineTrigger(type: "cron", expression: "20 14 * * 0", timeZone: "Asia/Taipei")- let calendar = RoutineScheduleDraft(triggers: [weekly])- #expect(calendar.calendarStyle == "weekly")- #expect(calendar.weekday == 0)- #expect(try calendar.triggers() == [weekly])- let custom = RoutineTrigger(type: "cron", expression: "*/15 9-17 * * 1-5", timeZone: "America/New_York")- #expect(try RoutineScheduleDraft(triggers: [custom]).triggers() == [custom])- #expect(try RoutineScheduleDraft(triggers: [weekly, interval]).triggers() == [weekly, interval])+@Test func routineScheduleResponseCarriesServerPreviewWithoutClientRules() throws {+ let data = Data(#"{"draft":{"kind":"cron","amount":"1","unit":3600,"calendarStyle":"days","weekday":1,"selectedDays":[1,3,5],"monthDay":1,"minuteStep":15,"hour":23,"minute":47,"at":0,"expression":"47 23 * * 1,3,5","zone":"Asia/Taipei","original":[]},"triggers":[{"type":"cron","expression":"47 23 * * 1,3,5","timeZone":"Asia/Taipei"}],"summary":"Server schedule description","nextRunAt":1790470800000,"warning":null}"#.utf8)+ let preview = try JSONDecoder().decode(RoutineSchedulePreview.self, from: data)+ #expect(preview.summary == "Server schedule description")+ #expect(preview.draft.selectedDays == [1, 3, 5])+ #expect(preview.nextRunAt == 1_790_470_800_000)+ let encoded = try JSONEncoder().encode(preview.draft)+ #expect(try JSONDecoder().decode(RoutineScheduleDraft.self, from: encoded) == preview.draft)}-@Test func routineScheduleConvertsUnitsAndRejectsOverflow() throws {+@Test func routineDateControlPreservesWireMilliseconds() {var draft = RoutineScheduleDraft()- draft.amount = "2"- draft.unit = 3600- #expect(try draft.triggers().first?.seconds == 7200)- draft.amount = String(Int64.max)- #expect(throws: (any Error).self) { try draft.triggers() }- draft.amount = "0"- #expect(throws: (any Error).self) { try draft.triggers() }- draft.kind = "cron"- draft.zone = "invalid/zone"- #expect(throws: (any Error).self) { try draft.triggers() }-}--@Test func editingAnExpiredOneTimeRoutinePreservesItsTimestamp() throws {- let once = RoutineTrigger(type: "once", at: 1_779_000_000_001)- #expect(try RoutineScheduleDraft(triggers: [once]).triggers() == [once])-}--@Test func weekdayScheduleKeepsItsZoneAndWorkingDays() throws {- let weekday = RoutineTrigger(type: "cron", expression: "30 8 * * 1-5", timeZone: "America/New_York")- let draft = RoutineScheduleDraft(triggers: [weekday])- #expect(draft.calendarStyle == "weekdays")- #expect(try draft.triggers() == [weekday])+ draft.at = 1_779_000_000_001+ let date = draft.date+ draft.date = date+ #expect(draft.at == 1_779_000_000_001)}diff --git a/kit/Tests/CodyncKitTests/WorkspaceTests.swift b/kit/Tests/CodyncKitTests/WorkspaceTests.swiftnew file mode 100644index 00000000..654d2ca6--- /dev/null+++ b/kit/Tests/CodyncKitTests/WorkspaceTests.swift@@ -0,0 +1,19 @@+import Foundation+import Testing+@testable import CodyncKit++@Test func personalWorkspaceDraftDoesNotReuseAnotherBotsDirectory() throws {+ let bot = try JSONDecoder().decode(Bot.self, from: Data(#"{"id":"one","name":"One","cwd":"/data/bots/one/workspace","managedWorkspace":true}"#.utf8))+ let draft = BotDraft(bot)+ #expect(draft.cwd.isEmpty)+ #expect(bot.folderName == "Personal workspace")+ let encoded = try JSONEncoder().encode(draft)+ let object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any])+ #expect(object["cwd"] as? String == "")+}++@Test func existingProjectFolderRemainsExplicit() throws {+ let bot = try JSONDecoder().decode(Bot.self, from: Data(#"{"id":"one","name":"One","cwd":"/projects/app"}"#.utf8))+ #expect(!bot.managedWorkspace)+ #expect(BotDraft(bot).cwd == "/projects/app")+}diff --git a/kit/Tests/CodyncUITests/ComputerSelectionTests.swift b/kit/Tests/CodyncUITests/ComputerSelectionTests.swiftnew file mode 100644index 00000000..4d901b9a--- /dev/null+++ b/kit/Tests/CodyncUITests/ComputerSelectionTests.swift@@ -0,0 +1,33 @@+import Testing+@testable import CodyncUI++@Test func computerFilterSupportsMultipleAndSingleSelections() {+ let all = ["a", "b", "c"]+ let initial = ComputerSelection(all: all, hidden: "")+ #expect(initial.shown == all)+ let withoutB = ComputerSelection(all: all, hidden: initial.toggling("b"))+ #expect(withoutB.shown == ["a", "c"])+ let onlyC = ComputerSelection(all: all, hidden: withoutB.only("c"))+ #expect(onlyC.shown == ["c"])+ #expect(ComputerSelection(all: all, hidden: onlyC.toggling("a")).shown == ["a", "c"])+}++@Test func computerFilterKeepsOneComputerAndRecoversFromRemovedComputers() {+ let single = ComputerSelection(all: ["a", "b"], hidden: "b")+ #expect(ComputerSelection(all: single.all, hidden: single.toggling("a")).shown == ["a"])+ let removed = ComputerSelection(all: ["b", "c"], hidden: "b,c")+ #expect(removed.shown == ["b", "c"])+ #expect(ComputerSelection(all: removed.all, hidden: removed.toggling("b")).shown == ["c"])+ #expect(ComputerSelection(all: ["a", "b", "new"], hidden: "b").shown == ["a", "new"])+ #expect(ComputerSelection(all: [], hidden: "a").shown.isEmpty)+}++@Test func headerSummarizesOnlyTheSelectedConnections() {+ #expect(ConnectionSummary(connections: []).text == "Computers")+ #expect(ConnectionSummary(connections: [.online]).text == "1 connected")+ #expect(ConnectionSummary(connections: [.online, .online]).text == "2 connected")+ #expect(ConnectionSummary(connections: [.online, .computerOffline(lastSeen: nil)]).text == "1/2 connected")+ #expect(ConnectionSummary(connections: [.offline("timeout"), .computerOffline(lastSeen: nil)]).text == "2 offline")+ #expect(ConnectionSummary(connections: [.offline("timeout"), .connecting]).text == "Connecting…")+ #expect(ConnectionSummary(connections: [.unauthorized("revoked")]).text == "No access")+}diff --git a/kit/Tests/CodyncUITests/MarketplacePageTests.swift b/kit/Tests/CodyncUITests/MarketplacePageTests.swiftnew file mode 100644index 00000000..b3ff282b--- /dev/null+++ b/kit/Tests/CodyncUITests/MarketplacePageTests.swift@@ -0,0 +1,43 @@+import Testing+@testable import CodyncUI++private struct CatalogItem: Identifiable { let id: Int }++@Test func catalogStartsSmallAndExpandsOnlyWhenRequested() {+ var page = MarketplacePage<CatalogItem>()+ page.replace(with: (0..<60).map { CatalogItem(id: $0) })+ #expect(page.visible.count == 12)+ #expect(page.hasHiddenItems)+ page.revealMore()+ #expect(page.visible.map(\.id) == Array(0..<24))+ #expect(page.items.count == 60)+}++@Test func catalogEndsAtItsActualCount() {+ var page = MarketplacePage<CatalogItem>()+ page.replace(with: (0..<15).map { CatalogItem(id: $0) })+ page.revealMore()+ #expect(page.visible.count == 15)+ #expect(!page.hasHiddenItems)+}++@Test func laterCatalogPagesStayBoundedAndRemoveDuplicates() {+ var page = MarketplacePage<CatalogItem>()+ page.replace(with: (0..<12).map { CatalogItem(id: $0) })+ page.append((10..<60).map { CatalogItem(id: $0) })+ #expect(page.visible.count == 12)+ page.revealMore()+ #expect(page.visible.map(\.id) == Array(0..<24))+ #expect(page.items.count == 60)+}++@Test func newCatalogSearchResetsTheVisibleBatch() {+ var page = MarketplacePage<CatalogItem>()+ page.replace(with: (0..<60).map { CatalogItem(id: $0) })+ page.revealMore()+ page.replace(with: (100..<130).map { CatalogItem(id: $0) })+ #expect(page.visible.map(\.id) == Array(100..<112))+ page.replace(with: [])+ #expect(page.isEmpty)+ #expect(!page.hasHiddenItems)+}diff --git a/kit/Tests/CodyncUITests/StoreTests.swift b/kit/Tests/CodyncUITests/StoreTests.swiftindex f081417a..29846f3e 100644--- a/kit/Tests/CodyncUITests/StoreTests.swift+++ b/kit/Tests/CodyncUITests/StoreTests.swift@@ -11,12 +11,18 @@ actor FakeRemote: RemoteTransport {private var eventSinks: [AsyncThrowingStream<Data, Error>.Continuation] = []private var mailboxSinks: [AsyncStream<MailboxEvent>.Continuation] = []private(set) var sent: [String] = []+ private(set) var readReceipts: [Data] = []+ private var failReadReceipts = false+ private(set) var readAttempts = 0++ func setReadFailure(_ fail: Bool) { failReadReceipts = fail }private(set) var enqueued: [String] = []var cancelResult = MailboxCancel.cancelledinit(_ state: LinkState) { self.state = state }var subscribed: Bool { !eventSinks.isEmpty }+ var eventSubscriptionCount: Int { eventSinks.count }func set(_ new: LinkState) {state = new@@ -35,6 +41,11 @@ actor FakeRemote: RemoteTransport {switch method {case "hello":return Data(#"{"hostId":"h1","name":"Mac","version":"3.0.0","os":"macos","backends":[],"rev":0}"#.utf8)+ case "markRead":+ readAttempts += 1+ if failReadReceipts { throw HostError.unreachable }+ readReceipts.append(body)+ return Data("{}".utf8)case "send":let b = (try JSONSerialization.jsonObject(with: body) as? [String: String]) ?? [:]sent.append(b["text"] ?? "")@@ -201,6 +212,23 @@ private func botEvent(_ id: String, name: String, rev: Int) -> String {#expect(updates.count == 2)}+@MainActor @Test func computersReorderAndStaySaved() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let a = randomComputer("A"), b = randomComputer("B"), c = randomComputer("C")+ storage.computers = [a, b, c]+ let account = AccountStore(storage: storage, clientKind: "ios", cloud: nil) { computer, route in+ BotStore(computer: computer, route: route, clientKind: "ios", storage: storage) { FakeRemote(.ready(.direct)) }+ }+ account.move(a.id, to: c.id)+ #expect(account.computers.map(\.id) == [b.id, c.id, a.id])+ account.move(a.id, to: b.id)+ #expect(account.computers.map(\.id) == [a.id, b.id, c.id])+ account.move(c.id, to: b.id)+ #expect(storage.computers.map(\.id) == [a.id, c.id, b.id])+ account.retire()+}+@MainActor @Test func attachedComputersAreNotSaved() async throws {let (storage, suite) = context()defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }@@ -226,3 +254,122 @@ private func botEvent(_ id: String, name: String, rev: Int) -> String {extension FakeRemote {func setCancelResult(_ result: MailboxCancel) { cancelResult = result }}+++@MainActor @Test func visibleConversationAcknowledgesEntriesBeforeUnreadAndFinalUpdates() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let fake = FakeRemote(.ready(.direct))+ let store = BotStore(computer: randomComputer("Mac"), route: .channel, clientKind: "ios", storage: storage) { fake }+ store.setActive(true)+ defer { store.setActive(false) }+ #expect(await until { await fake.subscribed })+ await fake.emit(botEvent("b1", name: "Bot", rev: 1))+ #expect(await until { store.connection == .online })+ await fake.emit(botEvent("b1", name: "Bot", rev: 1))+ #expect(await until { store.bots["b1"] != nil })+ let token = UUID()+ store.setReading(token, botId: "b1", thread: nil, active: true)+ #expect(await until { await fake.readReceipts.count == 1 })+ // Streaming and final content have the same ID. The final update must be read+ // even though the roster has not yet reported any unread messages.+ await fake.emit(#"{"type":"entry","entry":{"id":"answer","seq":1,"botId":"b1","rev":2,"kind":"agent","turn":1,"data":{"text":"draft","final":false},"createdAt":1,"updatedAt":1}}"#)+ #expect(await until { store.allEntries("b1").last?.rev == 2 })+ await fake.emit(#"{"type":"entry","entry":{"id":"answer","seq":1,"botId":"b1","rev":3,"kind":"agent","turn":1,"data":{"text":"done","final":true},"createdAt":1,"updatedAt":2}}"#)+ #expect(await until { await fake.readReceipts.count == 2 })+ await fake.emit(#"{"type":"bot","bot":{"id":"b1","name":"Bot","rev":4,"unread":1}}"#)+ #expect(await until { await fake.readReceipts.count == 3 })+ store.setReading(token, botId: "b1", thread: nil, active: false)+ await fake.emit(#"{"type":"bot","bot":{"id":"b1","name":"Bot","rev":5,"unread":2}}"#)+ #expect(await until { store.bots["b1"]?.rev == 5 })+ try await Task.sleep(for: .milliseconds(50))+ #expect(await fake.readReceipts.count == 3)+ // Returning to the foreground acknowledges without needing navigation.+ store.setReading(token, botId: "b1", thread: nil, active: true)+ #expect(await until { await fake.readReceipts.count == 4 })+}++@MainActor @Test func readingOneThreadDoesNotAcknowledgeOtherThreads() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let fake = FakeRemote(.ready(.direct))+ let store = BotStore(computer: randomComputer("Mac"), route: .channel, clientKind: "mac", storage: storage) { fake }+ store.setActive(true)+ defer { store.setActive(false) }+ #expect(await until { await fake.subscribed })+ await fake.emit(botEvent("b1", name: "Bot", rev: 1))+ #expect(await until { store.connection == .online })+ let token = UUID()+ store.setReading(token, botId: "b1", thread: "root-a", active: true)+ #expect(await until { await fake.readReceipts.count == 1 })+ await fake.emit(#"{"type":"entry","entry":{"id":"other","seq":1,"botId":"b1","threadId":"root-b","rev":2,"kind":"agent","turn":1,"data":{"text":"done","final":true},"createdAt":1,"updatedAt":1}}"#)+ #expect(await until { store.allEntries("b1").last?.id == "other" })+ try await Task.sleep(for: .milliseconds(50))+ #expect(await fake.readReceipts.count == 1)+ await fake.emit(#"{"type":"entry","entry":{"id":"own","seq":2,"botId":"b1","threadId":"root-a","rev":3,"kind":"agent","turn":1,"data":{"text":"done","final":true},"createdAt":1,"updatedAt":1}}"#)+ #expect(await until { await fake.readReceipts.count == 2 })+ for receipt in await fake.readReceipts {+ let body = try #require(JSONSerialization.jsonObject(with: receipt) as? [String: Any])+ #expect(body["threadId"] as? String == "root-a")+ #expect(body["all"] as? Bool == false)+ }+}++@MainActor @Test func initialOfflineReportWaitsForReconnect() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let fake = FakeRemote(.hostOffline(lastSeen: nil))+ let store = BotStore(computer: randomComputer("Mac"), route: .channel, clientKind: "ios", storage: storage) { fake }+ defer { store.retire() }+ store.setActive(true)+ try await Task.sleep(for: .milliseconds(200))+ #expect(store.connection == .connecting)+ #expect(store.lastError == nil)+ await fake.set(.ready(.relay))+ #expect(await until { await fake.subscribed })+ await fake.emit(botEvent("b1", name: "Bot", rev: 1))+ #expect(await until { store.connection == .online })+ try await Task.sleep(for: .seconds(1))+ #expect(store.connection == .online)+}++@MainActor @Test func initialUnreachableEventuallyShowsOffline() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let fake = FakeRemote(.failed("Can't reach"))+ let store = BotStore(computer: randomComputer("Mac"), route: .channel, clientKind: "ios", storage: storage) { fake }+ defer { store.retire() }+ store.setActive(true)+ try await Task.sleep(for: .milliseconds(200))+ #expect(store.connection == .connecting)+ #expect(await until { store.connection == .offline("Can't reach") })+ #expect(store.lastError == nil)+}++@MainActor @Test func failedAutomaticReadDoesNotInterruptChatAndRecoversWithTheLink() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let fake = FakeRemote(.ready(.direct))+ let store = BotStore(computer: randomComputer("Mac"), route: .channel, clientKind: "ios", storage: storage) { fake }+ defer { store.retire() }+ store.setActive(true)+ #expect(await until { await fake.subscribed })+ await fake.emit(botEvent("b1", name: "Bot", rev: 1))+ #expect(await until { store.connection == .online })+ await fake.setReadFailure(true)+ store.setReading(UUID(), botId: "b1", thread: nil, active: true)+ #expect(await until { await fake.readAttempts == 1 })+ try await Task.sleep(for: .milliseconds(50))+ #expect(store.lastError == nil)+ await fake.set(.hostOffline(lastSeen: nil))+ #expect(await until { store.hostRoute == nil })+ #expect(store.connection == .online)+ #expect(store.canQueue)+ await fake.setReadFailure(false)+ await fake.set(.ready(.relay))+ #expect(await until { await fake.eventSubscriptionCount == 2 })+ await fake.emit(botEvent("b2", name: "Other bot", rev: 2))+ #expect(await until { await fake.readReceipts.count == 1 })+ #expect(store.connection == .online)+ #expect(store.lastError == nil)+}