Skip to content

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.

Sync in-progress work from the main tree

leepokaif3ee85f1a1f4
diff --git a/apps/ios/Views/AccountSwitcherView.swift b/apps/ios/Views/AccountSwitcherView.swift
index c4aeab37..4e8548d5 100644
--- a/apps/ios/Views/AccountSwitcherView.swift
+++ b/apps/ios/Views/AccountSwitcherView.swift
@@ -24,8 +24,8 @@ struct AccountSwitcherView: View {
@Environment(\.dismiss) private var dismiss
var body: some View {
- Form {
- Section("Accounts") {
+ CardForm {
+ CardSection("Accounts") {
if account.accounts.isEmpty {
Label("Local pairing", systemImage: "person.crop.circle")
.foregroundStyle(Palette.secondary)
@@ -46,7 +46,9 @@ struct AccountSwitcherView: View {
.accessibilityLabel("Current account")
}
}
+ .contentShape(Rectangle())
}
+ .buttonStyle(.plain)
.disabled(account.isBusy)
}
if !account.isSignedIn || account.supportsMultipleAccounts {
@@ -54,48 +56,56 @@ struct AccountSwitcherView: View {
Task { await account.signIn() }
} label: {
Label(account.isSignedIn ? "Add Google account" : "Continue with Google", systemImage: "person.crop.circle.badge.plus")
+ .foregroundStyle(Palette.text)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
}
+ .buttonStyle(.plain)
.disabled(account.isBusy || !account.isConfigured)
}
}
- Section {
+ CardSection(footer: "Computer connections are saved separately for each account on this iPhone. Pair a computer to see its bots.") {
NavigationLink {
SettingsView()
} label: {
- Label("Computers & settings", systemImage: "desktopcomputer")
+ HStack {
+ Label("Computers & settings", systemImage: "desktopcomputer").foregroundStyle(Palette.text)
+ Spacer(minLength: 8)
+ Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Palette.tertiary)
+ }
+ .contentShape(Rectangle())
}
- } footer: {
- Text("Computer connections are saved separately for each account on this iPhone. Pair a computer to see its bots.")
+ .buttonStyle(.plain)
}
if account.isSignedIn {
- Section {
- Button("Sign out of this account", role: .destructive) {
+ CardSection(footer: account.supportsMultipleAccounts ? nil : "Sign out to use a different Google account.") {
+ Button {
Task { await account.signOut() }
+ } label: {
+ Text("Sign out of this account")
+ .foregroundStyle(Palette.danger)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
}
+ .buttonStyle(.plain)
.disabled(account.isBusy)
- } footer: {
- if !account.supportsMultipleAccounts {
- Text("Sign out to use a different Google account.")
- }
}
}
if !account.isConfigured {
- Section {
+ CardSection {
Text("Account sign-in isn't configured in this build. Local pairing is available.")
.foregroundStyle(Palette.secondary)
}
}
if let message = account.errorMessage {
- Section {
+ CardSection {
Text(message).foregroundStyle(Palette.danger)
}
}
}
- .scrollContentBackground(.hidden)
- .background(Palette.background)
.navigationTitle("Accounts")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
diff --git a/apps/ios/Views/ActivityGalleryView.swift b/apps/ios/Views/ActivityGalleryView.swift
index b0691ef8..0c8021ba 100644
--- a/apps/ios/Views/ActivityGalleryView.swift
+++ b/apps/ios/Views/ActivityGalleryView.swift
@@ -1,5 +1,6 @@
import ActivityKit
import CodyncKit
+import CodyncUI
import SwiftUI
struct ActivityGalleryView: View {
@@ -27,6 +28,7 @@ struct ActivityGalleryView: View {
VStack(alignment: .leading, spacing: 24) {
VStack(alignment: .leading, spacing: 10) {
Toggle("Show Live Activities", isOn: $enabled)
+ .toggleStyle(.codync)
.font(.subheadline.weight(.medium))
Text("Starts when you send a task from this iPhone. Follow its progress, then open the conversation when your bot needs you.")
.font(.footnote).foregroundStyle(Palette.secondary)
@@ -45,16 +47,11 @@ struct ActivityGalleryView: View {
Spacer()
Text("Sample task").font(.caption).foregroundStyle(Palette.secondary)
}
- Picker("Presentation", selection: $form) {
- ForEach(BotActivityPreview.Form.allCases, id: \.self) { Text($0.rawValue).tag($0) }
- }.pickerStyle(.menu)
- Picker("Task state", selection: $phase) {
- Text("Working").tag(BotActivityPresentation.Phase.working)
- Text("Needs you").tag(BotActivityPresentation.Phase.needsInput)
- Text("Done").tag(BotActivityPresentation.Phase.completed)
- Text("Error").tag(BotActivityPresentation.Phase.failed)
- Text("Update delayed").tag(BotActivityPresentation.Phase.stale)
- }.pickerStyle(.menu)
+ ChoicePicker(selection: $form, options: BotActivityPreview.Form.allCases.map { ($0, $0.rawValue) })
+ ChoicePicker(selection: $phase, options: [
+ (.working, "Working"), (.needsInput, "Needs you"), (.completed, "Done"),
+ (.failed, "Error"), (.stale, "Update delayed"),
+ ])
if let bot = Bot.widgetPreview.first {
BotActivityPreview(bot: bot, state: state, form: form)
.frame(maxWidth: .infinity, minHeight: 90)
@@ -97,10 +94,7 @@ struct LockWidgetGalleryView: View {
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 22) {
- Picker("Widget", selection: $kind) {
- Text("Bots").tag("bots")
- Text("Usage limits").tag("usage")
- }.pickerStyle(.menu)
+ ChoicePicker(selection: $kind, options: [("bots", "Bots"), ("usage", "Usage limits")])
Text("Sample data").font(.caption).foregroundStyle(Palette.secondary)
ForEach(AccessoryWidgetCard.Family.allCases, id: \.self) { family in
VStack(alignment: .leading, spacing: 10) {
diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swift
index 172ed29e..5495b8d6 100644
--- a/apps/ios/Views/BotListView.swift
+++ b/apps/ios/Views/BotListView.swift
@@ -10,50 +10,34 @@ struct BotListView: View {
var body: some View {
let roster = model.roster
- List {
- Section {
+ ScrollView {
+ LazyVStack(spacing: 0) {
ConnectionBanner()
- }
- .listRowSeparator(.hidden)
- .listRowBackground(Color.clear)
- .listRowInsets(EdgeInsets(top: 4, leading: 16, bottom: 4, trailing: 16))
-
- if roster.isEmpty {
- EmptyRoster { editing = EditorRequest(BotDraft()) }
- .listRowSeparator(.hidden)
- .listRowBackground(Color.clear)
- }
+ .padding(.vertical, 4)
- ForEach(roster) { bot in
- // A plain button instead of a NavigationLink: same push, no chevron.
- Button { model.selection = bot.id } label: {
- BotRow(bot: bot)
+ if roster.isEmpty {
+ EmptyRoster { editing = EditorRequest(BotDraft()) }
}
- .buttonStyle(.plain)
- .listRowBackground(Palette.background)
- .listRowSeparator(.hidden)
- .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
- .swipeActions(edge: .leading) {
- Button(bot.pinned ? "Unpin" : "Pin", systemImage: bot.pinned ? "pin.slash" : "pin") {
- model.setPinned(bot, !bot.pinned)
+
+ ForEach(roster) { bot in
+ // A plain button instead of a NavigationLink: same push, no chevron.
+ Button { model.selection = bot.id } label: {
+ BotRow(bot: bot)
+ }
+ .buttonStyle(.plain)
+ .contextActions {
+ [
+ MenuItem(bot.pinned ? "Unpin" : "Pin", icon: bot.pinned ? "pin.slash" : "pin") { model.setPinned(bot, !bot.pinned) },
+ MenuItem("Edit profile", icon: "pencil") { editing = EditorRequest(BotDraft(bot)) },
+ MenuItem("Mark as read", icon: "checkmark.message") { model.markRead(bot.id) },
+ MenuItem("Hide from list", icon: "eye.slash") { model.setHidden(bot, true) },
+ MenuItem("Delete", icon: "trash", destructive: true, divider: true) { confirmDelete = bot },
+ ]
}
- .tint(Palette.accentDim)
- }
- .swipeActions(edge: .trailing) {
- Button("Delete", systemImage: "trash", role: .destructive) { confirmDelete = bot }
- Button("Hide", systemImage: "eye.slash") { model.setHidden(bot, true) }
- }
- .contextMenu {
- Button(bot.pinned ? "Unpin" : "Pin", systemImage: "pin") { model.setPinned(bot, !bot.pinned) }
- Button("Edit profile", systemImage: "pencil") { editing = EditorRequest(BotDraft(bot)) }
- Button("Mark as read", systemImage: "checkmark.message") { model.markRead(bot.id) }
- Button("Hide from list", systemImage: "eye.slash") { model.setHidden(bot, true) }
- Button("Delete", systemImage: "trash", role: .destructive) { confirmDelete = bot }
}
}
+ .padding(.horizontal, 16)
}
- .listStyle(.plain)
- .scrollContentBackground(.hidden)
.background(Palette.background)
.navigationTitle(model.hostName)
.navigationBarTitleDisplayMode(.inline)
@@ -104,9 +88,7 @@ private struct EmptyRoster: View {
.foregroundStyle(Palette.secondary)
.multilineTextAlignment(.center)
Button("Create your first bot", action: create)
- .buttonStyle(.borderedProminent)
- .tint(Palette.accentFill)
- .foregroundStyle(Palette.onAccent)
+ .buttonStyle(.primary)
}
.frame(maxWidth: .infinity)
.padding(.vertical, 40)
diff --git a/apps/ios/Views/PairingView.swift b/apps/ios/Views/PairingView.swift
index c2aaf7cc..76d877b5 100644
--- a/apps/ios/Views/PairingView.swift
+++ b/apps/ios/Views/PairingView.swift
@@ -56,9 +56,7 @@ struct PairingView: View {
.font(.headline)
.frame(maxWidth: .infinity, minHeight: 50)
}
- .buttonStyle(.borderedProminent)
- .tint(Palette.accentFill)
- .foregroundStyle(Palette.onAccent)
+ .buttonStyle(.primary)
.disabled(!DataScannerViewController.isSupported)
HStack {
@@ -73,7 +71,6 @@ struct PairingView: View {
}
.padding(12)
.background(Palette.surface, in: RoundedRectangle(cornerRadius: 12))
- .overlay(RoundedRectangle(cornerRadius: 12).stroke(Palette.border))
if let error {
Text(error).font(.footnote).foregroundStyle(Palette.danger)
@@ -146,7 +143,6 @@ private struct Step: View {
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 8))
- .overlay(RoundedRectangle(cornerRadius: 8).stroke(Palette.border))
}
}
}
diff --git a/apps/ios/Views/SettingsView.swift b/apps/ios/Views/SettingsView.swift
index 88379cab..f9111123 100644
--- a/apps/ios/Views/SettingsView.swift
+++ b/apps/ios/Views/SettingsView.swift
@@ -12,91 +12,75 @@ struct SettingsView: View {
@State private var confirmForget: Pairing?
var body: some View {
- Form {
- Section {
+ CardForm {
+ CardSection("Computers on this iPhone", footer: "Each bot runs on its own computer. Tap a computer to view its bots.") {
ForEach(model.computers, id: \.token) { computer in
- ComputerRow(computer: computer, active: computer.token == model.pairing?.token)
- .contentShape(Rectangle())
- .onTapGesture { if computer.token != model.pairing?.token { model.pair(computer) } }
- .swipeActions {
- Button("Remove", systemImage: "trash", role: .destructive) { confirmForget = computer }
- }
- .contextMenu {
- Menu("Color", systemImage: "paintpalette") {
- ForEach(AvatarPalette.colors) { swatch in
- Button { model.setColor(computer, swatch.id) } label: {
- // Menus drop SwiftUI tints; an original-mode UIImage keeps the swatch colored.
- Label {
- Text(swatch.label)
- } icon: {
- Image(uiImage: UIImage(systemName: computer.color == swatch.id ? "checkmark.circle.fill" : "circle.fill")!
- .withTintColor(UIColor(swatch.color), renderingMode: .alwaysOriginal))
- }
- }
- }
- }
- Button("Remove", systemImage: "trash", role: .destructive) { confirmForget = computer }
- }
+ ComputerRow(computer: computer, active: computer.token == model.pairing?.token) { confirmForget = computer }
}
Button {
addingComputer = true
} label: {
Label("Add a computer", systemImage: "plus")
.foregroundStyle(Palette.text)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
}
- } header: {
- Text("Computers on this iPhone")
- } footer: {
- Text("Each bot runs on its own computer. Tap a computer to view its bots.")
+ .buttonStyle(.plain)
}
- Section {
+ CardSection {
NavigationLink {
MarketplaceView()
} label: {
- VStack(alignment: .leading, spacing: 2) {
- Text("Marketplace")
- Text("Agents, connectors and skills for your bots").font(.subheadline).foregroundStyle(Palette.secondary)
+ LinkRow {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Marketplace")
+ Text("Agents, connectors and skills for your bots").font(.subheadline).foregroundStyle(Palette.secondary)
+ }
}
}
+ .buttonStyle(.plain)
}
- Section {
+ CardSection {
NavigationLink {
WidgetGalleryView()
} label: {
- Label("Widgets", systemImage: "square.grid.2x2")
+ LinkRow { Label("Widgets", systemImage: "square.grid.2x2") }
}
+ .buttonStyle(.plain)
NavigationLink { ActivityGalleryView() } label: {
- Label("Live Activity & Dynamic Island", systemImage: "waveform")
+ LinkRow { Label("Live Activity & Dynamic Island", systemImage: "waveform") }
}
+ .buttonStyle(.plain)
notificationsRow
}
if !model.hiddenBots.isEmpty {
- Section("Hidden bots") {
+ CardSection("Hidden bots") {
ForEach(model.hiddenBots) { bot in
HStack {
CharacterAvatar(bot: bot, size: 28, animated: false)
Text(bot.name)
Spacer()
- Button("Unhide", systemImage: "eye") { model.setHidden(bot, false) }.labelStyle(.iconOnly)
+ Button("Unhide", systemImage: "eye") { model.setHidden(bot, false) }
+ .labelStyle(.iconOnly)
+ .buttonStyle(.plain)
+ .foregroundStyle(Palette.text)
}
}
}
}
- Section {
+ CardSection {
if let hello = model.hello {
- LabeledContent("Host version", value: hello.version)
+ ValueRow("Host version", value: hello.version)
}
- LabeledContent("App version", value: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "")
+ ValueRow("App version", value: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "")
Link("Source code", destination: URL(string: "https://github.com/leepokai/Codync")!)
.foregroundStyle(Palette.text)
}
}
- .scrollContentBackground(.hidden)
- .background(Palette.background)
.navigationTitle("Computers & settings")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
@@ -107,13 +91,13 @@ struct SettingsView: View {
.sheet(isPresented: $addingComputer) {
PairingView(introductory: false) { addingComputer = false }
}
- .confirmationDialog("Remove \(confirmForget?.name ?? "computer")?", isPresented: Binding(get: { confirmForget != nil }, set: { if !$0 { confirmForget = nil } }), titleVisibility: .visible) {
- Button("Remove", role: .destructive) {
+ .codyncDialog("Remove \(confirmForget?.name ?? "computer")?",
+ isPresented: Binding(get: { confirmForget != nil }, set: { if !$0 { confirmForget = nil } }),
+ message: "Its bots and conversations stay on that computer. You can pair again any time.") {
+ [DialogAction("Remove", destructive: true) {
if let c = confirmForget { model.forget(c) }
if model.pairing == nil { dismiss() }
- }
- } message: {
- Text("Its bots and conversations stay on that computer. You can pair again any time.")
+ }]
}
.task {
let status = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus
@@ -127,7 +111,7 @@ struct SettingsView: View {
@ViewBuilder private var notificationsRow: some View {
if notificationsAllowed == true {
- LabeledContent("Notifications", value: "On")
+ ValueRow("Notifications", value: "On")
} else {
Button {
if notificationsAllowed == false {
@@ -136,9 +120,10 @@ struct SettingsView: View {
Task { notificationsAllowed = await PushRegistrar.shared.requestAuthorization() }
}
} label: {
- LabeledContent("Notifications", value: notificationsAllowed == false ? "Off in Settings" : "Turn on")
- .foregroundStyle(Palette.text)
+ ValueRow("Notifications", value: notificationsAllowed == false ? "Off in Settings" : "Turn on")
+ .contentShape(Rectangle())
}
+ .buttonStyle(.plain)
}
}
}
@@ -146,7 +131,9 @@ struct SettingsView: View {
private struct ComputerRow: View {
let computer: Pairing
let active: Bool
+ let onRemove: () -> Void
@Environment(BotStore.self) private var model
+ @State private var coloring = false
var body: some View {
HStack(spacing: 12) {
@@ -159,7 +146,7 @@ private struct ComputerRow: View {
if !active || model.screen != nil {
Button("Screen", systemImage: "display") { openScreen() }
.labelStyle(.iconOnly)
- .buttonStyle(.borderless)
+ .buttonStyle(.plain)
.foregroundStyle(Palette.text)
}
if active {
@@ -167,6 +154,30 @@ private struct ComputerRow: View {
}
}
.padding(.vertical, 2)
+ .contentShape(Rectangle())
+ .onTapGesture { if !active { model.pair(computer) } }
+ .contextActions {
+ [
+ MenuItem("Color", icon: "paintpalette") {
+ // ponytail: waits for the menu popover to close before opening the swatches; one popover at a time.
+ Task {
+ try? await Task.sleep(for: .milliseconds(350))
+ coloring = true
+ }
+ },
+ MenuItem("Remove", icon: "trash", destructive: true, divider: true, action: onRemove),
+ ]
+ }
+ .background {
+ Color.clear.popover(isPresented: $coloring, arrowEdge: .bottom) {
+ SwatchPanel(selected: computer.color) { id in
+ coloring = false
+ model.setColor(computer, id)
+ }
+ .presentationCompactAdaptation(.popover)
+ .presentationBackground(Palette.bubbleAgent)
+ }
+ }
}
/// Only the active computer is connected: switch to this one first, then open its screen.
@@ -190,3 +201,43 @@ private struct ComputerRow: View {
}
}
}
+
+/// A navigation row label with a trailing chevron.
+private struct LinkRow<Content: View>: View {
+ @ViewBuilder let content: Content
+
+ var body: some View {
+ HStack {
+ content.foregroundStyle(Palette.text)
+ Spacer(minLength: 8)
+ Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Palette.tertiary)
+ }
+ .contentShape(Rectangle())
+ }
+}
+
+/// The computer color choices: a grid of colored dots, the current one checked.
+private struct SwatchPanel: View {
+ let selected: String?
+ let pick: (String) -> Void
+
+ var body: some View {
+ LazyVGrid(columns: Array(repeating: GridItem(.fixed(36), spacing: 10), count: 6), spacing: 10) {
+ ForEach(AvatarPalette.colors) { swatch in
+ Button { pick(swatch.id) } label: {
+ Circle().fill(swatch.color)
+ .frame(width: 32, height: 32)
+ .overlay {
+ if selected == swatch.id {
+ Image(systemName: "checkmark").font(.caption.weight(.bold)).foregroundStyle(.white)
+ }
+ }
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(swatch.label)
+ .accessibilityAddTraits(selected == swatch.id ? .isSelected : [])
+ }
+ }
+ .padding(14)
+ }
+}
diff --git a/apps/ios/Views/UsageView.swift b/apps/ios/Views/UsageView.swift
index 3a41c112..1a5f82ad 100644
--- a/apps/ios/Views/UsageView.swift
+++ b/apps/ios/Views/UsageView.swift
@@ -18,11 +18,18 @@ struct UsageView: View {
))
}
if model.usage.providers.isEmpty {
- ContentUnavailableView("No usage yet", systemImage: "chart.bar",
- description: Text("Your computer reads the limits from Claude Code and Codex."))
- .padding(.top, 60)
+ VStack(spacing: 8) {
+ Image(systemName: "chart.bar").font(.system(size: 40)).foregroundStyle(Palette.tertiary)
+ Text("No usage yet").font(.title3.weight(.semibold)).foregroundStyle(Palette.text)
+ Text("Your computer reads the limits from Claude Code and Codex.")
+ .font(.subheadline).foregroundStyle(Palette.secondary)
+ }
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: .infinity)
+ .padding(.top, 60)
}
Button("Widgets & setup") { widgetHelp = true }
+ .buttonStyle(.plain)
.font(.subheadline.weight(.medium))
.foregroundStyle(Palette.secondary)
.padding(.top, 4)
@@ -63,6 +70,7 @@ private struct ProviderCard: View {
withAnimation(.snappy) { collapsed.toggle() }
}
.labelStyle(.iconOnly)
+ .buttonStyle(.plain)
.rotationEffect(.degrees(collapsed ? 180 : 0))
.foregroundStyle(Palette.tertiary)
}
diff --git a/apps/ios/Views/WidgetGalleryView.swift b/apps/ios/Views/WidgetGalleryView.swift
index 84bdc8d1..77ac807a 100644
--- a/apps/ios/Views/WidgetGalleryView.swift
+++ b/apps/ios/Views/WidgetGalleryView.swift
@@ -63,20 +63,15 @@ struct WidgetGalleryView: View {
Text("Sample data").font(.caption2).foregroundStyle(Palette.secondary)
}
if typeSize.isAccessibilitySize {
- kindPicker.pickerStyle(.menu)
- if kind == "usage" { providerPicker.pickerStyle(.menu) }
+ ChoicePicker(selection: $kind, options: Self.kinds)
+ if kind == "usage" { ChoicePicker(selection: $providerID, options: Self.providers) }
} else {
- kindPicker.pickerStyle(.segmented)
+ SegmentedChoice(selection: $kind, options: Self.kinds)
if kind == "usage" {
- providerPicker.pickerStyle(.segmented)
+ SegmentedChoice(selection: $providerID, options: Self.providers)
}
}
- Picker("Size", selection: $size) {
- Text("Small").tag("small")
- Text("Medium").tag("medium")
- Text("Large").tag("large")
- }
- .pickerStyle(.menu)
+ ChoicePicker(selection: $size, options: [("small", "Small"), ("medium", "Medium"), ("large", "Large")])
VStack(spacing: 18) {
preview(wide: size != "small")
.frame(width: size == "small" ? 158 : nil, height: size == "large" ? 338 : 158)
@@ -118,19 +113,8 @@ struct WidgetGalleryView: View {
.onChange(of: scenePhase) { _, phase in if phase == .active { checkWidgets() } }
}
- private var kindPicker: some View {
- Picker("Widget", selection: $kind) {
- Text("Provider usage").tag("usage")
- Text("Bots").tag("bots")
- }
- }
-
- private var providerPicker: some View {
- Picker("Provider", selection: $providerID) {
- Text("Claude").tag("claude")
- Text("Codex").tag("codex")
- }
- }
+ private static let kinds: [(id: String, label: String)] = [("usage", "Provider usage"), ("bots", "Bots")]
+ private static let providers: [(id: String, label: String)] = [("claude", "Claude"), ("codex", "Codex")]
private var previewDescription: some View {
VStack(alignment: .leading, spacing: 6) {
diff --git a/apps/macos/App/CodyncMacApp.swift b/apps/macos/App/CodyncMacApp.swift
index 0817e0a6..836f81fb 100644
--- a/apps/macos/App/CodyncMacApp.swift
+++ b/apps/macos/App/CodyncMacApp.swift
@@ -39,6 +39,7 @@ struct MenuView: View {
@Environment(HostController.self) private var host
@Environment(\.openWindow) private var openWindow
@State private var showPairing = false
+ @State private var showSettings = false
var body: some View {
VStack(alignment: .leading, spacing: 0) {
@@ -128,14 +129,12 @@ struct MenuView: View {
.foregroundStyle(Palette.secondary)
.fixedSize(horizontal: false, vertical: true)
Button("Install host") { host.install() }
- .buttonStyle(.borderedProminent)
- .tint(Palette.accentFill)
- .foregroundStyle(Palette.onAccent)
+ .buttonStyle(.primary)
}
.tile()
case .starting:
HStack(spacing: 8) {
- ProgressView().controlSize(.small)
+ Spinner(size: 12)
Text("Connecting…").font(.caption).foregroundStyle(Palette.secondary)
}
.frame(maxWidth: .infinity)
@@ -147,7 +146,7 @@ struct MenuView: View {
Button("Restart host") { host.restart() }
Button("Open log") { NSWorkspace.shared.open(host.logURL) }
}
- .controlSize(.small)
+ .buttonStyle(.secondary)
}
.tile()
case .running:
@@ -205,21 +204,16 @@ struct MenuView: View {
Text("v\(version)").font(.caption2.monospacedDigit()).foregroundStyle(Palette.tertiary).padding(.leading, 6)
}
Spacer()
- Menu {
- Toggle("Open at login", isOn: Binding(get: { host.launchAtLogin }, set: { host.setLaunchAtLogin($0) }))
- Divider()
- Button("Restart host") { host.restart() }
- Button("Open log") { NSWorkspace.shared.open(host.logURL) }
- Divider()
- Button("Uninstall host service") { host.uninstall() }
- } label: {
- Image(systemName: "gearshape")
- }
- .menuStyle(.button)
- .buttonStyle(IconButtonStyle())
- .menuIndicator(.hidden)
- .fixedSize()
- .help("Settings")
+ // The DropdownMenu shape, but kept on IconButton so the gear hovers like its neighbours.
+ IconButton("Settings", systemImage: "gearshape", selected: showSettings) { showSettings.toggle() }
+ .codyncMenu(isPresented: $showSettings) {
+ [
+ MenuItem("Open at login", selected: host.launchAtLogin) { host.setLaunchAtLogin(!host.launchAtLogin) },
+ MenuItem("Restart host", divider: true) { host.restart() },
+ MenuItem("Open log") { NSWorkspace.shared.open(host.logURL) },
+ MenuItem("Uninstall host service", divider: true) { host.uninstall() },
+ ]
+ }
IconButton("Quit Codync", systemImage: "power") { NSApp.terminate(nil) }
}
.padding(.horizontal, 10)
@@ -259,12 +253,10 @@ private struct RemoteScreenSection: View {
.fixedSize(horizontal: false, vertical: true)
}
Spacer(minLength: 8)
- Toggle("Remote screen", isOn: Binding(get: { screen.enabled }, set: { host.setRemoteScreen($0) }))
- .labelsHidden()
- .toggleStyle(.switch)
- .controlSize(.mini)
- // Grey, not blue: a white track would hide the white knob.
- .tint(Palette.secondary)
+ Toggle(isOn: Binding(get: { screen.enabled }, set: { host.setRemoteScreen($0) })) { EmptyView() }
+ .toggleStyle(.codync)
+ .fixedSize()
+ .accessibilityLabel("Remote screen")
}
if screen.enabled {
if host.screenAgentNeedsApproval {
@@ -440,7 +432,7 @@ private struct PairingPanel: View {
NSPasteboard.general.setString(info.pairingUrl, forType: .string)
}
} else {
- ProgressView()
+ Spinner(size: 20)
}
}
.frame(maxWidth: .infinity)
@@ -473,7 +465,7 @@ private struct TailscaleTip: View {
.foregroundStyle(Palette.tertiary)
.multilineTextAlignment(.center)
if installed {
- Button("Open Tailscale") { NSWorkspace.shared.open(Self.app) }.controlSize(.small)
+ Button("Open Tailscale") { NSWorkspace.shared.open(Self.app) }.buttonStyle(.secondary)
} else {
Link("Get Tailscale", destination: Tailscale.downloadURL).font(.caption)
}
diff --git a/apps/macos/Views/ChatWindow.swift b/apps/macos/Views/ChatWindow.swift
index 376c49ac..eee13f6d 100644
--- a/apps/macos/Views/ChatWindow.swift
+++ b/apps/macos/Views/ChatWindow.swift
@@ -302,15 +302,12 @@ private struct ChatSplitView: View {
sidebarWidth = min(sidebarWidth, max(260, $0.width - 420))
}
.hiddenWindowTitle()
- .confirmationDialog("Start a new session?", isPresented: Binding(
+ .codyncDialog("Start a new session?", isPresented: Binding(
get: { newSessionBot != nil },
set: { if !$0 { newSessionBot = nil } }
- ), titleVisibility: .visible) {
- if let bot = newSessionBot {
- Button("New session") { model.newSession(bot.id); newSessionBot = nil }
- }
- } message: {
- Text("The conversation stays here, but the agent starts with a fresh context.")
+ ), message: "The conversation stays here, but the agent starts with a fresh context.") {
+ guard let bot = newSessionBot else { return [] }
+ return [DialogAction("New session") { model.newSession(bot.id); newSessionBot = nil }]
}
.deleteBotConfirmation($confirmDelete)
.storeErrorAlert(model)
@@ -403,7 +400,6 @@ extension ChatSplitView {
.padding(.horizontal, 9)
.frame(height: 28)
.background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 8))
- .overlay(RoundedRectangle(cornerRadius: 8).stroke(Palette.border, lineWidth: 0.5))
.padding(.horizontal, 12)
.padding(.top, 4)
.padding(.bottom, 8)
@@ -421,8 +417,7 @@ extension ChatSplitView {
.frame(width: 28, height: 28)
.background(Palette.bubbleUser, in: Circle())
.clipShape(Circle())
- .overlay(Circle().strokeBorder(Palette.text.opacity(0.08), lineWidth: 0.5))
- .overlay { if account.isBusy { ProgressView().controlSize(.small) } }
+ .overlay { if account.isBusy { Spinner(size: 14) } }
.accessibilityHidden(true)
}
@@ -443,7 +438,6 @@ extension ChatSplitView {
.font(.system(size: 14, weight: .regular))
.frame(width: 30, height: 30)
.background(Palette.text.opacity(0.025), in: Circle())
- .overlay(Circle().strokeBorder(Palette.text.opacity(0.1), lineWidth: 0.5))
Text("Marketplace")
Spacer(minLength: 0)
}
@@ -625,7 +619,6 @@ private struct SidebarAccountPanel: View {
menuContent
.padding(7)
.background(Color(light: 0xFAFAFA, dark: 0x1B1B1B), in: RoundedRectangle(cornerRadius: 18))
- .overlay(RoundedRectangle(cornerRadius: 18).strokeBorder(Palette.text.opacity(0.15), lineWidth: 0.5))
.shadow(color: .black.opacity(0.25), radius: 20, x: 0, y: 8)
.accessibilityElement(children: .contain)
.accessibilityLabel("Account menu")
@@ -765,7 +758,6 @@ private struct DesktopActionMenu: View {
}
.padding(7)
.background(Color(light: 0xFAFAFA, dark: 0x1B1B1B), in: RoundedRectangle(cornerRadius: 14))
- .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Palette.text.opacity(0.15), lineWidth: 0.5))
.shadow(color: .black.opacity(0.25), radius: 20, x: 0, y: 8)
.accessibilityElement(children: .contain)
.accessibilityLabel("Conversation actions")
@@ -789,31 +781,3 @@ private struct DesktopActionMenu: View {
items[index].action()
}
}
-
-/// Intercepts only secondary clicks; primary clicks, scrolling and dragging pass through.
-private struct SecondaryClickCapture: NSViewRepresentable {
- let onClick: (CGPoint) -> Void
-
- func makeNSView(context: Context) -> CaptureView { CaptureView(onClick: onClick) }
- func updateNSView(_ view: CaptureView, context: Context) { view.onClick = onClick }
-
- final class CaptureView: NSView {
- var onClick: (CGPoint) -> Void
- override var isFlipped: Bool { true }
-
- init(onClick: @escaping (CGPoint) -> Void) {
- self.onClick = onClick
- super.init(frame: .zero)
- }
- required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
-
- override func hitTest(_ point: NSPoint) -> NSView? {
- guard let event = NSApp.currentEvent,
- event.type == .rightMouseDown || (event.type == .leftMouseDown && event.modifierFlags.contains(.control))
- else { return nil }
- return super.hitTest(point)
- }
- override func rightMouseDown(with event: NSEvent) { onClick(convert(event.locationInWindow, from: nil)) }
- override func mouseDown(with event: NSEvent) { onClick(convert(event.locationInWindow, from: nil)) }
- }
-}
diff --git a/host/src/api.rs b/host/src/api.rs
index 7bc694b2..5001e420 100644
--- a/host/src/api.rs
+++ b/host/src/api.rs
@@ -107,6 +107,26 @@ fn str_arg<'a>(b: &'a Value, k: &str) -> Result<&'a str> {
pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {
Ok(match method {
+ "composioCall" => {
+ json!({"result": crate::composio::call(&hub.store, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"]).await?})
+ }
+ "composioStatus" => crate::composio::status(&hub.store),
+ "setComposioKey" => crate::composio::set_key(&hub.store, b["key"].as_str().unwrap_or_default()).await?,
+ "composioToolkits" => {
+ crate::composio::toolkits(
+ &hub.store,
+ b["search"].as_str().unwrap_or_default(),
+ b["cursor"].as_str().unwrap_or_default(),
+ )
+ .await?
+ }
+ "composioConnect" => crate::composio::connect(&hub.store, str_arg(&b, "toolkit")?).await?,
+ "composioConnectFields" => {
+ let fields = b["fields"].as_object().ok_or_else(|| anyhow!("`fields` is required"))?;
+ crate::composio::connect_with_fields(&hub.store, str_arg(&b, "toolkit")?, str_arg(&b, "mode")?, fields)
+ .await?
+ }
+ "composioConnection" => crate::composio::connection(&hub.store, str_arg(&b, "id")?).await?,
"teamCall" => crate::team::call(hub, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"]).await?,
"hello" => {
let port = hub.port;
@@ -272,7 +292,11 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {
json!({"connector": c})
}
"removeConnector" => {
- market::remove_connector(&hub.store, str_arg(&b, "id")?)?;
+ let id = str_arg(&b, "id")?;
+ match id.strip_prefix(crate::composio::PREFIX) {
+ Some(toolkit) => crate::composio::disconnect(&hub.store, toolkit).await?,
+ None => market::remove_connector(&hub.store, id)?,
+ }
json!({})
}
"skills" => market::list_skills(&hub.store),
diff --git a/host/src/bot.rs b/host/src/bot.rs
index ffccbf30..8b52da32 100644
--- a/host/src/bot.rs
+++ b/host/src/bot.rs
@@ -459,7 +459,9 @@ impl Actor {
all.iter().filter(|c| self.cfg.connectors.contains(&c.id)).filter_map(|c| c.acp(http_ok)).collect();
match std::env::current_exe() {
Ok(exe) => {
- for name in [Some("team"), self.cfg.computer.then_some("computer")].into_iter().flatten() {
+ let composio = crate::composio::enabled_for(&self.hub.store, &self.cfg.connectors);
+ let builtin = [Some("team"), self.cfg.computer.then_some("computer"), composio.then_some("composio")];
+ for name in builtin.into_iter().flatten() {
servers.push(json!({
"name": name, "command": exe,
"args": ["mcp", name, "--bot", self.cfg.id, "--port", self.hub.port.to_string()],
diff --git a/host/src/composio.rs b/host/src/composio.rs
new file mode 100644
index 00000000..dfcc339e
--- /dev/null
+++ b/host/src/composio.rs
@@ -0,0 +1,530 @@
+//! Composio (<https://composio.dev>): hosted sign-in and tools for ~1,000 apps
+//! (Gmail, Slack, GitHub, Notion…), as Marketplace connectors.
+//!
+//! The user pastes a Composio API key once. Connecting an app goes through
+//! Composio's hosted auth link (OAuth works from the phone: Composio owns the
+//! callback) or, for key-based apps, a form whose fields the toolkit declares.
+//! Each connected app shows up as a connector `composio-<toolkit>`; a bot with
+//! some turned on gets the built-in `composio` MCP server, limited to those
+//! apps, which searches, describes and runs their tools through this host.
+//! The key never leaves the computer.
+
+use crate::store::Store;
+use anyhow::{Context, Result, anyhow, bail};
+use serde::{Deserialize, Serialize};
+use serde_json::{Value, json};
+use std::time::Duration;
+
+const API: &str = "https://backend.composio.dev/api/v3.1";
+const TIMEOUT: Duration = Duration::from_secs(30);
+/// Connector ids for Composio apps: `composio-<toolkit slug>`.
+pub const PREFIX: &str = "composio-";
+const SLOT: &str = "composio";
+pub const KEY_URL: &str = "https://platform.composio.dev";
+
+pub const INSTRUCTIONS: &str = "Act in the user's connected apps through Composio. Find a tool with \
+`search_tools`, read its parameters with `get_tool`, then run it with `execute`. Tool slugs look like \
+GMAIL_SEND_EMAIL. Only the apps listed by `list_apps` are available to you.";
+
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct Config {
+ key: String,
+ /// Composio's "user": one per computer.
+ user_id: String,
+ #[serde(default)]
+ connections: Vec<Connection>,
+}
+
+/// A connected account, cached so connector listings work offline.
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct Connection {
+ /// Composio's connected account id.
+ pub id: String,
+ pub toolkit: String,
+ pub name: String,
+ #[serde(default)]
+ pub logo: Option<String>,
+ /// Composio's status, lowercased (`active`, `initiated`, `failed`, `expired`…).
+ pub status: String,
+}
+
+impl Connection {
+ pub fn active(&self) -> bool {
+ self.status == "active"
+ }
+}
+
+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 save(store: &Store, c: &Config) -> Result<()> {
+ store.kv_set(SLOT, &serde_json::to_string(c)?)
+}
+
+fn config(store: &Store) -> Result<Config> {
+ 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()
+}
+
+async fn request(
+ key: &str,
+ method: reqwest::Method,
+ path: &str,
+ query: &[(&str, &str)],
+ body: Option<&Value>,
+) -> Result<Value> {
+ let url = reqwest::Url::parse_with_params(&format!("{API}{path}"), query)?;
+ let mut req = crate::http().request(method.clone(), url).header("x-api-key", key).timeout(TIMEOUT);
+ if let Some(body) = body {
+ req = req.json(body);
+ }
+ let res = req.send().await.with_context(|| format!("can't reach Composio ({method} {path})"))?;
+ let status = res.status();
+ 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: {msg} ({status})");
+ }
+ Ok(v)
+}
+
+async fn get(key: &str, path: &str, query: &[(&str, &str)]) -> Result<Value> {
+ request(key, reqwest::Method::GET, path, query, None).await
+}
+
+async fn post(key: &str, path: &str, body: &Value) -> Result<Value> {
+ request(key, reqwest::Method::POST, path, &[], Some(body)).await
+}
+
+fn text(v: &Value) -> Option<String> {
+ v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
+}
+
+/// Lowercase letters, digits, `_` and `-`: toolkit and tool slugs go into URLs.
+fn checked_slug(s: &str) -> Result<&str> {
+ let ok = !s.is_empty() && s.len() <= 100 && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
+ if ok { Ok(s) } else { bail!("`{s}` isn't a Composio slug") }
+}
+
+/// `google_calendar` → `Google Calendar`.
+fn title_case(s: &str) -> String {
+ s.split(['_', '-'])
+ .filter(|w| !w.is_empty())
+ .map(|w| {
+ let mut c = w.chars();
+ c.next().map(|f| f.to_uppercase().chain(c).collect::<String>()).unwrap_or_default()
+ })
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+// MARK: setup
+
+pub fn status(store: &Store) -> Value {
+ 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));
+ }
+ 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());
+ }
+ save(store, &c)?;
+ refresh(store).await?;
+ Ok(status(store))
+}
+
+/// Re-reads this computer's connected accounts from Composio.
+pub async fn refresh(store: &Store) -> Result<Vec<Connection>> {
+ let mut c = config(store)?;
+ let v = get(&c.key, "/connected_accounts", &[("user_ids", &c.user_id), ("limit", "200")]).await?;
+ let mut list: Vec<Connection> = v["items"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ // Belt and braces: the filter is a query parameter Composio could ignore.
+ .filter(|a| a["user_id"].as_str().is_none_or(|u| u == c.user_id))
+ .filter_map(|a| {
+ Some(Connection {
+ id: text(&a["id"])?,
+ toolkit: text(&a["toolkit"]["slug"])?.to_lowercase(),
+ name: text(&a["toolkit"]["name"]).unwrap_or_default(),
+ logo: text(&a["toolkit"]["logo"]),
+ status: text(&a["status"]).unwrap_or_default().to_lowercase(),
+ })
+ })
+ .collect();
+ // Names and logos from the toolkit list when the account listing omits them.
+ for conn in &mut list {
+ if let Some(old) = c.connections.iter().find(|o| o.toolkit == conn.toolkit) {
+ if conn.name.is_empty() {
+ conn.name.clone_from(&old.name);
+ }
+ if conn.logo.is_none() {
+ conn.logo.clone_from(&old.logo);
+ }
+ }
+ if conn.name.is_empty() {
+ conn.name = title_case(&conn.toolkit);
+ }
+ }
+ c.connections.clone_from(&list);
+ save(store, &c)?;
+ Ok(list)
+}
+
+/// 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)?;
+ let mut query = vec![("limit", "30")];
+ let search = search.trim();
+ if !search.is_empty() {
+ query.push(("search", search));
+ }
+ if !cursor.is_empty() {
+ query.push(("cursor", cursor));
+ }
+ let (v, connected) = tokio::join!(get(&c.key, "/toolkits", &query), refresh(store));
+ let v = v?;
+ let connected = connected.unwrap_or(c.connections);
+ let items: Vec<Value> = v["items"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(|t| {
+ let slug = text(&t["slug"])?.to_lowercase();
+ // Composio's own meta-toolkits aren't apps.
+ if slug.starts_with("composio") {
+ return None;
+ }
+ let conn = connected.iter().find(|c| c.toolkit == slug);
+ Some(json!({
+ "slug": slug,
+ "name": text(&t["name"]).unwrap_or_else(|| slug.clone()),
+ "description": text(&t["meta"]["description"]).or_else(|| text(&t["description"])),
+ "logo": text(&t["meta"]["logo"]).or_else(|| text(&t["logo"])),
+ "connection": conn.map(|c| json!({"id": c.id, "status": c.status})),
+ }))
+ })
+ .collect();
+ Ok(json!({"items": items, "nextCursor": text(&v["next_cursor"])}))
+}
+
+// MARK: connecting
+
+/// Starts connecting `toolkit`: a hosted link to open, or the fields a key-based app needs.
+pub async fn connect(store: &Store, toolkit: &str) -> Result<Value> {
+ let c = config(store)?;
+ let slug = checked_slug(toolkit)?.to_lowercase();
+ let detail = get(&c.key, &format!("/toolkits/{slug}"), &[]).await?;
+ let managed = detail["composio_managed_auth_schemes"].as_array().is_some_and(|a| !a.is_empty());
+ if !managed && let Some((mode, fields)) = key_fields(&detail) {
+ return Ok(json!({"status": "needsFields", "mode": mode, "fields": fields}));
+ }
+ let auth_config = managed_auth_config(&c.key, &slug).await?;
+ let v =
+ post(&c.key, "/connected_accounts/link", &json!({"auth_config_id": auth_config, "user_id": c.user_id})).await?;
+ let url = text(&v["redirect_url"]).ok_or_else(|| anyhow!("Composio didn't return a sign-in link"))?;
+ Ok(json!({"status": "redirect", "url": url, "connection": text(&v["connected_account_id"])}))
+}
+
+/// The first non-OAuth scheme a toolkit declares, with its input fields.
+fn key_fields(detail: &Value) -> Option<(String, Vec<Value>)> {
+ detail["auth_config_details"].as_array()?.iter().find_map(|d| {
+ let mode = text(&d["mode"])?.to_uppercase();
+ if mode.starts_with("OAUTH") {
+ return None;
+ }
+ let init = &d["fields"]["connected_account_initiation"];
+ let mut fields: Vec<Value> = [("required", true), ("optional", false)]
+ .iter()
+ .flat_map(|(k, required)| {
+ init[*k].as_array().into_iter().flatten().filter_map(move |f| {
+ let name = text(&f["name"])?;
+ let secret = f["is_secret"].as_bool().unwrap_or_else(|| {
+ let n = name.to_lowercase();
+ ["key", "token", "secret", "password"].iter().any(|h| n.contains(h))
+ });
+ Some(json!({
+ "name": name,
+ "label": text(&f["display_name"]).unwrap_or_else(|| title_case(&name)),
+ "description": text(&f["description"]),
+ "secret": secret,
+ "required": *required || f["required"].as_bool().unwrap_or(false),
+ }))
+ })
+ })
+ .collect();
+ if fields.is_empty() {
+ fields.push(json!({"name": "generic_api_key", "label": "API key", "secret": true, "required": true}));
+ }
+ Some((mode, fields))
+ })
+}
+
+/// A Composio-managed auth config for `slug`, made on first use.
+async fn managed_auth_config(key: &str, slug: &str) -> Result<String> {
+ let list = get(key, "/auth_configs", &[("toolkit_slug", slug), ("limit", "100")]).await?;
+ let existing = list["items"].as_array().into_iter().flatten().find(|a| {
+ a["is_composio_managed"] == true
+ && text(&a["status"]).is_none_or(|s| s.eq_ignore_ascii_case("enabled") || s.eq_ignore_ascii_case("active"))
+ });
+ if let Some(id) = existing.and_then(|a| text(&a["id"])) {
+ return Ok(id);
+ }
+ let v = post(
+ key,
+ "/auth_configs",
+ &json!({"toolkit": {"slug": slug}, "auth_config": {"type": "use_composio_managed_auth", "name": format!("Codync {slug}")}}),
+ )
+ .await?;
+ text(&v["auth_config"]["id"])
+ .or_else(|| text(&v["id"]))
+ .ok_or_else(|| anyhow!("Composio didn't return an auth config"))
+}
+
+/// Connects a key-based app with the fields `connect` asked for.
+pub async fn connect_with_fields(
+ store: &Store,
+ toolkit: &str,
+ mode: &str,
+ fields: &serde_json::Map<String, Value>,
+) -> Result<Value> {
+ let c = config(store)?;
+ let slug = checked_slug(toolkit)?.to_lowercase();
+ let mode = checked_slug(mode)?.to_uppercase();
+ let values: serde_json::Map<String, Value> = fields
+ .iter()
+ .filter(|(_, v)| v.as_str().is_some_and(|s| !s.trim().is_empty()))
+ .map(|(k, v)| (k.clone(), v.clone()))
+ .collect();
+ if values.is_empty() {
+ bail!("Fill in the fields first.");
+ }
+ let config = post(
+ &c.key,
+ "/auth_configs",
+ &json!({"toolkit": {"slug": slug}, "auth_config": {"type": "use_custom_auth", "authScheme": mode, "name": format!("Codync {slug}")}}),
+ )
+ .await?;
+ let config = text(&config["auth_config"]["id"])
+ .or_else(|| text(&config["id"]))
+ .ok_or_else(|| anyhow!("Composio didn't return an auth config"))?;
+ let v = post(
+ &c.key,
+ "/connected_accounts",
+ &json!({"auth_config": {"id": config}, "connection": {"user_id": c.user_id, "state": {"authScheme": mode, "val": values}}}),
+ )
+ .await?;
+ let id = text(&v["id"]).ok_or_else(|| anyhow!("Composio didn't return the connection"))?;
+ connection(store, &id).await
+}
+
+/// One connection's state (polled while the user signs in).
+pub async fn connection(store: &Store, id: &str) -> Result<Value> {
+ let c = config(store)?;
+ let v = get(&c.key, &format!("/connected_accounts/{}", checked_slug(id)?), &[]).await?;
+ let status = text(&v["status"]).unwrap_or_default().to_lowercase();
+ if status == "active" {
+ refresh(store).await?;
+ }
+ Ok(json!({"id": id, "status": status, "toolkit": text(&v["toolkit"]["slug"])}))
+}
+
+/// Disconnects the app behind connector `composio-<toolkit>` (every account of it).
+pub async fn disconnect(store: &Store, toolkit: &str) -> Result<()> {
+ let c = config(store)?;
+ for conn in refresh(store).await?.iter().filter(|x| x.toolkit == toolkit) {
+ request(
+ &c.key,
+ reqwest::Method::DELETE,
+ &format!("/connected_accounts/{}", checked_slug(&conn.id)?),
+ &[],
+ None,
+ )
+ .await?;
+ }
+ refresh(store).await?;
+ Ok(())
+}
+
+// MARK: tools for bots
+
+/// MCP tools of the built-in `composio` server.
+pub fn tools() -> Value {
+ json!([
+ {
+ "name": "list_apps",
+ "description": "The connected apps you may use.",
+ "inputSchema": {"type": "object", "properties": {}},
+ "annotations": {"readOnlyHint": true},
+ },
+ {
+ "name": "search_tools",
+ "description": "Find tools in the connected apps by what they do, e.g. \"send an email\" or \"create an issue\".",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "What you want to do."},
+ "app": {"type": "string", "description": "Limit to one app (its slug from list_apps)."},
+ },
+ "required": ["query"],
+ },
+ "annotations": {"readOnlyHint": true},
+ },
+ {
+ "name": "get_tool",
+ "description": "A tool's description and input parameters (JSON Schema).",
+ "inputSchema": {"type": "object", "properties": {"slug": {"type": "string"}}, "required": ["slug"]},
+ "annotations": {"readOnlyHint": true},
+ },
+ {
+ "name": "execute",
+ "description": "Run a tool with arguments that match its input parameters.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {"slug": {"type": "string"}, "arguments": {"type": "object"}},
+ "required": ["slug", "arguments"],
+ },
+ },
+ ])
+}
+
+/// Toolkits bot `bot` may use: its `composio-*` connectors that are connected.
+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())
+}
+
+/// 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
+ .iter()
+ .filter_map(|id| id.strip_prefix(PREFIX))
+ .any(|t| conns.iter().any(|c| c.active() && c.toolkit == t))
+}
+
+/// A tool call from a bot's `composio` MCP server.
+pub async fn call(store: &Store, bot: &str, name: &str, args: &Value) -> Result<Value> {
+ let c = config(store)?;
+ let apps = allowed(store, bot)?;
+ if apps.is_empty() {
+ bail!("No connected apps are turned on for this bot.");
+ }
+ let app_of = |toolkit: &str| apps.iter().find(|a| a.toolkit.eq_ignore_ascii_case(toolkit));
+ match name {
+ "list_apps" => Ok(json!(apps.iter().map(|a| json!({"slug": a.toolkit, "name": a.name})).collect::<Vec<_>>())),
+ "search_tools" => {
+ let query = args["query"].as_str().unwrap_or_default();
+ let targets: Vec<&Connection> = match args["app"].as_str().filter(|s| !s.is_empty()) {
+ Some(app) => {
+ vec![app_of(app).ok_or_else(|| anyhow!("`{app}` isn't one of your apps (see list_apps)"))?]
+ }
+ None => apps.iter().collect(),
+ };
+ let mut found = vec![];
+ for app in targets.iter().take(8) {
+ let v =
+ get(&c.key, "/tools", &[("toolkit_slug", &app.toolkit), ("query", query), ("limit", "8")]).await?;
+ for t in v["items"].as_array().into_iter().flatten() {
+ found.push(json!({
+ "slug": t["slug"], "name": t["name"], "app": app.toolkit,
+ "description": t["description"].as_str().map(|d| crate::acp::truncate(d, 300)),
+ }));
+ }
+ }
+ Ok(json!(found))
+ }
+ "get_tool" => {
+ let slug = checked_slug(args["slug"].as_str().unwrap_or_default())?;
+ let t = tool(&c.key, slug).await?;
+ let toolkit = text(&t["toolkit"]["slug"]).unwrap_or_default();
+ app_of(&toolkit).ok_or_else(|| anyhow!("{slug} belongs to an app this bot can't use"))?;
+ Ok(
+ json!({"slug": t["slug"], "name": t["name"], "description": t["description"], "input_parameters": t["input_parameters"]}),
+ )
+ }
+ "execute" => {
+ let slug = checked_slug(args["slug"].as_str().unwrap_or_default())?;
+ let t = tool(&c.key, slug).await?;
+ let toolkit = text(&t["toolkit"]["slug"]).unwrap_or_default();
+ let app = app_of(&toolkit).ok_or_else(|| anyhow!("{slug} belongs to an app this bot can't use"))?;
+ let arguments = args.get("arguments").filter(|a| a.is_object()).cloned().unwrap_or_else(|| json!({}));
+ let v = post(
+ &c.key,
+ &format!("/tools/execute/{slug}"),
+ &json!({"user_id": c.user_id, "connected_account_id": app.id, "arguments": arguments}),
+ )
+ .await?;
+ if v["successful"] == false {
+ bail!("{}", text(&v["error"]).unwrap_or_else(|| "the tool failed".into()));
+ }
+ Ok(v["data"].clone())
+ }
+ other => bail!("unknown tool {other}"),
+ }
+}
+
+async fn tool(key: &str, slug: &str) -> Result<Value> {
+ get(key, &format!("/tools/{slug}"), &[("toolkit_versions", "latest")]).await
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reads_key_based_fields() {
+ let detail = json!({
+ "composio_managed_auth_schemes": [],
+ "auth_config_details": [
+ {"mode": "OAUTH2", "fields": {}},
+ {"mode": "API_KEY", "fields": {"connected_account_initiation": {
+ "required": [{"name": "api_key", "display_name": "API Key"}],
+ "optional": [{"name": "subdomain", "description": "Your workspace"}],
+ }}},
+ ],
+ });
+ let (mode, fields) = key_fields(&detail).unwrap();
+ assert_eq!(mode, "API_KEY");
+ assert_eq!(fields[0]["name"], "api_key");
+ assert_eq!(fields[0]["secret"], true);
+ assert_eq!(fields[0]["required"], true);
+ assert_eq!(fields[1]["label"], "Subdomain");
+ assert_eq!(fields[1]["secret"], false);
+ assert_eq!(fields[1]["required"], false);
+ }
+
+ #[test]
+ fn slugs_stay_out_of_paths() {
+ assert!(checked_slug("GMAIL_SEND_EMAIL").is_ok());
+ assert!(checked_slug("ca_abc-123").is_ok());
+ assert!(checked_slug("../auth_configs").is_err());
+ assert!(checked_slug("a/b").is_err());
+ assert!(checked_slug("").is_err());
+ }
+}
diff --git a/host/src/main.rs b/host/src/main.rs
index 4f0ca933..7fac3784 100644
--- a/host/src/main.rs
+++ b/host/src/main.rs
@@ -5,6 +5,7 @@ mod api;
mod auth;
mod backends;
mod bot;
+mod composio;
mod context;
mod hub;
mod market;
@@ -126,6 +127,13 @@ enum McpServer {
#[arg(long, default_value_t = service::DEFAULT_PORT)]
port: u16,
},
+ /// Tools of the apps connected through Composio.
+ Composio {
+ #[arg(long)]
+ bot: String,
+ #[arg(long, default_value_t = service::DEFAULT_PORT)]
+ port: u16,
+ },
/// See and operate this computer's desktop.
Computer {
#[arg(long)]
@@ -253,6 +261,7 @@ async fn main() -> Result<()> {
}
Sub::Mcp { server: McpServer::Computer { bot, port } } => mcp::serve(bot, port, mcp::Server::Computer).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::Tui { url, token, port } => {
tui::run(url.unwrap_or_else(|| format!("http://127.0.0.1:{port}")), token).await
}
diff --git a/host/src/market.rs b/host/src/market.rs
index 9df357b6..a6205f16 100644
--- a/host/src/market.rs
+++ b/host/src/market.rs
@@ -428,8 +428,23 @@ pub fn add_custom_connector(store: &crate::store::Store, b: &Value) -> Result<Va
Ok(c.public())
}
+/// Installed MCP servers, then the apps connected through Composio.
pub fn list_connectors(store: &crate::store::Store) -> Value {
- json!({"items": connectors(store).iter().map(Connector::public).collect::<Vec<_>>()})
+ let mut items: Vec<Value> = connectors(store).iter().map(Connector::public).collect();
+ items.extend(crate::composio::connections(store).iter().filter(|c| c.active()).map(|c| {
+ json!({
+ "id": format!("{}{}", crate::composio::PREFIX, c.toolkit),
+ "name": c.name,
+ "description": format!("{} through Composio", c.name),
+ "registryName": null,
+ "kind": "composio",
+ "command": null,
+ "url": null,
+ "keys": [],
+ "logo": c.logo,
+ })
+ }));
+ json!({"items": items})
}
pub fn remove_connector(store: &crate::store::Store, id: &str) -> Result<()> {
diff --git a/host/src/mcp.rs b/host/src/mcp.rs
index e8152eff..cf868992 100644
--- a/host/src/mcp.rs
+++ b/host/src/mcp.rs
@@ -13,6 +13,7 @@ const PROTOCOL_VERSION: &str = "2025-06-18";
pub enum Server {
Computer,
Team,
+ Composio,
}
const INSTRUCTIONS: &str = "Operate this computer's desktop like a person would. Start with `screenshot` \
@@ -106,6 +107,7 @@ pub async fn serve(bot: String, port: u16, server: Server) -> Result<()> {
let (name, instructions, available_tools) = match server {
Server::Computer => ("codync-computer", INSTRUCTIONS, tools()),
Server::Team => ("codync-team", crate::team::INSTRUCTIONS, crate::team::tools()),
+ Server::Composio => ("codync-composio", crate::composio::INSTRUCTIONS, crate::composio::tools()),
};
while let Some(line) = lines.next_line().await? {
let Ok(msg) = serde_json::from_str::<Value>(&line) else { continue };
@@ -147,6 +149,7 @@ async fn call(port: u16, token: &str, bot: &str, params: &Value, server: Server)
let (method, timeout) = match server {
Server::Computer => ("computerCall", Duration::from_secs(60)),
Server::Team => ("teamCall", crate::team::ASK_TIMEOUT + Duration::from_secs(30)),
+ Server::Composio => ("composioCall", Duration::from_secs(120)),
};
let res = crate::http()
.post(format!("http://127.0.0.1:{port}/api/{method}"))
@@ -163,6 +166,7 @@ async fn call(port: u16, token: &str, bot: &str, params: &Value, server: Server)
return match server {
Server::Computer => json!({"content": v["content"]}),
Server::Team => json!({"content": [{"type": "text", "text": v.to_string()}]}),
+ Server::Composio => json!({"content": [{"type": "text", "text": v["result"].to_string()}]}),
};
}
Ok(v) => v["error"].as_str().unwrap_or("the Codync host refused the call").to_owned(),
diff --git a/kit/Sources/CodyncKit/Design/SwitchStyle.swift b/kit/Sources/CodyncKit/Design/SwitchStyle.swift
deleted file mode 100644
index 3c562899..00000000
--- a/kit/Sources/CodyncKit/Design/SwitchStyle.swift
+++ /dev/null
@@ -1,32 +0,0 @@
-import SwiftUI
-
-/// Codync's own on/off switch: label on the left, a flat capsule track on the right.
-public struct CodyncSwitch: ToggleStyle {
- @Environment(\.accessibilityReduceMotion) private var reduceMotion
-
- public init() {}
-
- public func makeBody(configuration: Configuration) -> some View {
- Button {
- withAnimation(Motion.reduced(Motion.hover, reduceMotion)) { configuration.isOn.toggle() }
- } label: {
- HStack(spacing: 12) {
- configuration.label
- Spacer(minLength: 0)
- Capsule()
- .fill(configuration.isOn ? Palette.switchOn : Palette.bubbleUser)
- .frame(width: 34, height: 20)
- .overlay(alignment: configuration.isOn ? .trailing : .leading) {
- Circle().fill(.white).padding(2)
- }
- }
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .accessibilityRepresentation { Toggle(isOn: configuration.$isOn) { configuration.label } }
- }
-}
-
-public extension ToggleStyle where Self == CodyncSwitch {
- static var codync: CodyncSwitch { CodyncSwitch() }
-}
diff --git a/kit/Sources/CodyncKit/Models/Market.swift b/kit/Sources/CodyncKit/Models/Market.swift
index 5d08d3cb..dc45e7c0 100644
--- a/kit/Sources/CodyncKit/Models/Market.swift
+++ b/kit/Sources/CodyncKit/Models/Market.swift
@@ -8,12 +8,61 @@ public struct InstalledConnector: Codable, Hashable, Sendable, Identifiable {
public var name: String
public var description: String
public var registryName: String?
- /// `local` (a command the agent starts) or `remote` (a URL).
+ /// `local` (a command the agent starts), `remote` (a URL) or `composio` (an app connected through Composio).
public var kind: String
public var command: String?
public var url: String?
/// Names of the keys and headers that are set; their values stay on the computer.
public var keys: [String]
+ /// Composio apps: the app's logo.
+ public var logo: String?
+}
+
+// MARK: Composio (host/src/composio.rs): apps connected through composio.dev
+
+public struct ComposioStatus: Decodable, Sendable {
+ public var configured: Bool
+ /// Where to get an API key.
+ public var keyUrl: String
+}
+
+public struct ComposioApp: Decodable, Hashable, Sendable, Identifiable {
+ public struct Connection: Decodable, Hashable, Sendable {
+ public var id: String
+ /// Composio's status: `active`, `initiated`, `failed`, `expired`…
+ public var status: String
+ }
+
+ public var slug: String
+ public var name: String
+ public var description: String?
+ public var logo: String?
+ public var connection: Connection?
+ public var id: String { slug }
+ public var connected: Bool { connection?.status == "active" }
+}
+
+/// What connecting an app needs: a sign-in page, or fields for a key-based app.
+public struct ComposioConnect: Decodable, Sendable {
+ public struct Field: Decodable, Hashable, Sendable {
+ public var name: String
+ public var label: String
+ public var description: String?
+ public var secret: Bool
+ public var required: Bool
+ }
+
+ /// `redirect` or `needsFields`.
+ public var status: String
+ public var url: String?
+ public var connection: String?
+ public var mode: String?
+ public var fields: [Field]?
+}
+
+public struct ComposioConnectionState: Decodable, Sendable {
+ public var id: String
+ public var status: String
}
public struct MarketConnector: Codable, Hashable, Sendable, Identifiable {
@@ -91,6 +140,31 @@ public extension HostClient {
let _: Empty = try await call("removeConnector", ["id": id])
}
+ func composioStatus() async throws -> ComposioStatus { try await call("composioStatus") }
+
+ /// Checks the key with Composio before keeping it; an empty key forgets Composio.
+ func setComposioKey(_ key: String) async throws -> ComposioStatus {
+ try await call("setComposioKey", ["key": key], timeout: 60)
+ }
+
+ func composioApps(search: String) async throws -> [ComposioApp] {
+ let res: Items<ComposioApp> = try await call("composioToolkits", ["search": search], timeout: 60)
+ return res.items
+ }
+
+ func composioConnect(_ app: String) async throws -> ComposioConnect {
+ try await call("composioConnect", ["toolkit": app], timeout: 60)
+ }
+
+ func composioConnect(_ app: String, mode: String, fields: [String: String]) async throws -> ComposioConnectionState {
+ struct Body: Encodable { var toolkit: String; var mode: String; var fields: [String: String] }
+ return try await call("composioConnectFields", Body(toolkit: app, mode: mode, fields: fields), timeout: 60)
+ }
+
+ func composioConnection(_ id: String) async throws -> ComposioConnectionState {
+ try await call("composioConnection", ["id": id], timeout: 30)
+ }
+
func skills() async throws -> [InstalledSkill] {
let res: Items<InstalledSkill> = try await call("skills")
return res.items
diff --git a/kit/Sources/CodyncUI/Bots/BotEditorView.swift b/kit/Sources/CodyncUI/Bots/BotEditorView.swift
index 95e8790c..ad289af0 100644
--- a/kit/Sources/CodyncUI/Bots/BotEditorView.swift
+++ b/kit/Sources/CodyncUI/Bots/BotEditorView.swift
@@ -30,7 +30,7 @@ public struct BotEditorView: View {
}
ToolbarItem(placement: .confirmationAction) {
if saving {
- ProgressView()
+ Spinner()
} else {
Button(isNew ? "Create" : "Save", systemImage: "checkmark") { save() }
.labelStyle(.iconOnly)
@@ -148,8 +148,9 @@ struct BotSettingsForm: View {
.foregroundStyle(Palette.secondary)
}
OptionRow("Agent") {
- PillMenu(title: model.backendName(draft.backend), selection: $draft.backend,
- options: (model.hello?.backends ?? []).map { ($0.id, $0.available ? $0.name : "\($0.name) (not installed)") } + [("custom", "Custom command")])
+ ChoicePicker(selection: $draft.backend,
+ options: (model.hello?.backends ?? []).map { ($0.id, $0.available ? $0.name : "\($0.name) (not installed)") } + [("custom", "Custom command")],
+ fill: Palette.background)
}
if let b = model.hello?.backends.first(where: { $0.id == draft.backend }), !b.available {
Text(b.installHint).font(.caption).foregroundStyle(Palette.warning)
@@ -181,8 +182,8 @@ struct BotSettingsForm: View {
.help(draft.cwd)
}
OptionRow("Permissions") {
- PillMenu(title: draft.permission == "auto" ? "Automatic" : "Ask me", selection: $draft.permission,
- options: [("ask", "Ask me"), ("auto", "Approve automatically")])
+ ChoicePicker(selection: $draft.permission, options: [("ask", "Ask me"), ("auto", "Approve automatically")],
+ fill: Palette.background)
}
Toggle(isOn: Binding(get: { draft.notify ?? true }, set: { draft.notify = $0 })) {
VStack(alignment: .leading, spacing: 3) {
@@ -336,77 +337,7 @@ private struct PluginToggles: View {
}
}
-/// A value shown in a pill with a chevron; tapping opens our own list of choices.
-private struct PillMenu: View {
- let title: String
- @Binding var selection: String
- let options: [(id: String, label: String)]
- @State private var open = false
-
- var body: some View {
- Button { open.toggle() } label: {
- HStack(spacing: 6) {
- Text(title).lineLimit(1)
- Image(systemName: "chevron.down").font(.caption2.weight(.semibold)).foregroundStyle(Palette.secondary)
- }
- .foregroundStyle(Palette.text)
- .pill()
- }
- .buttonStyle(.plain)
- .fixedSize()
- .popover(isPresented: $open, arrowEdge: .bottom) {
- VStack(alignment: .leading, spacing: 2) {
- ForEach(options, id: \.id) { option in
- ChoiceRow(label: option.label, selected: option.id == selection) {
- selection = option.id
- open = false
- }
- }
- }
- .padding(6)
- .frame(minWidth: 200)
- .fixedSize()
- .presentationCompactAdaptation(.popover)
- .presentationBackground(Palette.bubbleAgent)
- }
- }
-}
-
-private struct ChoiceRow: View {
- let label: String
- let selected: Bool
- let action: () -> Void
- @State private var hovering = false
-
- var body: some View {
- Button(action: action) {
- HStack(spacing: 10) {
- Text(label).foregroundStyle(Palette.text).lineLimit(1)
- Spacer(minLength: 16)
- Image(systemName: "checkmark")
- .font(.caption.weight(.semibold))
- .foregroundStyle(Palette.text)
- .opacity(selected ? 1 : 0)
- }
- .padding(.horizontal, 10)
- .padding(.vertical, InterfaceMetrics.value(mac: 6, mobile: 10))
- .background(hovering ? Palette.text.opacity(0.06) : .clear, in: RoundedRectangle(cornerRadius: 8, style: .continuous))
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .onHover { h in withAnimation(Motion.hover) { hovering = h } }
- .accessibilityAddTraits(selected ? .isSelected : [])
- }
-}
-
extension View {
- /// The value pill used in the options card.
- func pill() -> some View {
- padding(.horizontal, InterfaceMetrics.value(mac: 9, mobile: 12))
- .padding(.vertical, InterfaceMetrics.value(mac: 5, mobile: 7))
- .background(Palette.background, in: RoundedRectangle(cornerRadius: 10, style: .continuous))
- }
-
/// A rounded input box.
func fieldBox() -> some View {
textFieldStyle(.plain)
@@ -495,41 +426,56 @@ struct FolderPicker: View {
@State private var filter = ""
var body: some View {
- List {
- if let listing {
- Section {
- Button {
- onPick(listing.path)
- } label: {
- Label("Use “\((listing.path as NSString).lastPathComponent)”", systemImage: "checkmark.circle.fill")
- .font(.headline)
- }
- } footer: {
- Text(listing.path).font(.caption.monospaced())
- }
- Section {
- ForEach(listing.dirs.filter { filter.isEmpty || $0.name.localizedCaseInsensitiveContains(filter) }) { dir in
- NavigationLink {
- FolderPicker(path: dir.path, onPick: onPick)
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 14, mobile: 22)) {
+ SearchField(text: $filter)
+ if let listing {
+ CardSection(footer: listing.path) {
+ Button {
+ onPick(listing.path)
} label: {
- Label {
- Text(dir.name)
- } icon: {
- Image(systemName: dir.isGit ? "arrow.triangle.branch" : "folder")
- .foregroundStyle(dir.isGit ? Palette.accent : Palette.secondary)
+ Label("Use “\((listing.path as NSString).lastPathComponent)”", systemImage: "checkmark.circle.fill")
+ .font(.headline)
+ .foregroundStyle(Palette.accent)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ }
+ let dirs = listing.dirs.filter { filter.isEmpty || $0.name.localizedCaseInsensitiveContains(filter) }
+ if !dirs.isEmpty {
+ CardSection {
+ ForEach(dirs) { dir in
+ NavigationLink {
+ FolderPicker(path: dir.path, onPick: onPick)
+ } label: {
+ HStack(spacing: 10) {
+ Image(systemName: dir.isGit ? "arrow.triangle.branch" : "folder")
+ .foregroundStyle(dir.isGit ? Palette.accent : Palette.secondary)
+ .frame(width: 20)
+ Text(dir.name).foregroundStyle(Palette.text).lineLimit(1)
+ Spacer(minLength: 8)
+ Image(systemName: "chevron.right")
+ .font(.caption2.weight(.semibold))
+ .foregroundStyle(Palette.tertiary)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
}
}
}
+ } else if let error {
+ Text(error).foregroundStyle(Palette.danger)
+ } else {
+ Spinner(size: 20).frame(maxWidth: .infinity)
}
- } else if let error {
- Text(error).foregroundStyle(Palette.danger)
- } else {
- ProgressView()
}
+ .font(InterfaceMetrics.body)
+ .padding(InterfaceMetrics.value(mac: 14, mobile: 20))
}
- .scrollContentBackground(.hidden)
+ .scrollDismissesKeyboard(.interactively)
.background(Palette.background)
- .searchable(text: $filter)
.navigationTitle(listing.map { ($0.path as NSString).lastPathComponent } ?? "Folders")
.inlineNavigationTitle()
.task {
diff --git a/kit/Sources/CodyncUI/Bots/BotTemplateView.swift b/kit/Sources/CodyncUI/Bots/BotTemplateView.swift
index dd08aaee..f0f68b63 100644
--- a/kit/Sources/CodyncUI/Bots/BotTemplateView.swift
+++ b/kit/Sources/CodyncUI/Bots/BotTemplateView.swift
@@ -43,7 +43,6 @@ struct BotTemplateView: View {
.padding(16)
}
.background(Palette.surface, in: RoundedRectangle(cornerRadius: 12))
- .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(Palette.border))
HStack {
Text("Includes the working folder and agent configuration.")
.font(.caption).foregroundStyle(Palette.secondary)
diff --git a/kit/Sources/CodyncUI/Bots/Dialogs.swift b/kit/Sources/CodyncUI/Bots/Dialogs.swift
index 884f6dd1..06f3930b 100644
--- a/kit/Sources/CodyncUI/Bots/Dialogs.swift
+++ b/kit/Sources/CodyncUI/Bots/Dialogs.swift
@@ -8,13 +8,11 @@ public extension View {
modifier(DeleteBotConfirmation(bot: bot, onDeleted: onDeleted))
}
- /// Shows `BotStore.lastError` as an alert.
+ /// Shows `BotStore.lastError` in a dialog.
func storeErrorAlert(_ model: BotStore) -> some View {
- alert("Something went wrong", isPresented: Binding(get: { model.lastError != nil }, set: { if !$0 { model.lastError = nil } })) {
- Button("OK", role: .cancel) {}
- } message: {
- Text(model.lastError ?? "")
- }
+ codyncDialog("Something went wrong",
+ isPresented: Binding(get: { model.lastError != nil }, set: { if !$0 { model.lastError = nil } }),
+ message: model.lastError, cancel: "OK") { [] }
}
}
@@ -24,17 +22,17 @@ private struct DeleteBotConfirmation: ViewModifier {
@Environment(BotStore.self) private var model
func body(content: Content) -> some View {
- content.confirmationDialog(
+ content.codyncDialog(
"Delete \(bot?.name ?? "bot")?",
isPresented: Binding(get: { bot != nil }, set: { if !$0 { bot = nil } }),
- titleVisibility: .visible
+ message: "Files it changed on your computer stay as they are."
) {
- Button("Delete bot and its conversation", role: .destructive) {
- if let bot { model.delete(bot) }
+ // Captured now: the dialog clears `bot` before running the action.
+ let target = bot
+ return [DialogAction("Delete bot and its conversation", destructive: true) {
+ if let target { model.delete(target) }
onDeleted()
- }
- } message: {
- Text("Files it changed on your computer stay as they are.")
+ }]
}
}
}
diff --git a/kit/Sources/CodyncUI/Bots/MemoryView.swift b/kit/Sources/CodyncUI/Bots/MemoryView.swift
index 7bc372af..e222d25a 100644
--- a/kit/Sources/CodyncUI/Bots/MemoryView.swift
+++ b/kit/Sources/CodyncUI/Bots/MemoryView.swift
@@ -86,8 +86,8 @@ struct MemoryCard: View {
.background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18, style: .continuous))
}
.task(id: botId) { await load() }
- .confirmationDialog("Forget everything this bot remembers?", isPresented: $confirmClear, titleVisibility: .visible) {
- Button("Forget everything", role: .destructive) { clear() }
+ .codyncDialog("Forget everything this bot remembers?", isPresented: $confirmClear) {
+ [DialogAction("Forget everything", destructive: true) { clear() }]
}
}
diff --git a/kit/Sources/CodyncUI/Bots/NewChatView.swift b/kit/Sources/CodyncUI/Bots/NewChatView.swift
index 1ca6d3c6..2ed22b22 100644
--- a/kit/Sources/CodyncUI/Bots/NewChatView.swift
+++ b/kit/Sources/CodyncUI/Bots/NewChatView.swift
@@ -61,7 +61,6 @@ public struct NewChatView: View {
.frame(maxHeight: 460)
.fixedSize(horizontal: false, vertical: true)
.background(Palette.surface, in: RoundedRectangle(cornerRadius: 18, style: .continuous))
- .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).stroke(Palette.border))
.shadow(color: .black.opacity(0.08), radius: 16, y: 6)
.frame(maxWidth: 620, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading)
@@ -165,6 +164,5 @@ private struct KeyCap: View {
.foregroundStyle(Palette.secondary)
.frame(minWidth: 18, minHeight: 18)
.background(Palette.background, in: RoundedRectangle(cornerRadius: 4))
- .overlay(RoundedRectangle(cornerRadius: 4).stroke(Palette.border))
}
}
diff --git a/kit/Sources/CodyncUI/Controls.swift b/kit/Sources/CodyncUI/Controls.swift
new file mode 100644
index 00000000..7a873534
--- /dev/null
+++ b/kit/Sources/CodyncUI/Controls.swift
@@ -0,0 +1,665 @@
+import CodyncKit
+import SwiftUI
+#if os(macOS)
+import AppKit
+#endif
+
+// Codync's own controls. Never use the stock ones (Menu, Picker, .switch toggles,
+// Form/List styling, confirmationDialog/alert, ProgressView, DisclosureGroup,
+// .bordered buttons, contextMenu/swipeActions): build from these instead.
+// Anything with a background fill gets no border line.
+
+// MARK: - Switch
+
+/// On/off switch: label on the left, a flat capsule track on the right.
+public struct CodyncSwitch: ToggleStyle {
+ public init() {}
+
+ public func makeBody(configuration: Configuration) -> some View {
+ SwitchBody(configuration: configuration)
+ }
+
+ private struct SwitchBody: View {
+ let configuration: Configuration
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @Environment(\.isEnabled) private var isEnabled
+
+ var body: some View {
+ Button {
+ withAnimation(Motion.reduced(Motion.hover, reduceMotion)) { configuration.isOn.toggle() }
+ } label: {
+ HStack(spacing: 12) {
+ configuration.label
+ Spacer(minLength: 0)
+ Capsule()
+ .fill(configuration.isOn ? Palette.switchOn : Palette.bubbleUser)
+ .frame(width: 34, height: 20)
+ .overlay(alignment: configuration.isOn ? .trailing : .leading) {
+ Circle().fill(.white).padding(2)
+ }
+ }
+ .contentShape(Rectangle())
+ .opacity(isEnabled ? 1 : 0.4)
+ }
+ .buttonStyle(.plain)
+ .accessibilityRepresentation { Toggle(isOn: configuration.$isOn) { configuration.label } }
+ }
+ }
+}
+
+public extension ToggleStyle where Self == CodyncSwitch {
+ static var codync: CodyncSwitch { CodyncSwitch() }
+}
+
+// MARK: - Buttons
+
+/// The filled call-to-action: accent capsule with press feedback.
+public struct PrimaryButtonStyle: ButtonStyle {
+ public init() {}
+
+ public func makeBody(configuration: Configuration) -> some View {
+ StyledButton(configuration: configuration, fill: Palette.accentFill, foreground: Palette.onAccent)
+ }
+}
+
+/// A quieter filled button next to a primary one.
+public struct SecondaryButtonStyle: ButtonStyle {
+ public init() {}
+
+ public func makeBody(configuration: Configuration) -> some View {
+ StyledButton(configuration: configuration, fill: Palette.bubbleUser, foreground: Palette.text)
+ }
+}
+
+private struct StyledButton: View {
+ let configuration: ButtonStyleConfiguration
+ let fill: Color
+ let foreground: Color
+ @Environment(\.isEnabled) private var isEnabled
+
+ var body: some View {
+ configuration.label
+ .font(InterfaceMetrics.body.weight(.medium))
+ .foregroundStyle(foreground)
+ .padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 18))
+ .padding(.vertical, InterfaceMetrics.value(mac: 6, mobile: 11))
+ .background(fill, in: Capsule())
+ .opacity(isEnabled ? (configuration.isPressed ? 0.85 : 1) : 0.4)
+ .scaleEffect(configuration.isPressed ? Motion.pressScale : 1)
+ .animation(Motion.press, value: configuration.isPressed)
+ .contentShape(Capsule())
+ }
+}
+
+public extension ButtonStyle where Self == PrimaryButtonStyle {
+ static var primary: PrimaryButtonStyle { PrimaryButtonStyle() }
+}
+
+public extension ButtonStyle where Self == SecondaryButtonStyle {
+ static var secondary: SecondaryButtonStyle { SecondaryButtonStyle() }
+}
+
+// MARK: - Spinner
+
+/// Loading indicator: a thin arc that turns.
+public struct Spinner: View {
+ var size: CGFloat
+ @State private var turning = false
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ public init(size: CGFloat = 14) { self.size = size }
+
+ public var body: some View {
+ Circle()
+ .trim(from: 0, to: 0.7)
+ .stroke(Palette.secondary, style: StrokeStyle(lineWidth: max(1.5, size / 9), lineCap: .round))
+ .frame(width: size, height: size)
+ .rotationEffect(.degrees(turning ? 360 : 0))
+ .animation(reduceMotion ? nil : .linear(duration: 0.8).repeatForever(autoreverses: false), value: turning)
+ .onAppear { turning = true }
+ .accessibilityLabel("Loading")
+ }
+}
+
+// MARK: - Menus
+
+/// One row in a Codync menu: an action, or a choice when `selected` is set.
+public struct MenuItem: Identifiable {
+ public let id = UUID()
+ public var title: String
+ public var icon: String?
+ public var selected: Bool?
+ public var destructive: Bool
+ public var divider: Bool
+ public var action: () -> Void
+
+ public init(_ title: String, icon: String? = nil, selected: Bool? = nil, destructive: Bool = false,
+ divider: Bool = false, action: @escaping () -> Void) {
+ self.title = title
+ self.icon = icon
+ self.selected = selected
+ self.destructive = destructive
+ self.divider = divider
+ self.action = action
+ }
+}
+
+/// The floating panel of menu rows (used by every menu, popover or overlay).
+public struct MenuPanel: View {
+ let items: [MenuItem]
+ let dismiss: () -> Void
+
+ public init(items: [MenuItem], dismiss: @escaping () -> Void) {
+ self.items = items
+ self.dismiss = dismiss
+ }
+
+ public var body: some View {
+ VStack(alignment: .leading, spacing: 2) {
+ 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()
+ }
+ }
+ }
+ .padding(6)
+ .frame(minWidth: InterfaceMetrics.value(mac: 180, mobile: 220))
+ .fixedSize()
+ }
+}
+
+private struct MenuRow: View {
+ let item: MenuItem
+ let action: () -> Void
+ @State private var hovering = false
+
+ var body: some View {
+ Button(action: action) {
+ HStack(spacing: 10) {
+ if let icon = item.icon {
+ Image(systemName: icon).frame(width: 18)
+ }
+ Text(item.title).lineLimit(1)
+ Spacer(minLength: 16)
+ if let selected = item.selected {
+ Image(systemName: "checkmark").font(.caption.weight(.semibold)).opacity(selected ? 1 : 0)
+ }
+ }
+ .font(InterfaceMetrics.body)
+ .foregroundStyle(item.destructive ? Palette.danger : Palette.text)
+ .padding(.horizontal, 10)
+ .padding(.vertical, InterfaceMetrics.value(mac: 6, mobile: 11))
+ .background(hovering ? Palette.text.opacity(0.07) : .clear, in: RoundedRectangle(cornerRadius: 8, style: .continuous))
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .onHover { h in withAnimation(Motion.hover) { hovering = h } }
+ .accessibilityAddTraits(item.selected == true ? .isSelected : [])
+ }
+}
+
+public extension View {
+ /// Shows a Codync menu anchored to this view while `isPresented` is true.
+ func codyncMenu(isPresented: Binding<Bool>, items: @escaping () -> [MenuItem]) -> some View {
+ popover(isPresented: isPresented, arrowEdge: .bottom) {
+ MenuPanel(items: items()) { isPresented.wrappedValue = false }
+ .presentationCompactAdaptation(.popover)
+ .presentationBackground(Palette.bubbleAgent)
+ }
+ }
+
+ /// Long-press (iPhone) or right-click (Mac) opens a Codync menu: the replacement for `contextMenu`.
+ func contextActions(_ items: @escaping () -> [MenuItem]) -> some View {
+ modifier(ContextActions(items: items))
+ }
+}
+
+private struct ContextActions: ViewModifier {
+ let items: () -> [MenuItem]
+ @State private var open = false
+
+ func body(content: Content) -> some View {
+ content
+ #if os(macOS)
+ .overlay { SecondaryClickCapture { _ in open = true } }
+ #else
+ .onLongPressGesture(minimumDuration: 0.35) { open = true }
+ #endif
+ .codyncMenu(isPresented: $open, items: items)
+ .accessibilityActions {
+ ForEach(items()) { item in
+ Button(item.title, action: item.action)
+ }
+ }
+ }
+}
+
+/// A button that opens a Codync menu.
+public struct DropdownMenu<Label: View>: View {
+ let items: () -> [MenuItem]
+ let label: Label
+ @State private var open = false
+
+ public init(items: @escaping () -> [MenuItem], @ViewBuilder label: () -> Label) {
+ self.items = items
+ self.label = label()
+ }
+
+ public var body: some View {
+ Button { open.toggle() } label: { label }
+ .buttonStyle(.plain)
+ .codyncMenu(isPresented: $open, items: items)
+ }
+}
+
+/// Picks one value: shows the current choice in a pill with a chevron, opens a Codync menu.
+public struct ChoicePicker<ID: Hashable>: View {
+ @Binding var selection: ID
+ let options: [(id: ID, label: String)]
+ var fill: Color
+
+ public init(selection: Binding<ID>, options: [(id: ID, label: String)], fill: Color = Palette.bubbleUser) {
+ _selection = selection
+ self.options = options
+ self.fill = fill
+ }
+
+ public var body: some View {
+ DropdownMenu {
+ options.map { option in MenuItem(option.label, selected: option.id == selection) { selection = option.id } }
+ } label: {
+ HStack(spacing: 6) {
+ Text(options.first { $0.id == selection }?.label ?? "Choose").lineLimit(1)
+ Image(systemName: "chevron.down").font(.caption2.weight(.semibold)).foregroundStyle(Palette.secondary)
+ }
+ .font(InterfaceMetrics.body)
+ .foregroundStyle(Palette.text)
+ .pill(fill: fill)
+ }
+ .fixedSize()
+ }
+}
+
+/// Picks one of a few values side by side: the replacement for `.segmented`.
+public struct SegmentedChoice<ID: Hashable>: View {
+ @Binding var selection: ID
+ let options: [(id: ID, label: String)]
+ @Namespace private var thumb
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ public init(selection: Binding<ID>, options: [(id: ID, label: String)]) {
+ _selection = selection
+ self.options = options
+ }
+
+ public var body: some View {
+ HStack(spacing: 2) {
+ ForEach(options, id: \.id) { option in
+ let on = option.id == selection
+ Button {
+ withAnimation(Motion.reduced(Motion.morph, reduceMotion)) { selection = option.id }
+ } label: {
+ Text(option.label)
+ .font(InterfaceMetrics.secondary.weight(.medium))
+ .foregroundStyle(on ? Palette.text : Palette.secondary)
+ .lineLimit(1)
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, InterfaceMetrics.value(mac: 5, mobile: 8))
+ .background {
+ if on {
+ Capsule().fill(Palette.background).matchedGeometryEffect(id: "thumb", in: thumb)
+ }
+ }
+ .contentShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(on ? .isSelected : [])
+ }
+ }
+ .padding(3)
+ .background(Palette.bubbleUser, in: Capsule())
+ }
+}
+
+/// A list of choices, one per row with a checkmark: the replacement for `.inline` pickers.
+public struct ChoiceList<ID: Hashable>: View {
+ @Binding var selection: ID
+ let options: [(id: ID, label: String, detail: String?)]
+
+ public init(selection: Binding<ID>, options: [(id: ID, label: String, detail: String?)]) {
+ _selection = selection
+ self.options = options
+ }
+
+ public var body: some View {
+ VStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 10, mobile: 14)) {
+ ForEach(options, id: \.id) { option in
+ Button { selection = option.id } label: {
+ HStack(spacing: 10) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(option.label).foregroundStyle(Palette.text)
+ if let detail = option.detail, !detail.isEmpty {
+ Text(detail).font(InterfaceMetrics.secondary).foregroundStyle(Palette.secondary)
+ }
+ }
+ Spacer(minLength: 8)
+ Image(systemName: "checkmark")
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(Palette.text)
+ .opacity(option.id == selection ? 1 : 0)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(option.id == selection ? .isSelected : [])
+ }
+ }
+ }
+}
+
+// MARK: - Forms
+
+/// A scrolling page of cards: the replacement for `Form` / grouped `List`.
+public struct CardForm<Content: View>: View {
+ let content: Content
+
+ public init(@ViewBuilder content: () -> Content) { self.content = content() }
+
+ public var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 14, mobile: 22)) {
+ content
+ }
+ .font(InterfaceMetrics.body)
+ .padding(InterfaceMetrics.value(mac: 14, mobile: 20))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .background(Palette.background)
+ }
+}
+
+/// A titled card of rows: the replacement for `Section`.
+public struct CardSection<Content: View>: View {
+ let title: String?
+ let footer: String?
+ let content: Content
+
+ public init(_ title: String? = nil, footer: String? = nil, @ViewBuilder content: () -> Content) {
+ self.title = title
+ self.footer = footer
+ self.content = content()
+ }
+
+ public var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ if let title {
+ Text(title).font(InterfaceMetrics.secondary).foregroundStyle(Palette.secondary).padding(.leading, 4)
+ }
+ VStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 12, mobile: 16)) {
+ content
+ }
+ .padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 16))
+ .padding(.vertical, InterfaceMetrics.value(mac: 12, mobile: 16))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18, style: .continuous))
+ if let footer {
+ Text(footer).font(.caption).foregroundStyle(Palette.tertiary).padding(.horizontal, 4)
+ }
+ }
+ }
+}
+
+/// Label on the left, value on the right: the replacement for `LabeledContent`.
+public struct ValueRow<Value: View>: View {
+ let label: String
+ let value: Value
+
+ public init(_ label: String, @ViewBuilder value: () -> Value) {
+ self.label = label
+ self.value = value()
+ }
+
+ public init(_ label: String, value: String) where Value == Text {
+ self.label = label
+ self.value = Text(value)
+ }
+
+ public var body: some View {
+ HStack {
+ Text(label).foregroundStyle(Palette.text)
+ Spacer(minLength: 12)
+ value.foregroundStyle(Palette.secondary)
+ }
+ }
+}
+
+/// A search box: the replacement for `.searchable`.
+public struct SearchField: View {
+ let prompt: String
+ @Binding var text: String
+
+ public init(_ prompt: String = "Search", text: Binding<String>) {
+ self.prompt = prompt
+ _text = text
+ }
+
+ public var body: some View {
+ HStack(spacing: 8) {
+ Image(systemName: "magnifyingglass").foregroundStyle(Palette.secondary)
+ TextField(prompt, text: $text).textFieldStyle(.plain).plainTextInput()
+ if !text.isEmpty {
+ Button { text = "" } label: {
+ Image(systemName: "xmark.circle.fill").foregroundStyle(Palette.tertiary)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Clear search")
+ }
+ }
+ .font(InterfaceMetrics.body)
+ .padding(.horizontal, InterfaceMetrics.value(mac: 10, mobile: 14))
+ .padding(.vertical, InterfaceMetrics.value(mac: 7, mobile: 10))
+ .background(Palette.bubbleAgent, in: Capsule())
+ }
+}
+
+/// A row that expands to show more: the replacement for `DisclosureGroup`.
+public struct Disclosure<Label: View, Content: View>: View {
+ @Binding var isExpanded: Bool
+ let label: Label
+ let content: Content
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ public init(isExpanded: Binding<Bool>, @ViewBuilder content: () -> Content, @ViewBuilder label: () -> Label) {
+ _isExpanded = isExpanded
+ self.content = content()
+ self.label = label()
+ }
+
+ public var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Button {
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { isExpanded.toggle() }
+ } label: {
+ HStack(spacing: 6) {
+ label
+ Spacer(minLength: 8)
+ Image(systemName: "chevron.right")
+ .font(.caption2.weight(.semibold))
+ .foregroundStyle(Palette.secondary)
+ .rotationEffect(.degrees(isExpanded ? 90 : 0))
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityValue(isExpanded ? "Expanded" : "Collapsed")
+ if isExpanded { content }
+ }
+ }
+}
+
+// MARK: - Dialogs
+
+/// A button in a Codync dialog.
+public struct DialogAction: Identifiable {
+ public let id = UUID()
+ public var title: String
+ public var destructive: Bool
+ public var action: () -> Void
+
+ public init(_ title: String, destructive: Bool = false, action: @escaping () -> Void) {
+ self.title = title
+ self.destructive = destructive
+ self.action = action
+ }
+}
+
+public extension View {
+ /// A centered card over a dimmed screen with the actions and Cancel:
+ /// the replacement for `confirmationDialog` and `alert`.
+ 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))
+ }
+}
+
+private struct CodyncDialog: ViewModifier {
+ let title: String
+ let message: String?
+ let cancel: String?
+ @Binding var isPresented: Bool
+ let actions: () -> [DialogAction]
+
+ func body(content: Content) -> some View {
+ #if os(iOS)
+ content.fullScreenCover(isPresented: $isPresented) {
+ DialogCard(title: title, message: message, cancel: cancel, actions: actions()) { isPresented = false }
+ .presentationBackground(.clear)
+ }
+ .transaction { $0.disablesAnimations = true }
+ #else
+ content.overlay {
+ if isPresented {
+ DialogCard(title: title, message: message, cancel: cancel, actions: actions()) { isPresented = false }
+ .transition(.opacity)
+ }
+ }
+ .animation(Motion.fade, value: isPresented)
+ #endif
+ }
+}
+
+private struct DialogCard: View {
+ let title: String
+ let message: String?
+ let cancel: String?
+ let actions: [DialogAction]
+ let dismiss: () -> Void
+ @State private var shown = false
+
+ var body: some View {
+ ZStack {
+ Color.black.opacity(shown ? 0.35 : 0).ignoresSafeArea()
+ .onTapGesture { if cancel != nil { dismiss() } }
+ VStack(spacing: 14) {
+ VStack(spacing: 6) {
+ Text(title).font(.headline).foregroundStyle(Palette.text)
+ if let message, !message.isEmpty {
+ Text(message).font(InterfaceMetrics.secondary).foregroundStyle(Palette.secondary)
+ }
+ }
+ .multilineTextAlignment(.center)
+ VStack(spacing: 8) {
+ ForEach(actions) { action in
+ Button {
+ dismiss()
+ action.action()
+ } label: {
+ Text(action.title).frame(maxWidth: .infinity)
+ }
+ .buttonStyle(DialogButtonStyle(destructive: action.destructive, prominent: true))
+ }
+ if let cancel {
+ Button(action: dismiss) { Text(cancel).frame(maxWidth: .infinity) }
+ .buttonStyle(DialogButtonStyle(destructive: false, prominent: false))
+ .keyboardShortcut(.cancelAction)
+ }
+ }
+ }
+ .padding(18)
+ .frame(maxWidth: 320)
+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
+ .shadow(color: .black.opacity(0.25), radius: 24, y: 10)
+ .padding(24)
+ .scaleEffect(shown ? 1 : 0.96)
+ .opacity(shown ? 1 : 0)
+ }
+ .onAppear { withAnimation(Motion.layout) { shown = true } }
+ .accessibilityAddTraits(.isModal)
+ }
+}
+
+private struct DialogButtonStyle: ButtonStyle {
+ let destructive: Bool
+ let prominent: Bool
+
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .font(InterfaceMetrics.body.weight(.medium))
+ .foregroundStyle(destructive ? Color.white : (prominent ? Palette.onAccent : Palette.text))
+ .padding(.vertical, InterfaceMetrics.value(mac: 8, mobile: 12))
+ .background(destructive ? Palette.danger : (prominent ? Palette.accentFill : Palette.bubbleUser), in: Capsule())
+ .opacity(configuration.isPressed ? 0.85 : 1)
+ .scaleEffect(configuration.isPressed ? Motion.pressScale : 1)
+ .animation(Motion.press, value: configuration.isPressed)
+ .contentShape(Capsule())
+ }
+}
+
+// MARK: - Shared bits
+
+extension View {
+ /// The value pill: a filled rounded box, no border.
+ func pill(fill: Color = Palette.background) -> some View {
+ padding(.horizontal, InterfaceMetrics.value(mac: 9, mobile: 12))
+ .padding(.vertical, InterfaceMetrics.value(mac: 5, mobile: 7))
+ .background(fill, in: RoundedRectangle(cornerRadius: 10, style: .continuous))
+ }
+}
+
+#if os(macOS)
+/// Intercepts only secondary clicks; primary clicks, scrolling and dragging pass through.
+public struct SecondaryClickCapture: NSViewRepresentable {
+ let onClick: (CGPoint) -> Void
+
+ public init(onClick: @escaping (CGPoint) -> Void) { self.onClick = onClick }
+
+ public func makeNSView(context: Context) -> CaptureView { CaptureView(onClick: onClick) }
+ public func updateNSView(_ view: CaptureView, context: Context) { view.onClick = onClick }
+
+ public final class CaptureView: NSView {
+ var onClick: (CGPoint) -> Void
+ override public var isFlipped: Bool { true }
+
+ init(onClick: @escaping (CGPoint) -> Void) {
+ self.onClick = onClick
+ super.init(frame: .zero)
+ }
+ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
+
+ override public func hitTest(_ point: NSPoint) -> NSView? {
+ guard let event = NSApp.currentEvent,
+ event.type == .rightMouseDown || (event.type == .leftMouseDown && event.modifierFlags.contains(.control))
+ else { return nil }
+ return super.hitTest(point)
+ }
+ override public func rightMouseDown(with event: NSEvent) { onClick(convert(event.locationInWindow, from: nil)) }
+ override public func mouseDown(with event: NSEvent) { onClick(convert(event.locationInWindow, from: nil)) }
+ }
+}
+#endif
diff --git a/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift b/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift
index c83ba058..8f00ab8d 100644
--- a/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift
+++ b/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift
@@ -202,7 +202,6 @@ public struct MarketplaceView: View {
HStack(spacing: -8) {
ForEach(model.installedConnectors.prefix(3)) { c in
ServiceLogo(website: nil, name: c.name, registryName: c.registryName, size: 26)
- .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).stroke(Palette.background, lineWidth: 2))
}
}
Text("\(installedCount) installed").foregroundStyle(Palette.secondary).lineLimit(1).fixedSize()
@@ -268,10 +267,9 @@ private struct InstalledView: View {
}
var body: some View {
- Form {
+ CardForm {
if ownsHeader {
- Section {
- HStack(spacing: 6) {
+ HStack(spacing: 6) {
Button("Back", systemImage: "chevron.left") { dismiss() }
.labelStyle(.iconOnly)
.font(.system(size: 15, weight: .semibold))
@@ -282,16 +280,14 @@ private struct InstalledView: View {
.keyboardShortcut(.cancelAction)
.help("Back to Marketplace")
Text("Installed").font(.title2.weight(.semibold)).foregroundStyle(Palette.text)
- }
- .padding(.leading, -12)
}
- .listRowBackground(Color.clear)
+ .padding(.leading, -12)
}
if model.installedConnectors.isEmpty && model.installedSkills.isEmpty {
ContentUnavailableView("Nothing installed", systemImage: "shippingbox", description: Text("Connectors and skills you add show up here."))
}
if !model.installedConnectors.isEmpty {
- Section("Connectors") {
+ CardSection("Connectors") {
ForEach(model.installedConnectors) { c in
InstalledRow(title: c.name, subtitle: c.command ?? c.url ?? c.description) {
ServiceLogo(website: nil, name: c.name, registryName: c.registryName, size: 32)
@@ -302,7 +298,7 @@ private struct InstalledView: View {
}
}
if !model.installedSkills.isEmpty {
- Section("Skills") {
+ CardSection("Skills") {
ForEach(model.installedSkills) { s in
InstalledRow(title: s.name, subtitle: s.description) {
SkillGlyph().frame(width: 32, height: 32)
@@ -313,11 +309,15 @@ private struct InstalledView: View {
}
}
}
- .formStyle(.grouped)
.navigationTitle("Installed")
.inlineNavigationTitle()
- .confirmationDialog("Remove \(removing?.name ?? "")?", isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } }), presenting: removing) { r in
- Button("Remove", role: .destructive) {
+ .codyncDialog(
+ "Remove \(removing?.name ?? "")?",
+ isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } }),
+ message: removing.map { $0.isSkill ? "Bots stop using this skill." : "Bots lose this connector, and the keys saved for it are deleted." }
+ ) {
+ guard let r = removing else { return [] }
+ return [DialogAction("Remove", destructive: true) {
Task {
do {
if r.isSkill { try await model.removeSkill(r.id) } else { try await model.removeConnector(r.id) }
@@ -325,9 +325,7 @@ private struct InstalledView: View {
model.lastError = error.localizedDescription
}
}
- }
- } message: { r in
- Text(r.isSkill ? "Bots stop using this skill." : "Bots lose this connector, and the keys saved for it are deleted.")
+ }]
}
}
}
@@ -348,7 +346,7 @@ private struct InstalledRow<Icon: View>: View {
Spacer(minLength: 12)
Button("Remove \(title)", systemImage: "trash", role: .destructive, action: remove)
.labelStyle(.iconOnly)
- .buttonStyle(.borderless)
+ .buttonStyle(.plain)
.foregroundStyle(Palette.secondary)
.frame(minWidth: 44, minHeight: 44)
.contentShape(Rectangle())
@@ -411,8 +409,7 @@ private struct AgentCard: View {
.frame(maxWidth: .infinity)
.padding(.vertical, 18)
.padding(.horizontal, 10)
- .background(hovering ? Palette.bubbleAgent.opacity(0.6) : Palette.background, in: RoundedRectangle(cornerRadius: 18, style: .continuous))
- .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).stroke(Palette.border))
+ .background(Palette.bubbleAgent.opacity(hovering ? 0.8 : 0.45), in: RoundedRectangle(cornerRadius: 18, style: .continuous))
.contentShape(RoundedRectangle(cornerRadius: 18, style: .continuous))
}
.buttonStyle(PressScale())
@@ -441,8 +438,8 @@ private struct AgentSheet: View {
private var signedIn: Bool? { auth?.signedIn ?? backend.signedIn }
var body: some View {
- Form {
- Section {
+ CardForm {
+ CardSection {
HStack(spacing: 14) {
AgentIcon(registry: backend.registry, size: 30)
.frame(width: 52, height: 52)
@@ -457,7 +454,7 @@ private struct AgentSheet: View {
.padding(.vertical, 4)
}
if curated {
- Section {
+ CardSection {
SetupStepRow(
number: 1,
title: "Install",
@@ -471,10 +468,9 @@ private struct AgentSheet: View {
}
signInSection
if let error {
- Section { Text(error).foregroundStyle(Palette.danger).textSelection(.enabled) }
+ CardSection { Text(error).foregroundStyle(Palette.danger).textSelection(.enabled) }
}
}
- .formStyle(.grouped)
.navigationTitle(backend.name)
.inlineNavigationTitle()
.navigationDestination(item: $route) { route in
@@ -497,8 +493,10 @@ private struct AgentSheet: View {
}
}
- @ViewBuilder private var signInSection: some View {
- Section {
+ private var signInSection: some View {
+ CardSection(footer: signedIn != true && auth?.methods.contains(where: { $0.kind == .agent }) == true
+ ? "Browser sign-ins open on \(model.hostName) itself. Away from it? Use Remote screen to finish there."
+ : nil) {
HStack(spacing: 0) {
SetupStepRow(number: curated ? 2 : 1, title: "Sign in", detail: statusText, done: signedIn == true, action: nil)
if checking {
@@ -545,10 +543,6 @@ private struct AgentSheet: View {
}
}
}
- } footer: {
- if signedIn != true, auth?.methods.contains(where: { $0.kind == .agent }) == true {
- Text("Browser sign-ins open on \(model.hostName) itself. Away from it? Use Remote screen to finish there.")
- }
}
}
@@ -634,25 +628,24 @@ private struct AgentKeysForm: View {
private var vars: [AuthMethod.Var] { method.vars ?? [] }
var body: some View {
- Form {
- Section {
- ForEach(vars, id: \.name) { v in
- VStack(alignment: .leading, spacing: 4) {
- let prompt = Text(saved.contains(v.name) ? "Saved (type to replace)" : v.name)
- Group {
- if v.secret {
- SecureField(v.label, text: binding(v.name), prompt: prompt)
- } else {
- TextField(v.label, text: binding(v.name), prompt: prompt)
+ CardForm {
+ VStack(alignment: .leading, spacing: 6) {
+ CardSection(method.name) {
+ ForEach(vars, id: \.name) { v in
+ VStack(alignment: .leading, spacing: 4) {
+ let prompt = Text(saved.contains(v.name) ? "Saved (type to replace)" : v.name)
+ Group {
+ if v.secret {
+ SecureField(v.label, text: binding(v.name), prompt: prompt)
+ } else {
+ TextField(v.label, text: binding(v.name), prompt: prompt)
+ }
}
+ .plainTextInput()
+ Text(v.label + (v.optional ? " (optional)" : "")).font(.caption).foregroundStyle(Palette.secondary)
}
- .plainTextInput()
- Text(v.label + (v.optional ? " (optional)" : "")).font(.caption).foregroundStyle(Palette.secondary)
}
}
- } header: {
- Text(method.name)
- } footer: {
VStack(alignment: .leading, spacing: 6) {
if let d = method.description { Text(d) }
Text("Saved on \(model.hostName) only and given to \(backend.name) when it starts.")
@@ -660,25 +653,30 @@ private struct AgentKeysForm: View {
Link("Get a key", destination: url)
}
}
+ .font(.caption)
+ .foregroundStyle(Palette.tertiary)
+ .padding(.horizontal, 4)
}
if !saved.isEmpty {
- Section {
+ CardSection {
Button("Remove saved keys", role: .destructive) {
save(Dictionary(uniqueKeysWithValues: vars.map { ($0.name, "") }))
}
+ .buttonStyle(.plain)
+ .foregroundStyle(Palette.danger)
}
}
if let error {
- Section { Text(error).foregroundStyle(Palette.danger) }
+ CardSection { Text(error).foregroundStyle(Palette.danger) }
}
}
- .formStyle(.grouped)
+ .textFieldStyle(.plain)
.navigationTitle(backend.name)
.inlineNavigationTitle()
.toolbar {
ToolbarItem(placement: .confirmationAction) {
if saving {
- ProgressView()
+ Spinner()
} else {
Button("Save") { save(values.filter { !$0.value.isEmpty }) }
.disabled(vars.contains { !$0.optional && (values[$0.name] ?? "").isEmpty && !saved.contains($0.name) })
@@ -860,7 +858,6 @@ private struct ServiceLogo: View {
}
.frame(width: size, height: size)
.clipShape(shape)
- .overlay(shape.stroke(Palette.border.opacity(0.6)))
}
}
@@ -889,8 +886,8 @@ private struct InstallConnectorSheet: View {
}
var body: some View {
- Form {
- Section {
+ CardForm {
+ CardSection {
VStack(alignment: .leading, spacing: 6) {
Text(item.title).font(.title3.weight(.semibold))
if let d = item.description { Text(d).foregroundStyle(Palette.secondary) }
@@ -901,18 +898,14 @@ private struct InstallConnectorSheet: View {
.padding(.vertical, 4)
}
if item.options.count > 1 {
- Section("Runs") {
- Picker("Runs", selection: $optionId) {
- ForEach(item.options) { o in
- Text(o.kind == "remote" ? "Hosted by \(item.title)" : "On \(model.hostName) (\(o.kind))").tag(o.id)
- }
- }
- .labelsHidden()
- .pickerStyle(.inline)
+ CardSection("Runs") {
+ ChoiceList(selection: $optionId, options: item.options.map { o in
+ (id: o.id, label: o.kind == "remote" ? "Hosted by \(item.title)" : "On \(model.hostName) (\(o.kind))", detail: nil)
+ })
}
}
if let option {
- Section {
+ CardSection("Setup", footer: "Keys are saved on \(model.hostName) only.") {
if option.inputs.isEmpty {
Text(option.kind == "remote"
? "No keys needed here. If the service asks you to sign in, the agent shows how the first time it's used."
@@ -934,17 +927,13 @@ private struct InstallConnectorSheet: View {
}
}
}
- } header: {
- Text("Setup")
- } footer: {
- Text("Keys are saved on \(model.hostName) only.")
}
}
if let error {
- Section { Text(error).foregroundStyle(Palette.danger) }
+ CardSection { Text(error).foregroundStyle(Palette.danger) }
}
}
- .formStyle(.grouped)
+ .textFieldStyle(.plain)
.navigationTitle("Add connector")
.inlineNavigationTitle()
.onAppear { optionId = item.options.first?.id ?? "" }
@@ -954,7 +943,7 @@ private struct InstallConnectorSheet: View {
}
ToolbarItem(placement: .confirmationAction) {
if saving {
- ProgressView()
+ Spinner()
} else {
Button("Add") { install() }
.disabled(option?.inputs.contains { $0.required && (values[$0.name] ?? "").isEmpty } ?? true)
@@ -995,37 +984,27 @@ private struct CustomConnectorSheet: View {
@State private var error: String?
var body: some View {
- Form {
- Section {
+ CardForm {
+ CardSection(footer: remote ? "A remote MCP server (streamable HTTP)." : "Runs on \(model.hostName) in the bot's project folder.") {
TextField("Name", text: $name)
- Picker("Type", selection: $remote) {
- Text("Command").tag(false)
- Text("URL").tag(true)
- }
- .pickerStyle(.segmented)
+ 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()
- } footer: {
- Text(remote ? "A remote MCP server (streamable HTTP)." : "Runs on \(model.hostName) in the bot's project folder.")
}
if !remote {
- Section {
+ CardSection("Environment", footer: "One KEY=value per line. Saved on \(model.hostName) only.") {
TextField("API_KEY=…", text: $envText, axis: .vertical)
.lineLimit(2...6)
.font(.callout.monospaced())
.plainTextInput()
- } header: {
- Text("Environment")
- } footer: {
- Text("One KEY=value per line. Saved on \(model.hostName) only.")
}
}
if let error {
- Section { Text(error).foregroundStyle(Palette.danger) }
+ CardSection { Text(error).foregroundStyle(Palette.danger) }
}
}
- .formStyle(.grouped)
+ .textFieldStyle(.plain)
.navigationTitle("Custom connector")
.inlineNavigationTitle()
.toolbar {
@@ -1034,7 +1013,7 @@ private struct CustomConnectorSheet: View {
}
ToolbarItem(placement: .confirmationAction) {
if saving {
- ProgressView()
+ Spinner()
} else {
Button("Add") { save() }
.disabled(name.trimmingCharacters(in: .whitespaces).isEmpty || target.trimmingCharacters(in: .whitespaces).isEmpty)
@@ -1073,22 +1052,20 @@ private struct NewSkillSheet: View {
@State private var error: String?
var body: some View {
- Form {
- Section {
+ CardForm {
+ CardSection(footer: "The bot sees the name and when to use it, and reads the instructions only when a task fits.") {
TextField("Name", text: $name)
TextField("When to use it", text: $summary, axis: .vertical).lineLimit(2...4)
- } footer: {
- Text("The bot sees the name and when to use it, and reads the instructions only when a task fits.")
}
- Section("Instructions") {
+ CardSection("Instructions") {
TextField("Step by step, in plain words…", text: $instructions, axis: .vertical)
.lineLimit(6...20)
}
if let error {
- Section { Text(error).foregroundStyle(Palette.danger) }
+ CardSection { Text(error).foregroundStyle(Palette.danger) }
}
}
- .formStyle(.grouped)
+ .textFieldStyle(.plain)
.navigationTitle("New skill")
.inlineNavigationTitle()
.toolbar {
@@ -1097,7 +1074,7 @@ private struct NewSkillSheet: View {
}
ToolbarItem(placement: .confirmationAction) {
if saving {
- ProgressView()
+ Spinner()
} else {
Button("Save") {
saving = true
diff --git a/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swift b/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swift
index 99c4172a..a73d71af 100644
--- a/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swift
+++ b/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swift
@@ -58,7 +58,7 @@ struct SetupTerminalView: View {
}
Spacer(minLength: 0)
if session.exitCode != nil {
- Button("Done") { dismiss() }.buttonStyle(.borderedProminent)
+ Button("Done") { dismiss() }.buttonStyle(.primary)
}
}
.font(.footnote)
diff --git a/kit/Sources/CodyncUI/Platform.swift b/kit/Sources/CodyncUI/Platform.swift
index 76cfab1d..d9bb9505 100644
--- a/kit/Sources/CodyncUI/Platform.swift
+++ b/kit/Sources/CodyncUI/Platform.swift
@@ -34,14 +34,6 @@ extension View {
autocorrectionDisabled()
#endif
}
-
- @ViewBuilder func groupedList() -> some View {
- #if os(iOS)
- listStyle(.insetGrouped)
- #else
- listStyle(.inset)
- #endif
- }
}
extension View {
@@ -56,12 +48,11 @@ extension View {
}
extension View {
- /// The message box: Liquid Glass on iPhone; on the Mac a white box with a
- /// hairline border and a soft shadow (as in Grok Bot's desktop app).
+ /// The message box: Liquid Glass on iPhone; on the Mac a filled box with a
+ /// soft shadow (as in Grok Bot's desktop app).
@ViewBuilder func composerSurface(in shape: some Shape) -> some View {
#if os(macOS)
background(Palette.bubbleUser, in: shape)
- .overlay(shape.stroke(Palette.border))
.shadow(color: .black.opacity(0.06), radius: 10, y: 2)
#else
glass(in: shape)
diff --git a/kit/Sources/CodyncUI/Screen/ScreenView.swift b/kit/Sources/CodyncUI/Screen/ScreenView.swift
index 9b1f56db..16f3a422 100644
--- a/kit/Sources/CodyncUI/Screen/ScreenView.swift
+++ b/kit/Sources/CodyncUI/Screen/ScreenView.swift
@@ -110,9 +110,9 @@ public struct ScreenView: View {
IconButton("Fit screen", "arrow.down.right.and.arrow.up.left") { resetToken += 1 }
}
if let displays = screen?.displays, displays.count > 1 {
- Menu {
- ForEach(displays) { d in
- Button(d.name, systemImage: d.id == display?.id ? "checkmark" : "display") {
+ DropdownMenu {
+ displays.map { d in
+ MenuItem(d.name, icon: "display", selected: d.id == display?.id) {
display = d
session?.switchDisplay(d)
resetToken += 1
@@ -130,15 +130,20 @@ public struct ScreenView: View {
}
private var clipboardMenu: some View {
- Menu {
- Button("Send my clipboard", systemImage: "arrow.up.doc.on.clipboard") {
- if let text = UIPasteboard.general.string { session?.pushClipboard(text) }
+ // MenuItem has no disabled state: unavailable actions are left out instead.
+ DropdownMenu {
+ var items: [MenuItem] = []
+ if UIPasteboard.general.hasStrings {
+ items.append(MenuItem("Send my clipboard", icon: "arrow.up.doc.on.clipboard") {
+ if let text = UIPasteboard.general.string { session?.pushClipboard(text) }
+ })
}
- .disabled(!UIPasteboard.general.hasStrings)
- Button("Copy from computer", systemImage: "arrow.down.doc.on.clipboard") {
- if let text = session?.takeRemoteClipboard() { UIPasteboard.general.string = text }
+ if session?.remoteClipboard != nil {
+ items.append(MenuItem("Copy from computer", icon: "arrow.down.doc.on.clipboard") {
+ if let text = session?.takeRemoteClipboard() { UIPasteboard.general.string = text }
+ })
}
- .disabled(session?.remoteClipboard == nil)
+ return items
} label: {
IconLabel("Clipboard", session?.remoteClipboard == nil ? "doc.on.clipboard" : "doc.on.clipboard.fill")
}
@@ -188,13 +193,13 @@ private struct Overlay: View {
if let icon {
Image(systemName: icon).font(.largeTitle).foregroundStyle(.secondary)
} else {
- ProgressView()
+ Spinner(size: 22)
}
Text(text).font(.callout).multilineTextAlignment(.center).foregroundStyle(.secondary)
if let retry {
Button("Try again", systemImage: "arrow.clockwise", action: retry)
.labelStyle(.iconOnly)
- .buttonStyle(.bordered)
+ .buttonStyle(.secondary)
}
}
.padding(32)
diff --git a/kit/Sources/CodyncUI/Thread/ChatRows.swift b/kit/Sources/CodyncUI/Thread/ChatRows.swift
index a2e550c2..261b80e4 100644
--- a/kit/Sources/CodyncUI/Thread/ChatRows.swift
+++ b/kit/Sources/CodyncUI/Thread/ChatRows.swift
@@ -17,8 +17,8 @@ struct UserBubble: View {
.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))
- .contextMenu {
- Button("Copy", systemImage: "doc.on.doc") { Pasteboard.copy(entry.data.text) }
+ .contextActions {
+ [MenuItem("Copy", icon: "doc.on.doc") { Pasteboard.copy(entry.data.text) }]
}
status
}
@@ -38,6 +38,7 @@ struct UserBubble: View {
Button("Resend", systemImage: "arrow.clockwise") { model.retry(entry) }.labelStyle(.iconOnly).help("Resend")
Button("Delete", systemImage: "trash") { model.discard(entry) }.labelStyle(.iconOnly).help("Delete")
}
+ .buttonStyle(.plain)
.font(.caption2.bold())
case "cancelled":
Text("Not sent — stopped").font(.caption2).foregroundStyle(Palette.tertiary)
@@ -61,9 +62,11 @@ struct AgentBubble: View {
.padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 16))
.padding(.vertical, InterfaceMetrics.value(mac: 8, mobile: 10))
.background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
- .contextMenu {
- Button("Copy", systemImage: "doc.on.doc") { Pasteboard.copy(entry.data.text) }
- Button("Show what it did", systemImage: "list.bullet.rectangle", action: openTrace)
+ .contextActions {
+ [
+ MenuItem("Copy", icon: "doc.on.doc") { Pasteboard.copy(entry.data.text) },
+ MenuItem("Show what it did", icon: "list.bullet.rectangle", action: openTrace),
+ ]
}
#if os(macOS)
Text(entry.date, style: .time)
diff --git a/kit/Sources/CodyncUI/Thread/MarkdownText.swift b/kit/Sources/CodyncUI/Thread/MarkdownText.swift
index 8b1afd62..00e10245 100644
--- a/kit/Sources/CodyncUI/Thread/MarkdownText.swift
+++ b/kit/Sources/CodyncUI/Thread/MarkdownText.swift
@@ -55,7 +55,6 @@ public struct MarkdownText: View {
.padding(10)
}
.background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 8))
- .overlay(RoundedRectangle(cornerRadius: 8).stroke(Palette.border))
}
}
diff --git a/kit/Sources/CodyncUI/Thread/PermissionCard.swift b/kit/Sources/CodyncUI/Thread/PermissionCard.swift
index d9db9421..c9f23633 100644
--- a/kit/Sources/CodyncUI/Thread/PermissionCard.swift
+++ b/kit/Sources/CodyncUI/Thread/PermissionCard.swift
@@ -39,7 +39,7 @@ struct PermissionCard: View {
.foregroundStyle(Palette.tertiary)
if hasDetail {
- DisclosureGroup(isExpanded: $expanded) {
+ Disclosure(isExpanded: $expanded) {
VStack(alignment: .leading, spacing: 8) {
if let command = d.command, !command.isEmpty {
CodeBox(text: command)
@@ -105,7 +105,6 @@ struct PermissionCard: View {
}
}
.background(Palette.background, in: RoundedRectangle(cornerRadius: 14, style: .continuous))
- .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).stroke(Palette.border))
.padding(.top, 4)
}
diff --git a/kit/Sources/CodyncUI/Thread/ThreadView.swift b/kit/Sources/CodyncUI/Thread/ThreadView.swift
index ecfe7b17..9078885a 100644
--- a/kit/Sources/CodyncUI/Thread/ThreadView.swift
+++ b/kit/Sources/CodyncUI/Thread/ThreadView.swift
@@ -169,10 +169,9 @@ public struct ThreadView: View {
.sheet(item: $editing) { request in
NavigationStack { BotEditorView(draft: request.draft) }
}
- .confirmationDialog("Start a new session?", isPresented: $confirmNewSession, titleVisibility: .visible) {
- Button("New session") { model.newSession(botId) }
- } message: {
- Text("The conversation stays here, but the agent starts with a fresh context.")
+ .codyncDialog("Start a new session?", isPresented: $confirmNewSession,
+ message: "The conversation stays here, but the agent starts with a fresh context.") {
+ [DialogAction("New session") { model.newSession(botId) }]
}
.deleteBotConfirmation($confirmDelete) { dismiss() }
}
@@ -283,7 +282,6 @@ public struct ThreadView: View {
.frame(maxWidth: .infinity)
.frame(height: 164)
.background(Palette.surface, in: RoundedRectangle(cornerRadius: 8))
- .overlay(RoundedRectangle(cornerRadius: 8).stroke(Palette.border, lineWidth: 0.5))
Text(model.hostName)
.font(.caption)
.foregroundStyle(Palette.tertiary)
@@ -334,10 +332,10 @@ public struct ThreadView: View {
#endif
private var menu: some View {
- Menu {
- Button("Full conversation", systemImage: "list.bullet.rectangle") { showTrace = true }
+ DropdownMenu {
+ var items = [MenuItem("Full conversation", icon: "list.bullet.rectangle") { showTrace = true }]
if let bot {
- Button("Edit profile", systemImage: "pencil") {
+ items.append(MenuItem("Edit profile", icon: "pencil") {
#if os(macOS)
editingDetails = true
showSettings = true
@@ -345,15 +343,16 @@ public struct ThreadView: View {
#else
editing = EditorRequest(BotDraft(bot))
#endif
- }
- Button(bot.pinned ? "Unpin" : "Pin", systemImage: "pin") { model.setPinned(bot, !bot.pinned) }
+ })
+ items.append(MenuItem(bot.pinned ? "Unpin" : "Pin", icon: "pin") { model.setPinned(bot, !bot.pinned) })
}
- Button("New session", systemImage: "arrow.counterclockwise") { confirmNewSession = true }
- Divider()
- Button("Delete bot", systemImage: "trash", role: .destructive) { confirmDelete = bot }
+ items.append(MenuItem("New session", icon: "arrow.counterclockwise") { confirmNewSession = true })
+ items.append(MenuItem("Delete bot", icon: "trash", destructive: true, divider: true) { confirmDelete = bot })
+ return items
} label: {
Image(systemName: "ellipsis.circle")
}
+ .accessibilityLabel("More")
}
private var canSend: Bool {
diff --git a/kit/Sources/CodyncUI/Thread/TraceView.swift b/kit/Sources/CodyncUI/Thread/TraceView.swift
index 3e3c65c8..6da96040 100644
--- a/kit/Sources/CodyncUI/Thread/TraceView.swift
+++ b/kit/Sources/CodyncUI/Thread/TraceView.swift
@@ -13,22 +13,28 @@ public struct TraceView: View {
public var body: some View {
let turns = Dictionary(grouping: model.thread(botId), by: \.turn)
.sorted { $0.key < $1.key }
- List {
- if turns.isEmpty {
- Text("Nothing yet.").foregroundStyle(Palette.tertiary)
- }
- ForEach(turns, id: \.key) { turn, entries in
- Section {
- ForEach(entries) { TraceRow(entry: $0) }
- } header: {
- Text(entries.first { $0.kind == "user" }?.data.text ?? "Turn \(turn)")
- .lineLimit(1)
- .textCase(nil)
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 14, mobile: 22)) {
+ if turns.isEmpty {
+ Text("Nothing yet.").foregroundStyle(Palette.tertiary)
+ }
+ ForEach(turns, id: \.key) { turn, entries in
+ VStack(alignment: .leading, spacing: 6) {
+ // CardSection's own title wraps; a turn header stays on one line.
+ Text(entries.first { $0.kind == "user" }?.data.text ?? "Turn \(turn)")
+ .lineLimit(1)
+ .font(InterfaceMetrics.secondary)
+ .foregroundStyle(Palette.secondary)
+ .padding(.leading, 4)
+ CardSection {
+ ForEach(entries) { TraceRow(entry: $0) }
+ }
+ }
}
}
+ .padding(InterfaceMetrics.value(mac: 14, mobile: 20))
+ .frame(maxWidth: .infinity, alignment: .leading)
}
- .groupedList()
- .scrollContentBackground(.hidden)
.background(Palette.background)
.navigationTitle("Full conversation")
.inlineNavigationTitle()
@@ -43,6 +49,7 @@ public struct TraceView: View {
private struct TraceRow: View {
let entry: Entry
+ @State private var expanded = false
var body: some View {
let d = entry.data
@@ -56,7 +63,7 @@ private struct TraceRow: View {
MarkdownText(d.text ?? "")
}
case "thought":
- DisclosureGroup {
+ Disclosure(isExpanded: $expanded) {
Text(d.text ?? "").font(.footnote).foregroundStyle(Palette.secondary).textSelection(.enabled)
} label: {
Label { Text("Thinking") } icon: {
@@ -90,6 +97,7 @@ private struct TraceRow: View {
struct ToolRow: View {
let data: EntryData
+ @State private var expanded = false
private var icon: String {
switch data.toolKind {
@@ -111,7 +119,7 @@ struct ToolRow: View {
var body: some View {
if hasBody {
- DisclosureGroup {
+ Disclosure(isExpanded: $expanded) {
VStack(alignment: .leading, spacing: 8) {
ForEach(data.diffs ?? [], id: \.self) { DiffView(diff: $0) }
if let out = data.output, !out.isEmpty { CodeBox(text: out) }
diff --git a/kit/Sources/CodyncUI/Usage/UsageViews.swift b/kit/Sources/CodyncUI/Usage/UsageViews.swift
index ff8f1e78..b0ae8e5c 100644
--- a/kit/Sources/CodyncUI/Usage/UsageViews.swift
+++ b/kit/Sources/CodyncUI/Usage/UsageViews.swift
@@ -14,11 +14,7 @@ public struct UsageStrip: View {
ForEach(p.windows.prefix(2)) { w in
HStack(spacing: 6) {
AgentIcon(registry: p.registry, size: 14)
- Gauge(value: min(w.percent, 100), in: 0...100) { EmptyView() }
- .gaugeStyle(.accessoryCircularCapacity)
- .scaleEffect(0.42)
- .frame(width: 22, height: 22)
- .tint(Palette.usageTint(w.percent))
+ UsageRing(percent: w.percent)
VStack(alignment: .leading, spacing: 0) {
Text(w.title).font(.caption2).foregroundStyle(Palette.tertiary)
Text("\(Int(w.percent.rounded()))%").font(.caption.bold().monospacedDigit()).foregroundStyle(Palette.text)
@@ -27,10 +23,27 @@ public struct UsageStrip: View {
.padding(.horizontal, 10)
.padding(.vertical, 6)
.background(Palette.surface, in: Capsule())
- .overlay(Capsule().stroke(Palette.border))
}
}
}
}
}
}
+
+/// A small capacity ring: the replacement for the circular `Gauge`.
+private struct UsageRing: View {
+ let percent: Double
+
+ var body: some View {
+ ZStack {
+ Circle().stroke(Palette.text.opacity(0.1), lineWidth: 2.5)
+ Circle()
+ .trim(from: 0, to: min(max(percent, 0), 100) / 100)
+ .stroke(Palette.usageTint(percent), style: StrokeStyle(lineWidth: 2.5, lineCap: .round))
+ .rotationEffect(.degrees(-90))
+ }
+ .frame(width: 16, height: 16)
+ .frame(width: 22, height: 22)
+ .accessibilityHidden(true)
+ }
+}