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.

feat(kit): add routines, model picker and connector sign-in

leepokai4dab2ce3d05b
diff --git a/kit/Sources/CodyncKit/Client/HostClient.swift b/kit/Sources/CodyncKit/Client/HostClient.swift
index 5e4e9225..1883b42b 100644
--- a/kit/Sources/CodyncKit/Client/HostClient.swift
+++ b/kit/Sources/CodyncKit/Client/HostClient.swift
@@ -26,6 +26,20 @@ public struct Empty: Codable, Sendable {
public init() {}
}
+/// A full editor update must explicitly clear a previous model override.
+struct BotUpdate: Encodable {
+ let draft: BotDraft
+ private enum CodingKeys: String, CodingKey { case model }
+
+ func encode(to encoder: Encoder) throws {
+ try draft.encode(to: encoder)
+ if draft.model == nil {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeNil(forKey: .model)
+ }
+ }
+}
+
public struct HostClient: Sendable {
public let transport: any HostTransport
@@ -167,7 +181,7 @@ public extension HostClient {
func updateBot(_ draft: BotDraft) async throws -> Bot {
struct Res: Decodable { var bot: Bot }
- let res: Res = try await call("updateBot", draft)
+ let res: Res = try await call("updateBot", BotUpdate(draft: draft))
return res.bot
}
@@ -175,8 +189,17 @@ public extension HostClient {
let _: Empty = try await call("deleteBot", ["botId": id])
}
- func markRead(_ id: String) async throws {
- let _: Empty = try await call("markRead", ["botId": id])
+ /// The main chat, one thread (`threadId`), or everything (`all`).
+ func markRead(_ id: String, threadId: String? = nil, all: Bool = false) async throws {
+ struct Body: Encodable { var botId: String; var threadId: String?; var all: Bool }
+ let _: Empty = try await call("markRead", Body(botId: id, threadId: threadId, all: all))
+ }
+
+ /// Toggles the user's `emoji` reaction on a chat message.
+ func react(entryId: String, emoji: String) async throws -> Entry {
+ struct Res: Decodable { var entry: Entry }
+ let res: Res = try await call("react", ["entryId": entryId, "emoji": emoji])
+ return res.entry
}
/// `threadId`: reply in the thread on that main-chat message.
@@ -268,6 +291,10 @@ public extension HostClient {
}
/// Starts the agent to see whether it's signed in and how it can be (first run may download it).
+ func agentModels(_ backend: String) async throws -> AgentModels {
+ try await call("agentModels", ["backend": backend], timeout: 300)
+ }
+
func agentAuth(_ backend: String) async throws -> AgentAuth {
try await call("agentAuth", ["backend": backend], timeout: 300)
}
diff --git a/kit/Sources/CodyncKit/Design/Motion.swift b/kit/Sources/CodyncKit/Design/Motion.swift
index b3d76822..de274707 100644
--- a/kit/Sources/CodyncKit/Design/Motion.swift
+++ b/kit/Sources/CodyncKit/Design/Motion.swift
@@ -1,4 +1,9 @@
import SwiftUI
+#if os(iOS)
+import UIKit
+#elseif os(macOS)
+import AppKit
+#endif
/// Grok Bot's motion, taken from its stylesheet and motion constants so ours feels the same.
/// With Reduce Motion on, Grok drops every duration to 0; use `Motion.reduced(_:)` for that.
@@ -24,6 +29,19 @@ public enum Motion {
public static func reduced(_ animation: Animation, _ reduce: Bool) -> Animation? {
reduce ? nil : animation
}
+
+ /// Runs a model change outside any view (connection state, account lists) with `layout`,
+ /// so every screen showing it cross-fades instead of jumping. Honors Reduce Motion.
+ @MainActor public static func animate(_ change: () -> Void) {
+ #if os(iOS)
+ let reduce = UIAccessibility.isReduceMotionEnabled
+ #elseif os(macOS)
+ let reduce = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
+ #else
+ let reduce = false
+ #endif
+ withAnimation(reduced(layout, reduce), change)
+ }
}
/// Grok's press: shrink to 98% in 50ms, spring back.
diff --git a/kit/Sources/CodyncKit/Models/AgentModels.swift b/kit/Sources/CodyncKit/Models/AgentModels.swift
new file mode 100644
index 00000000..7f79f6d9
--- /dev/null
+++ b/kit/Sources/CodyncKit/Models/AgentModels.swift
@@ -0,0 +1,13 @@
+import Foundation
+
+/// Model identifiers and display names advertised by the selected computer's ACP agent.
+public struct AgentModels: Decodable, Sendable {
+ public struct Model: Decodable, Identifiable, Sendable {
+ public let id: String
+ public let name: String
+ public let description: String?
+ }
+
+ public let models: [Model]
+ public let currentModelId: String?
+}
diff --git a/kit/Sources/CodyncKit/Models/BotActivity.swift b/kit/Sources/CodyncKit/Models/BotActivity.swift
index 10bf76a9..e25fff6b 100644
--- a/kit/Sources/CodyncKit/Models/BotActivity.swift
+++ b/kit/Sources/CodyncKit/Models/BotActivity.swift
@@ -3,7 +3,7 @@ import ActivityKit
import Foundation
/// Live Activity for a bot working on something the user just delegated.
-/// Content state keys must match what codync-host pushes (host/src/push.rs).
+/// Content state keys must match what codync-host pushes (host/src/remote/push.rs).
public struct BotActivityAttributes: ActivityAttributes {
public struct ContentState: Codable, Hashable, Sendable {
/// idle | working | needsInput | error
diff --git a/kit/Sources/CodyncKit/Models/Market.swift b/kit/Sources/CodyncKit/Models/Market.swift
index dc45e7c0..481919e2 100644
--- a/kit/Sources/CodyncKit/Models/Market.swift
+++ b/kit/Sources/CodyncKit/Models/Market.swift
@@ -1,6 +1,6 @@
import Foundation
-// Marketplace wire types (host/src/market.rs): connectors are MCP servers,
+// Marketplace wire types (host/src/market/mod.rs): connectors are MCP servers,
// skills are instruction folders; agents come from `Hello.backends`.
public struct InstalledConnector: Codable, Hashable, Sendable, Identifiable {
@@ -16,9 +16,20 @@ public struct InstalledConnector: Codable, Hashable, Sendable, Identifiable {
public var keys: [String]
/// Composio apps: the app's logo.
public var logo: String?
+ /// Remote servers: `none`, `signedOut` (waits for sign-in; bots don't get it yet) or `signedIn`.
+ public var auth: String?
+
+ public var needsSignIn: Bool { auth == "signedOut" }
+}
+
+/// Where a connector's sign-in page is and who catches its return: `app` (the phone's
+/// sign-in sheet, then `finishConnectorSignIn`) or `host` (the computer's own browser).
+public struct ConnectorSignIn: Decodable, Sendable {
+ public var url: String
+ public var callback: String
}
-// MARK: Composio (host/src/composio.rs): apps connected through composio.dev
+// MARK: Composio (host/src/market/composio.rs): apps connected through composio.dev
public struct ComposioStatus: Decodable, Sendable {
public var configured: Bool
@@ -112,6 +123,7 @@ public struct MarketSkill: Codable, Hashable, Sendable, Identifiable {
}
private struct Items<T: Decodable>: Decodable { var items: [T] }
+private struct Installed: Decodable { var connector: InstalledConnector }
public extension HostClient {
func connectors() async throws -> [InstalledConnector] {
@@ -125,15 +137,30 @@ public extension HostClient {
return res.items
}
- func installConnector(registryName: String, option: String, inputs: [String: String]) async throws {
+ @discardableResult
+ func installConnector(registryName: String, option: String, inputs: [String: String]) async throws -> InstalledConnector {
struct Body: Encodable { var registryName: String; var option: String; var inputs: [String: String] }
- let _: Empty = try await call("installConnector", Body(registryName: registryName, option: option, inputs: inputs), timeout: 30)
+ let res: Installed = try await call("installConnector", Body(registryName: registryName, option: option, inputs: inputs), timeout: 45)
+ return res.connector
+ }
+
+ /// A connector you describe yourself: a command line with env, or an https URL with headers.
+ @discardableResult
+ func addConnector(name: String, command: String?, url: String?, env: [String: String], headers: [String: String]) async throws -> InstalledConnector {
+ struct Body: Encodable { var name: String; var command: String?; var url: String?; var env: [String: String]; var headers: [String: String] }
+ let res: Installed = try await call("installConnector", Body(name: name, command: command, url: url, env: env, headers: headers), timeout: 45)
+ return res.connector
+ }
+
+ func connectorSignIn(_ id: String) async throws -> ConnectorSignIn {
+ try await call("connectorSignIn", ["id": id], timeout: 60)
}
- /// A connector you describe yourself: a command line, or an https URL with optional headers.
- func addConnector(name: String, command: String?, url: String?, env: [String: String]) async throws {
- struct Body: Encodable { var name: String; var command: String?; var url: String?; var env: [String: String] }
- let _: Empty = try await call("installConnector", Body(name: name, command: command, url: url, env: env))
+ @discardableResult
+ func finishConnectorSignIn(state: String, code: String?, error: String?) async throws -> InstalledConnector {
+ struct Body: Encodable { var state: String; var code: String?; var error: String? }
+ let res: Installed = try await call("connectorSignInFinish", Body(state: state, code: code, error: error), timeout: 60)
+ return res.connector
}
func removeConnector(_ id: String) async throws {
diff --git a/kit/Sources/CodyncKit/Models/Models.swift b/kit/Sources/CodyncKit/Models/Models.swift
index 88e75e66..281239bf 100644
--- a/kit/Sources/CodyncKit/Models/Models.swift
+++ b/kit/Sources/CodyncKit/Models/Models.swift
@@ -1,6 +1,6 @@
import Foundation
-// Wire types for codync-host (see host/src/api.rs). Field names match the
+// Wire types for codync-host (see host/src/api/mod.rs). Field names match the
// host's camelCase JSON. Timestamps are epoch milliseconds.
public struct Bot: Codable, Identifiable, Hashable, Sendable {
@@ -100,6 +100,8 @@ public struct Entry: Codable, Identifiable, Hashable, Sendable {
}
public struct EntryData: Codable, Hashable, Sendable {
+ public var routineId: String?
+ public var runId: String?
public var text: String?
public var final: Bool?
/// user: queued | sent | cancelled | failed · tool: pending | in_progress | completed | failed · permission: pending | answered | cancelled | expired
@@ -122,6 +124,8 @@ public struct EntryData: Codable, Hashable, Sendable {
public var author: String?
/// On a main-chat message that has a thread: its replies.
public var thread: ThreadSummary?
+ /// The user's emoji reactions, oldest first.
+ public var reactions: [String]?
public init(text: String? = nil, status: String? = nil, clientNonce: String? = nil) {
self.text = text
@@ -135,6 +139,8 @@ public struct ThreadSummary: Codable, Hashable, Sendable {
public var lastAt: Int64
/// Who replied, first reply first: bot ids, and `user`.
public var authors: [String]
+ /// Replies the user hasn't read (threads are read on their own).
+ public var unread: Int?
}
public struct FileDiff: Codable, Hashable, Sendable {
diff --git a/kit/Sources/CodyncKit/Models/Routine.swift b/kit/Sources/CodyncKit/Models/Routine.swift
new file mode 100644
index 00000000..90c77e80
--- /dev/null
+++ b/kit/Sources/CodyncKit/Models/Routine.swift
@@ -0,0 +1,92 @@
+import Foundation
+
+public struct Routine: Codable, Identifiable, Hashable, Sendable {
+ public var id: String
+ public var botId: String
+ public var name: String
+ public var instruction: String
+ public var triggers: [RoutineTrigger]
+ public var enabled: Bool
+ public var createdAt: Int64
+ public var updatedAt: Int64
+ public var triggerDescriptions: [String]
+ public var nextRunAt: Int64?
+ public var timeoutSeconds: Int?
+ public var lastError: String?
+}
+
+public struct RoutineTrigger: Codable, Hashable, Sendable {
+ public var type: String
+ public var seconds: Int64?
+ public var at: Int64?
+ public var expression: String?
+ public var timeZone: String?
+ public var source: String?
+ public var event: String?
+ public var filters: [String: String]?
+
+ public init(type: String, seconds: Int64? = nil, at: Int64? = nil, expression: String? = nil, timeZone: String? = nil) {
+ self.type = type
+ self.seconds = seconds
+ self.at = at
+ self.expression = expression
+ self.timeZone = timeZone
+ }
+}
+
+public struct RoutineRun: Codable, Identifiable, Hashable, Sendable {
+ public var id: String
+ public var routineId: String
+ public var botId: String
+ public var status: String
+ public var createdAt: Int64
+ public var finishedAt: Int64?
+ public var detail: String?
+ public var rootId: String?
+ public var isActive: Bool { ["pending", "starting", "running", "recovering"].contains(status) }
+}
+
+public struct RoutineListing: Codable, Sendable {
+ public var routines: [Routine]
+ public var runs: [RoutineRun]
+}
+
+public struct RoutineWebhook: Codable, Sendable {
+ public var url: String
+ public var key: String
+}
+
+extension HostClient {
+ public func routines(botId: String) async throws -> RoutineListing {
+ struct Body: Encodable { let botId: String }
+ return try await call("routines", Body(botId: botId))
+ }
+
+ public func routineAction(_ method: String, botId: String, id: String, enabled: Bool? = nil) async throws {
+ struct Body: Encodable { let botId: String; let id: String; let enabled: Bool? }
+ let _: Empty = try await call(method, Body(botId: botId, id: id, enabled: enabled))
+ }
+
+ public func routineWebhook(botId: String, id: String) async throws -> RoutineWebhook {
+ struct Body: Encodable { let botId: String; let id: String }
+ return try await call("routineWebhook", Body(botId: botId, id: id))
+ }
+}
+
+extension HostClient {
+ public func saveRoutine(botId: String, id: String?, name: String, instruction: String,
+ triggers: [RoutineTrigger], timeoutSeconds: Int) async throws -> Routine {
+ struct Body: Encodable {
+ let botId: String
+ let id: String?
+ let name: String
+ let instruction: String
+ let triggers: [RoutineTrigger]
+ let timeoutSeconds: Int
+ }
+ struct Response: Decodable { let routine: Routine }
+ let response: Response = try await call("saveRoutine", Body(botId: botId, id: id, name: name,
+ instruction: instruction, triggers: triggers, timeoutSeconds: timeoutSeconds))
+ return response.routine
+ }
+}
diff --git a/kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swift b/kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swift
new file mode 100644
index 00000000..7eab9e26
--- /dev/null
+++ b/kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swift
@@ -0,0 +1,81 @@
+import Foundation
+
+/// Editable common schedules, with a lossless fallback for compound/event triggers.
+public struct RoutineScheduleDraft: Sendable {
+ public var kind = "interval"
+ public var amount = "1"
+ public var unit: Int64 = 3600
+ public var calendarStyle = "daily"
+ public var weekday = 1
+ public var timeOfDay = Date(timeIntervalSince1970: 9 * 3600)
+ public var date = Date().addingTimeInterval(3600)
+ public var expression = "0 9 * * *"
+ public var zone = TimeZone.current.identifier
+ public var original: [RoutineTrigger] = []
+
+ public init(triggers: [RoutineTrigger] = []) {
+ original = triggers
+ guard !triggers.isEmpty else { return }
+ guard triggers.count == 1, let trigger = triggers.first else { kind = "keep"; return }
+ kind = trigger.type
+ switch trigger.type {
+ case "interval":
+ let seconds = trigger.seconds ?? 3600
+ unit = [Int64(86400), 3600, 60, 1].first { seconds % $0 == 0 } ?? 1
+ amount = String(seconds / unit)
+ case "once": date = Date(timeIntervalSince1970: Double(trigger.at ?? 0) / 1000)
+ case "cron":
+ expression = trigger.expression ?? ""
+ zone = trigger.timeZone ?? TimeZone.current.identifier
+ calendarStyle = "custom"
+ let fields = expression.split(separator: " ").map(String.init)
+ if fields.count == 5, let minute = Int(fields[0]), (0...59).contains(minute),
+ let hour = Int(fields[1]), (0...23).contains(hour), fields[2] == "*", fields[3] == "*" {
+ timeOfDay = Date(timeIntervalSince1970: Double(hour * 3600 + minute * 60))
+ if fields[4] == "*" { calendarStyle = "daily" }
+ else if fields[4] == "1-5" { calendarStyle = "weekdays" }
+ else if let day = Int(fields[4]), (0...6).contains(day) {
+ weekday = day
+ calendarStyle = "weekly"
+ }
+ }
+ case "webhook": break
+ default: kind = "keep"
+ }
+ }
+
+ public func triggers() throws -> [RoutineTrigger] {
+ switch kind {
+ case "keep": return original
+ case "interval":
+ guard let count = Int64(amount), count > 0, [1, 60, 3600, 86400].contains(unit) else {
+ throw ValidationError("Enter a positive whole number for the interval.")
+ }
+ let (seconds, overflow) = count.multipliedReportingOverflow(by: unit)
+ guard !overflow, seconds <= 31_536_000 else { throw ValidationError("The interval must be no longer than 365 days.") }
+ return [RoutineTrigger(type: "interval", seconds: seconds)]
+ case "cron":
+ guard TimeZone(identifier: zone) != nil else { throw ValidationError("Enter a valid time zone, such as Asia/Taipei.") }
+ var cron = expression
+ if calendarStyle != "custom" {
+ let seconds = Int(timeOfDay.timeIntervalSince1970)
+ let hour = ((seconds / 3600) % 24 + 24) % 24
+ let minute = ((seconds / 60) % 60 + 60) % 60
+ let days = calendarStyle == "weekly" ? String(weekday) : calendarStyle == "weekdays" ? "1-5" : "*"
+ cron = "\(minute) \(hour) * * \(days)"
+ }
+ return [RoutineTrigger(type: "cron", expression: cron, timeZone: zone)]
+ case "once":
+ if original.count == 1, original[0].type == "once", let at = original[0].at,
+ date == Date(timeIntervalSince1970: Double(at) / 1000) { return original }
+ return [RoutineTrigger(type: "once", at: Int64((date.timeIntervalSince1970 * 1000).rounded()))]
+ case "webhook": return [RoutineTrigger(type: "webhook")]
+ default: throw ValidationError("Choose when this routine should run.")
+ }
+ }
+
+ private struct ValidationError: LocalizedError {
+ let errorDescription: String?
+ init(_ message: String) { errorDescription = message }
+ }
+}
diff --git a/kit/Sources/CodyncUI/Bots/AgentModelPicker.swift b/kit/Sources/CodyncUI/Bots/AgentModelPicker.swift
new file mode 100644
index 00000000..1d9aefdc
--- /dev/null
+++ b/kit/Sources/CodyncUI/Bots/AgentModelPicker.swift
@@ -0,0 +1,124 @@
+import CodyncKit
+import SwiftUI
+
+/// Models come from the selected computer's agent, never a bundled provider list.
+struct AgentModelPicker: View {
+ let backend: String
+ @Binding var selection: String?
+ @Environment(BotStore.self) private var store
+ @State private var catalog: AgentModels?
+ @State private var catalogScope: String?
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var loading = false
+ @State private var failure: String?
+ @State private var retry = 0
+
+ private var requestKey: String {
+ "\(store.computer.id)/\(backend)/\(store.connection == .online)/\(retry)"
+ }
+
+ /// The agent's own "Default (recommended)" entry is the same choice as leaving the model unset,
+ /// so it folds into the single Default row instead of showing twice.
+ private var agentDefault: AgentModels.Model? {
+ catalog?.models.first { $0.name.lowercased().hasPrefix("default") }
+ }
+
+ private var options: [(String, String)] {
+ let available = (catalog?.models ?? []).filter { $0.id != agentDefault?.id }
+ let current = available.first { $0.id == catalog?.currentModelId }?.name
+ var result = [("", agentDefault?.name ?? current.map { "Default · \($0)" } ?? "Default")]
+ result += available.map { ($0.id, $0.name) }
+ if let selection, !selection.isEmpty, selection != agentDefault?.id,
+ !available.contains(where: { $0.id == selection }) {
+ result.append((selection, selection))
+ }
+ return result
+ }
+
+ private var value: Binding<String> {
+ Binding(
+ get: { selection == agentDefault?.id ? "" : selection ?? "" },
+ set: { selection = $0.isEmpty ? nil : $0 }
+ )
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ OptionRow("Model") {
+ HStack(spacing: 4) {
+ if backend != "custom" { refreshControl }
+ if backend == "custom" || (!loading && catalog?.models.isEmpty != false) {
+ TextField("Default", text: value)
+ .plainTextInput()
+ .multilineTextAlignment(.trailing)
+ .textFieldStyle(.plain)
+ .frame(width: InterfaceMetrics.value(mac: 160, mobile: 180))
+ .pill()
+ } else {
+ ChoicePicker(selection: value, options: options, fill: Palette.background)
+ }
+ }
+ }
+ if backend != "custom", !loading {
+ if let failure {
+ Text(failure)
+ .font(.caption)
+ .foregroundStyle(Palette.warning)
+ } else if catalog?.models.isEmpty == true {
+ Text("This agent doesn't advertise a model list. Leave Default or enter a model ID.")
+ .font(.caption)
+ .foregroundStyle(Palette.secondary)
+ }
+ }
+ Text("Changing the model starts a new agent session. Chat history is kept.")
+ .font(.caption)
+ .foregroundStyle(Palette.secondary)
+ }
+ .onChange(of: backend) { _, _ in selection = nil }
+ .task(id: requestKey) { await load() }
+ }
+
+ /// Loading and refresh share one fixed slot, so the row never grows for loading.
+ private var refreshControl: some View {
+ ZStack {
+ IconButton(failure == nil ? "Refresh model list" : "Retry model list", systemImage: "arrow.clockwise") {
+ retry += 1
+ }
+ .opacity(loading ? 0 : 1)
+ .disabled(loading)
+ .accessibilityHidden(loading)
+ if loading {
+ Spinner(size: 12)
+ .accessibilityLabel("Loading available models")
+ .transition(.opacity)
+ }
+ }
+ .frame(width: InterfaceMetrics.value(mac: 28, mobile: 36), height: InterfaceMetrics.value(mac: 28, mobile: 36))
+ .animation(Motion.reduced(Motion.fade, reduceMotion), value: loading)
+ }
+
+ @MainActor private func load() async {
+ let scope = "\(store.computer.id)/\(backend)"
+ if catalogScope != scope {
+ catalog = nil
+ catalogScope = scope
+ }
+ failure = nil
+ loading = false
+ guard backend != "custom" else { return }
+ guard store.connection == .online, let client = store.client else {
+ failure = "Connect to this computer to load its models. You can still enter a model ID."
+ return
+ }
+ loading = true
+ do {
+ let response = try await client.agentModels(backend)
+ try Task.checkCancellation()
+ catalog = response
+ } catch {
+ guard !Task.isCancelled else { return }
+ failure = "Couldn't load models: \(error.localizedDescription)"
+ }
+ loading = false
+ }
+}
diff --git a/kit/Sources/CodyncUI/Bots/BotEditorView.swift b/kit/Sources/CodyncUI/Bots/BotEditorView.swift
index 5ec26dcb..6d3b542a 100644
--- a/kit/Sources/CodyncUI/Bots/BotEditorView.swift
+++ b/kit/Sources/CodyncUI/Bots/BotEditorView.swift
@@ -160,14 +160,7 @@ struct BotSettingsForm: View {
.plainTextInput()
.fieldBox()
}
- OptionRow("Model") {
- TextField("Default", text: Binding(get: { draft.model ?? "" }, set: { draft.model = $0.isEmpty ? nil : $0 }))
- .plainTextInput()
- .multilineTextAlignment(.trailing)
- .textFieldStyle(.plain)
- .frame(width: InterfaceMetrics.value(mac: 100, mobile: 130))
- .pill()
- }
+ AgentModelPicker(backend: draft.backend, selection: $draft.model)
OptionRow("Project folder") {
Button { pickingFolder = true } label: {
HStack(spacing: 6) {
@@ -271,7 +264,7 @@ struct Field<Content: View>: View {
}
}
-private struct OptionRow<Content: View>: View {
+struct OptionRow<Content: View>: View {
let label: String
@ViewBuilder let content: Content
diff --git a/kit/Sources/CodyncUI/Chrome.swift b/kit/Sources/CodyncUI/Chrome.swift
index dfd14bc7..0b147fcc 100644
--- a/kit/Sources/CodyncUI/Chrome.swift
+++ b/kit/Sources/CodyncUI/Chrome.swift
@@ -160,6 +160,9 @@ public struct ConnectingIndicator: View {
.task(id: isConnecting) {
if isConnecting {
if !isVisible {
+ // A reconnect that settles within 0.4 s never shows, so nothing flashes.
+ try? await Task.sleep(for: .milliseconds(400))
+ guard !Task.isCancelled else { return }
shownAt = .now
withAnimation(Motion.reduced(Motion.fade, reduceMotion)) { isVisible = true }
}
@@ -210,8 +213,7 @@ public extension View {
}
func codyncSheet<Item: Identifiable, Sheet: View>(item: Binding<Item?>, @ViewBuilder content: @escaping (Item) -> Sheet) -> some View {
- let shown = Binding(get: { item.wrappedValue != nil }, set: { if !$0 { item.wrappedValue = nil } })
- return modifier(CodyncSheet(isPresented: shown, sheet: { item.wrappedValue.map(content) }))
+ modifier(CodyncItemSheet(item: item, sheet: content))
}
/// Presents a full-window layer the content draws itself (menus, dialogs), fading in and out.
@@ -231,19 +233,37 @@ public extension View {
}
}
+/// Keeps the last item on screen while the sheet slides away after the item is cleared.
+private struct CodyncItemSheet<Item: Identifiable, Sheet: View>: ViewModifier {
+ @Binding var item: Item?
+ let sheet: (Item) -> Sheet
+ @State private var last: Item?
+
+ func body(content: Content) -> some View {
+ let shown = Binding(get: { item != nil }, set: { if !$0 { item = nil } })
+ content
+ .modifier(CodyncSheet(isPresented: shown, sheet: { (item ?? last).map(sheet) }))
+ .onChange(of: item?.id, initial: true) { if item != nil { last = item } }
+ }
+}
+
#if os(iOS)
private struct CodyncSheet<Sheet: View>: ViewModifier {
@Binding var isPresented: Bool
let sheet: () -> Sheet
+ /// Outlives `isPresented` by the slide-out, so closing from outside the sheet
+ /// (clearing the binding) animates like the grabber and `dismissModal` do.
+ @State private var covered = false
func body(content: Content) -> some View {
content
- .fullScreenCover(isPresented: $isPresented) {
- BottomSheet(close: { isPresented = false }, content: sheet)
+ .fullScreenCover(isPresented: $covered) {
+ BottomSheet(isPresented: $isPresented, removed: { covered = false }, content: sheet)
.presentationBackground(.clear)
}
+ .onChange(of: isPresented, initial: true) { if isPresented { covered = true } }
// Our own slide replaces the system one.
- .transaction(value: isPresented) { $0.disablesAnimations = true }
+ .transaction(value: covered) { $0.disablesAnimations = true }
}
}
@@ -288,7 +308,8 @@ private struct FadeLayer<Layer: View>: View {
/// The iPhone modal: slides up over a dim, drags down (from the grabber) to close.
private struct BottomSheet<Content: View>: View {
- let close: () -> Void
+ @Binding var isPresented: Bool
+ let removed: () -> Void
@ViewBuilder let content: () -> Content
@State private var shown = false
@State private var drag: CGFloat = 0
@@ -319,7 +340,8 @@ private struct BottomSheet<Content: View>: View {
.ignoresSafeArea(.container, edges: .bottom)
}
}
- .onAppear { withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { shown = true } }
+ .onAppear(perform: slideIn)
+ .onChange(of: isPresented) { isPresented ? slideIn() : slideOut() }
.accessibilityAction(.escape, animateClose)
}
@@ -335,13 +357,20 @@ private struct BottomSheet<Content: View>: View {
}
}
- private func animateClose() {
+ /// Clears the binding; `slideOut` follows from the change.
+ private func animateClose() { isPresented = false }
+
+ private func slideIn() {
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { shown = true }
+ }
+
+ private func slideOut() {
withAnimation(Motion.reduced(Motion.layout, reduceMotion)) {
shown = false
} completion: {
var t = Transaction()
t.disablesAnimations = true
- withTransaction(t) { close() }
+ withTransaction(t) { if !isPresented { removed() } }
}
}
}
diff --git a/kit/Sources/CodyncUI/Controls.swift b/kit/Sources/CodyncUI/Controls.swift
index 2a7d04be..b54aab2f 100644
--- a/kit/Sources/CodyncUI/Controls.swift
+++ b/kit/Sources/CodyncUI/Controls.swift
@@ -144,18 +144,37 @@ public struct MenuItem: Identifiable {
}
}
+/// A row of emoji above a message's menu (Slack's quick reactions).
+public struct ReactionPick {
+ public var emoji: [String]
+ public var chosen: [String]
+ public var toggle: (String) -> Void
+
+ public init(emoji: [String], chosen: [String], toggle: @escaping (String) -> Void) {
+ self.emoji = emoji
+ self.chosen = chosen
+ self.toggle = toggle
+ }
+}
+
/// The floating panel of menu rows (used by every menu, popover or overlay).
public struct MenuPanel: View {
let items: [MenuItem]
+ var reactions: ReactionPick?
let dismiss: () -> Void
- public init(items: [MenuItem], dismiss: @escaping () -> Void) {
+ public init(items: [MenuItem], reactions: ReactionPick? = nil, dismiss: @escaping () -> Void) {
self.items = items
+ self.reactions = reactions
self.dismiss = dismiss
}
public var body: some View {
VStack(alignment: .leading, spacing: 2) {
+ if let reactions {
+ ReactionStrip(pick: reactions, dismiss: dismiss)
+ .padding(.bottom, 4)
+ }
ForEach(items) { item in
if item.divider {
Rectangle().fill(Palette.text.opacity(0.1)).frame(height: 0.5)
@@ -173,6 +192,59 @@ public struct MenuPanel: View {
}
}
+/// Quick-reaction buttons; a chosen one is highlighted and tapping it takes it back.
+struct ReactionStrip: View {
+ let pick: ReactionPick
+ var dismiss: () -> Void = {}
+
+ var body: some View {
+ HStack(spacing: 0) {
+ ForEach(pick.emoji, id: \.self) { emoji in
+ let chosen = pick.chosen.contains(emoji)
+ Button {
+ dismiss()
+ pick.toggle(emoji)
+ } label: {
+ Text(emoji).font(.system(size: InterfaceMetrics.value(mac: 14, mobile: 24)))
+ }
+ .buttonStyle(ReactionButtonStyle(chosen: chosen))
+ .help(chosen ? "Remove \(emoji)" : "React \(emoji)")
+ .accessibilityLabel(chosen ? "Remove reaction \(emoji)" : "React \(emoji)")
+ }
+ }
+ }
+}
+
+/// One emoji in a reaction row: grows a little under the pointer, tinted once chosen.
+private struct ReactionButtonStyle: ButtonStyle {
+ let chosen: Bool
+
+ func makeBody(configuration: Configuration) -> some View {
+ ReactionButton(configuration: configuration, chosen: chosen)
+ }
+
+ private struct ReactionButton: View {
+ let configuration: Configuration
+ let chosen: Bool
+ @State private var hovering = false
+
+ var body: some View {
+ let size = InterfaceMetrics.value(mac: 26, mobile: 40)
+ configuration.label
+ .scaleEffect(configuration.isPressed ? 0.85 : hovering ? 1.15 : 1)
+ .frame(width: size, height: size)
+ .background(
+ Palette.text.opacity(chosen ? 0.12 : hovering ? 0.06 : 0),
+ in: RoundedRectangle(cornerRadius: size * 0.28, style: .continuous)
+ )
+ .contentShape(Rectangle())
+ .animation(Motion.press, value: configuration.isPressed)
+ .animation(Motion.hover, value: hovering)
+ .onHover { hovering = $0 }
+ }
+ }
+}
+
private struct MenuRow: View {
let item: MenuItem
let action: () -> Void
@@ -210,13 +282,15 @@ public extension View {
}
/// 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))
+ /// `reactions` puts a quick-reaction row on top.
+ func contextActions(reactions: ReactionPick? = nil, _ items: @escaping () -> [MenuItem]) -> some View {
+ modifier(ContextActions(items: items, reactions: reactions))
}
}
private struct ContextActions: ViewModifier {
let items: () -> [MenuItem]
+ let reactions: ReactionPick?
@State private var open = false
@State private var point: CGPoint?
@@ -227,11 +301,16 @@ private struct ContextActions: ViewModifier {
#else
.onLongPressGesture(minimumDuration: 0.35) { point = nil; open = true }
#endif
- .modifier(AnchoredMenu(isPresented: $open, point: point, items: items))
+ .modifier(AnchoredMenu(isPresented: $open, point: point, items: items, reactions: reactions))
.accessibilityActions {
ForEach(items()) { item in
Button(item.title, action: item.action)
}
+ if let reactions {
+ ForEach(reactions.emoji, id: \.self) { emoji in
+ Button("React \(emoji)") { reactions.toggle(emoji) }
+ }
+ }
}
}
}
@@ -241,6 +320,7 @@ private struct AnchoredMenu: ViewModifier {
@Binding var isPresented: Bool
let point: CGPoint?
let items: () -> [MenuItem]
+ var reactions: ReactionPick?
@State private var frame: CGRect = .zero
func body(content: Content) -> some View {
@@ -249,7 +329,7 @@ private struct AnchoredMenu: ViewModifier {
.codyncOverlay(isPresented: $isPresented) { close in
let anchor = point.map { CGRect(x: frame.minX + $0.x, y: frame.minY + $0.y, width: 0, height: 0) } ?? frame
AnchoredPanel(anchor: anchor, close: close) {
- MenuPanel(items: items(), dismiss: close)
+ MenuPanel(items: items(), reactions: reactions, dismiss: close)
}
}
}
diff --git a/kit/Sources/CodyncUI/Marketplace/ComposioViews.swift b/kit/Sources/CodyncUI/Marketplace/ComposioViews.swift
index 5d3e9b7f..ef26e480 100644
--- a/kit/Sources/CodyncUI/Marketplace/ComposioViews.swift
+++ b/kit/Sources/CodyncUI/Marketplace/ComposioViews.swift
@@ -1,7 +1,7 @@
import CodyncKit
import SwiftUI
-// Apps through Composio (host/src/composio.rs): set up a key once, connect
+// Apps through Composio (host/src/market/composio.rs): set up a key once, connect
// apps with Composio's hosted sign-in, then turn them on per bot like any
// other connector.
diff --git a/kit/Sources/CodyncUI/Marketplace/ConnectorSignInFlow.swift b/kit/Sources/CodyncUI/Marketplace/ConnectorSignInFlow.swift
new file mode 100644
index 00000000..dd43ca3a
--- /dev/null
+++ b/kit/Sources/CodyncUI/Marketplace/ConnectorSignInFlow.swift
@@ -0,0 +1,37 @@
+import AuthenticationServices
+import CodyncKit
+import SwiftUI
+
+/// Signs in to a remote connector (host/src/market/oauth.rs). From the phone, the system sign-in sheet
+/// catches the return (`codync://oauth?…`) and hands the code to the host; on the computer itself
+/// the browser returns to the host directly and we wait for the connector to flip to signed in.
+@MainActor
+struct ConnectorSignInFlow {
+ let model: BotStore
+ let webAuthenticationSession: WebAuthenticationSession
+ let openURL: OpenURLAction
+
+ /// Returns quietly when the user cancels.
+ func signIn(_ id: String) async throws {
+ let plan = try await model.connectorSignIn(id)
+ guard let url = URL(string: plan.url) else { return }
+ guard plan.callback == "app" else {
+ openURL(url)
+ try await model.waitForSignIn(id)
+ return
+ }
+ let back: URL
+ do {
+ back = try await webAuthenticationSession.authenticate(using: url, callbackURLScheme: "codync", preferredBrowserSession: .shared)
+ } catch let error as ASWebAuthenticationSessionError where error.code == .canceledLogin {
+ return
+ }
+ let items = URLComponents(url: back, resolvingAgainstBaseURL: false)?.queryItems ?? []
+ func value(_ name: String) -> String? { items.first { $0.name == name }?.value }
+ try await model.finishConnectorSignIn(
+ state: value("state") ?? "",
+ code: value("code"),
+ error: value("error_description") ?? value("error")
+ )
+ }
+}
diff --git a/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift b/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift
index d157f31d..38121dc6 100644
--- a/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift
+++ b/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift
@@ -24,10 +24,9 @@ public struct MarketplaceView: View {
@State private var writingSkill = false
@State private var agent: Backend?
@State private var showInstalled = false
- /// Shown as a sheet: a close button in the header instead of the navigation bar.
- let close: (() -> Void)?
+ @Environment(\.dismissModal) private var dismiss
- public init(close: (() -> Void)? = nil) { self.close = close }
+ public init() {}
private var query: String { search.trimmingCharacters(in: .whitespaces) }
@@ -154,18 +153,17 @@ public struct MarketplaceView: View {
.font(.footnote)
.foregroundStyle(Palette.tertiary)
}
- .padding(.horizontal, close == nil ? 24 : 44)
+ .padding(.horizontal, 44)
.padding(.vertical, 20)
.frame(maxWidth: 980)
.frame(maxWidth: .infinity)
}
.background(Palette.background)
.overlay(alignment: .topTrailing) {
- if let close {
- IconButton("Close", systemImage: "xmark", action: close)
- .keyboardShortcut(.cancelAction)
- .padding(8)
- }
+ // dismissModal slides the sheet away; clearing the binding would cut it off.
+ IconButton("Close", systemImage: "xmark") { dismiss() }
+ .keyboardShortcut(.cancelAction)
+ .padding(8)
}
}
@@ -194,7 +192,7 @@ public struct MarketplaceView: View {
.buttonStyle(.plain)
}
}
- .padding(.top, close == nil ? 8 : 28)
+ .padding(.top, 28)
}
private var searchField: some View {
@@ -238,7 +236,10 @@ public struct MarketplaceView: View {
private struct InstalledView: View {
let back: () -> Void
@Environment(BotStore.self) private var model
+ @Environment(\.webAuthenticationSession) private var webAuthenticationSession
+ @Environment(\.openURL) private var openURL
@State private var removing: Removal?
+ @State private var signingIn: String?
private struct Removal: Identifiable {
let id: String
@@ -268,12 +269,20 @@ private struct InstalledView: View {
if !model.installedConnectors.isEmpty {
CardSection("Connectors") {
ForEach(model.installedConnectors) { c in
- InstalledRow(title: c.name, subtitle: c.command ?? c.url ?? c.description) {
+ InstalledRow(title: c.name, subtitle: c.needsSignIn ? "Sign in so bots can use it" : c.command ?? c.url ?? c.description) {
if c.kind == "composio" {
AppLogo(url: c.logo, name: c.name, size: 32)
} else {
ServiceLogo(website: nil, name: c.name, registryName: c.registryName, size: 32)
}
+ } accessory: {
+ if signingIn == c.id {
+ Spinner()
+ } else if c.needsSignIn {
+ Button("Sign in") { signIn(c.id) }
+ .buttonStyle(PrimaryButtonStyle())
+ .controlSize(.small)
+ }
} remove: {
removing = Removal(id: c.id, name: c.name, isSkill: false)
}
@@ -285,6 +294,8 @@ private struct InstalledView: View {
ForEach(model.installedSkills) { s in
InstalledRow(title: s.name, subtitle: s.description) {
SkillGlyph().frame(width: 32, height: 32)
+ } accessory: {
+ EmptyView()
} remove: {
removing = Removal(id: s.id, name: s.name, isSkill: true)
}
@@ -309,6 +320,18 @@ private struct InstalledView: View {
}]
}
}
+
+ private func signIn(_ id: String) {
+ signingIn = id
+ Task {
+ do {
+ try await ConnectorSignInFlow(model: model, webAuthenticationSession: webAuthenticationSession, openURL: openURL).signIn(id)
+ } catch {
+ model.lastError = error.localizedDescription
+ }
+ signingIn = nil
+ }
+ }
}
/// Text that opens a web page (replaces the system `Link`).
@@ -348,10 +371,11 @@ private struct EmptyState: View {
}
}
-private struct InstalledRow<Icon: View>: View {
+private struct InstalledRow<Icon: View, Accessory: View>: View {
let title: String
let subtitle: String
@ViewBuilder let icon: Icon
+ @ViewBuilder let accessory: Accessory
let remove: () -> Void
var body: some View {
@@ -362,6 +386,7 @@ private struct InstalledRow<Icon: View>: View {
Text(subtitle).font(.caption).foregroundStyle(Palette.secondary).lineLimit(1)
}
Spacer(minLength: 12)
+ accessory
Button("Remove \(title)", systemImage: "trash", role: .destructive, action: remove)
.labelStyle(.iconOnly)
.buttonStyle(.plain)
@@ -914,6 +939,8 @@ private struct InstallConnectorSheet: View {
let done: () -> Void
@Environment(BotStore.self) private var model
@Environment(\.dismissModal) private var dismiss
+ @Environment(\.webAuthenticationSession) private var webAuthenticationSession
+ @Environment(\.openURL) private var openURL
@State private var optionId = ""
@State private var values: [String: String] = [:]
@State private var saving = false
@@ -961,7 +988,7 @@ private struct InstallConnectorSheet: View {
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."
+ ? "No keys needed here. If \(item.title) wants you to sign in, its sign-in page opens next."
: "No setup needed.")
.foregroundStyle(Palette.secondary)
}
@@ -1000,7 +1027,10 @@ private struct InstallConnectorSheet: View {
error = nil
Task {
do {
- try await model.installConnector(item, option: option.id, inputs: values)
+ let c = try await model.installConnector(item, option: option.id, inputs: values)
+ if c.needsSignIn {
+ try await ConnectorSignInFlow(model: model, webAuthenticationSession: webAuthenticationSession, openURL: openURL).signIn(c.id)
+ }
done()
dismiss()
} catch {
@@ -1014,6 +1044,8 @@ private struct InstallConnectorSheet: View {
private struct CustomConnectorSheet: View {
@Environment(BotStore.self) private var model
@Environment(\.dismissModal) private var dismiss
+ @Environment(\.webAuthenticationSession) private var webAuthenticationSession
+ @Environment(\.openURL) private var openURL
@State private var name = ""
@State private var remote = false
@State private var target = ""
@@ -1045,7 +1077,14 @@ private struct CustomConnectorSheet: View {
.font(.callout.monospaced())
.plainTextInput()
}
- if !remote {
+ if remote {
+ CardSection("Headers", footer: "Optional, one Name: value per line. Leave empty if the service has you sign in. Saved on \(model.hostName) only.") {
+ TextField("Authorization: Bearer …", text: $envText, axis: .vertical)
+ .lineLimit(2...6)
+ .font(.callout.monospaced())
+ .plainTextInput()
+ }
+ } else {
CardSection("Environment", footer: "One KEY=value per line. Saved on \(model.hostName) only.") {
TextField("API_KEY=…", text: $envText, axis: .vertical)
.lineLimit(2...6)
@@ -1063,14 +1102,20 @@ private struct CustomConnectorSheet: View {
private func save() {
saving = true
error = nil
- var env: [String: String] = [:]
+ var pairs: [String: String] = [:]
for line in envText.split(separator: "\n") {
- let parts = line.split(separator: "=", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) }
- if parts.count == 2, !parts[0].isEmpty { env[parts[0]] = parts[1] }
+ let parts = line.split(separator: remote ? ":" : "=", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) }
+ if parts.count == 2, !parts[0].isEmpty { pairs[parts[0]] = parts[1] }
}
Task {
do {
- try await model.addConnector(name: name, command: remote ? nil : target, url: remote ? target : nil, env: env)
+ let c = try await model.addConnector(
+ name: name, command: remote ? nil : target, url: remote ? target : nil,
+ env: remote ? [:] : pairs, headers: remote ? pairs : [:]
+ )
+ if c.needsSignIn {
+ try await ConnectorSignInFlow(model: model, webAuthenticationSession: webAuthenticationSession, openURL: openURL).signIn(c.id)
+ }
dismiss()
} catch {
self.error = error.localizedDescription
diff --git a/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift b/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift
new file mode 100644
index 00000000..7cc76485
--- /dev/null
+++ b/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift
@@ -0,0 +1,232 @@
+import CodyncKit
+import SwiftUI
+
+struct RoutineEditorView: View {
+ let botId: String
+ let routine: Routine?
+ let saved: (Routine) -> Void
+ @Environment(BotStore.self) private var model
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var name = ""
+ @State private var instruction = ""
+ @State private var schedule = RoutineScheduleDraft()
+ @State private var timeout = "3600"
+ @State private var busy = false
+ @State private var error: String?
+ @State private var advanced = false
+
+ private var options: [(String, String)] {
+ var values = [("interval", "Repeat at an interval"), ("cron", "Calendar schedule"),
+ ("once", "Run once"), ("webhook", "Webhook")]
+ if routine != nil { values.insert(("keep", "Keep existing triggers"), at: 0) }
+ return values
+ }
+
+ private var canSave: Bool {
+ !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty &&
+ !instruction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !model.isOffline && !busy
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ ModalHeader(routine == nil ? "Set up a routine" : "Edit routine")
+ ScrollView {
+ VStack(alignment: .leading, spacing: 24) {
+ VStack(alignment: .leading, spacing: 14) {
+ Field("Name") {
+ TextField("Name", text: $name, prompt: Text("e.g. Morning summary").foregroundStyle(Palette.text.opacity(0.7))).routineInput()
+ }
+ Field("Instruction") {
+ TextField("Instruction", text: $instruction, prompt: Text("Describe what this bot should do each time it runs.").foregroundStyle(Palette.text.opacity(0.7)), axis: .vertical)
+ .lineLimit(3...8).routineInput()
+ }
+ }
+ VStack(alignment: .leading, spacing: 14) {
+ Text("When to run").font(.subheadline.weight(.semibold))
+ LazyVGrid(columns: [GridItem(.adaptive(minimum: 180), spacing: 8)], spacing: 8) {
+ ForEach(options, id: \.0) { option in triggerChoice(option) }
+ }
+ triggerFields
+ }
+ VStack(alignment: .leading, spacing: 12) {
+ Button {
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { advanced.toggle() }
+ } label: {
+ HStack {
+ Text("Run settings").font(.subheadline.weight(.medium))
+ Spacer()
+ Text("Timeout: \(timeout)s").font(.caption).foregroundStyle(Palette.secondary)
+ Image(systemName: advanced ? "chevron.up" : "chevron.down").font(.caption)
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityValue(advanced ? "Expanded" : "Collapsed")
+ if advanced {
+ Field("Run timeout (seconds)") { TextField("3600", text: $timeout).routineInput() }
+ Text("Stop a run if it exceeds this limit. Between 1 second and 24 hours.")
+ .font(.caption).foregroundStyle(Palette.secondary)
+ }
+ }
+ }
+ .padding(20)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .disabled(busy)
+ footer
+ }
+ .font(.system(size: InterfaceMetrics.value(mac: 13, mobile: 16)))
+ .foregroundStyle(Palette.text)
+ .background(Palette.background)
+ .onAppear {
+ if let routine {
+ name = routine.name
+ instruction = routine.instruction
+ timeout = String(routine.timeoutSeconds ?? 3600)
+ schedule = RoutineScheduleDraft(triggers: routine.triggers)
+ }
+ }
+ }
+
+ private func triggerChoice(_ option: (String, String)) -> some View {
+ let selected = schedule.kind == option.0
+ let symbols = ["interval": "arrow.clockwise", "cron": "calendar",
+ "once": "clock", "webhook": "link", "keep": "checklist"]
+ let details = ["interval": "Repeat at a fixed interval", "cron": "Choose days and times",
+ "once": "At a specific date and time", "webhook": "When an event arrives",
+ "keep": "Preserve the current schedule"]
+ return Button {
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { schedule.kind = option.0 }
+ } label: {
+ HStack(alignment: .top, spacing: 10) {
+ Image(systemName: symbols[option.0] ?? "clock")
+ .font(.system(size: 15)).frame(width: 20).padding(.top, 2)
+ VStack(alignment: .leading, spacing: 4) {
+ Text(option.1).font(.subheadline.weight(.medium))
+ Text(details[option.0] ?? "").font(.caption).foregroundStyle(selected ? Palette.text.opacity(0.75) : Palette.secondary)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ Image(systemName: "checkmark").font(.caption.weight(.semibold)).opacity(selected ? 1 : 0)
+ }
+ .padding(12)
+ .frame(maxWidth: .infinity, minHeight: 70, alignment: .topLeading)
+ .background(selected ? Palette.bubbleUser : Palette.bubbleAgent,
+ in: RoundedRectangle(cornerRadius: 12))
+ .contentShape(RoundedRectangle(cornerRadius: 12))
+ }
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(selected ? .isSelected : [])
+ }
+
+ @ViewBuilder private var triggerFields: some View {
+ switch schedule.kind {
+ case "interval":
+ Field("Repeat every") {
+ TextField("Interval", text: $schedule.amount).routineInput()
+ SegmentedChoice(selection: $schedule.unit, options: [(1, "Seconds"), (60, "Minutes"), (3600, "Hours"), (86400, "Days")])
+ }
+ case "cron":
+ SegmentedChoice(selection: $schedule.calendarStyle, options: [("daily", "Daily"), ("weekdays", "Weekdays"), ("weekly", "Weekly"), ("custom", "Custom")])
+ if schedule.calendarStyle == "custom" {
+ Field("Cron expression") {
+ TextField("0 9 * * *", text: $schedule.expression).routineInput().font(.callout.monospaced())
+ }
+ Text("For example, 0 9 * * * runs every day at 9 AM.")
+ .font(.caption).foregroundStyle(Palette.secondary)
+ } else {
+ if schedule.calendarStyle == "weekly" {
+ SegmentedChoice(selection: $schedule.weekday, options: [(0, "Sun"), (1, "Mon"), (2, "Tue"), (3, "Wed"), (4, "Thu"), (5, "Fri"), (6, "Sat")])
+ }
+ DatePicker("At", selection: $schedule.timeOfDay, displayedComponents: .hourAndMinute)
+ .environment(\.timeZone, TimeZone(identifier: "GMT") ?? .current)
+ .padding(12).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 12))
+ }
+ Field("Time zone") { TextField("Asia/Taipei", text: $schedule.zone).routineInput() }
+ case "once":
+ DatePicker("Run at", selection: $schedule.date)
+ .padding(12).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 12))
+ Text("Time zone: \(TimeZone.current.identifier)").font(.caption).foregroundStyle(Palette.secondary)
+ case "webhook":
+ VStack(alignment: .leading, spacing: 6) {
+ Label("Local connection", systemImage: "desktopcomputer").font(.subheadline.weight(.medium))
+ Text("Save to get a URL and secret key. External services need a public forwarding connection, configured separately.")
+ .font(.caption).foregroundStyle(Palette.secondary)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(14).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 12))
+ default:
+ ForEach(routine?.triggerDescriptions ?? [], id: \.self) {
+ Label($0, systemImage: "clock").font(.callout).foregroundStyle(Palette.secondary)
+ }
+ }
+ }
+
+ private var footer: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ if let error {
+ Label(error, systemImage: "exclamationmark.circle")
+ .font(.callout).foregroundStyle(Palette.danger).textSelection(.enabled)
+ }
+ if model.isOffline {
+ Label("Connect to this computer to save your routine.", systemImage: "wifi.slash")
+ .font(.caption).foregroundStyle(Palette.danger)
+ }
+ ViewThatFits(in: .horizontal) {
+ HStack(spacing: 16) { executionNote; Spacer(minLength: 0); saveButton }
+ VStack(alignment: .leading, spacing: 12) { executionNote; saveButton }
+ }
+ }
+ .padding(20)
+ .background(Palette.bubbleAgent)
+ }
+
+ private var executionNote: some View {
+ VStack(alignment: .leading, spacing: 3) {
+ Label("Runs on the bot’s computer", systemImage: "desktopcomputer").font(.caption.weight(.medium))
+ Text("Keep the host running and computer awake.")
+ .font(.caption).foregroundStyle(Palette.secondary)
+ }
+ }
+
+ private var saveButton: some View {
+ Button(action: save) {
+ HStack(spacing: 8) {
+ if busy { Spinner() }
+ Text(busy ? "Saving…" : routine == nil ? "Create routine" : "Save changes")
+ .fixedSize(horizontal: true, vertical: false)
+ }
+ }
+ .buttonStyle(.primary)
+ .disabled(!canSave)
+ .keyboardShortcut("s", modifiers: .command)
+ }
+
+ private func save() {
+ guard let client = model.client, canSave else { return }
+ guard let timeoutValue = Int(timeout), (1...86400).contains(timeoutValue) else {
+ error = "Timeout must be 1 to 86400 seconds."
+ return
+ }
+ let triggers: [RoutineTrigger]
+ do { triggers = try schedule.triggers() }
+ catch { self.error = error.localizedDescription; return }
+ busy = true
+ error = nil
+ Task {
+ defer { busy = false }
+ do {
+ let result = try await client.saveRoutine(botId: botId, id: routine?.id, name: name,
+ instruction: instruction, triggers: triggers, timeoutSeconds: timeoutValue)
+ saved(result)
+ } catch { self.error = error.localizedDescription }
+ }
+ }
+}
+
+private extension View {
+ func routineInput() -> some View {
+ textFieldStyle(.plain)
+ .padding(12)
+ .background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 12))
+ }
+}
diff --git a/kit/Sources/CodyncUI/Routines/RoutinesView.swift b/kit/Sources/CodyncUI/Routines/RoutinesView.swift
new file mode 100644
index 00000000..c94dae2e
--- /dev/null
+++ b/kit/Sources/CodyncUI/Routines/RoutinesView.swift
@@ -0,0 +1,309 @@
+import CodyncKit
+import SwiftUI
+
+/// The same routine list and details in the Mac sidebar and the phone's modal.
+struct RoutinesView: View {
+ let botId: String
+ var initialId: String?
+ var close: (() -> Void)?
+ @Environment(BotStore.self) private var model
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var routines: [Routine] = []
+ @State private var runs: [RoutineRun] = []
+ @State private var selected: String?
+ @State private var loaded = false
+ @State private var busy = false
+ @State private var error: String?
+ @State private var confirmDelete = false
+ @State private var webhook: RoutineWebhook?
+ @State private var showKey = false
+ @State private var openRun: ThreadTarget?
+ @State private var showSetup = false
+ @State private var loadError: String?
+ @State private var copied: String?
+
+ private var routine: Routine? { routines.first { $0.id == selected } }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 16) {
+ HStack {
+ if selected != nil {
+ IconButton("Back to Routines", systemImage: "chevron.left") { animate { selected = nil; webhook = nil; showKey = false; copied = nil } }
+ }
+ Text(routine?.name ?? "Routines").font(.system(size: 13, weight: .semibold))
+ Spacer(minLength: 0)
+ if selected == nil && !routines.isEmpty {
+ IconButton("Set up a routine", systemImage: "plus") { animate { showSetup = true } }
+ .disabled(model.isOffline)
+ }
+ if let close { IconButton("Close routines", systemImage: "xmark", action: close) }
+ }
+ if let loadError { Text(loadError).font(.caption).foregroundStyle(Palette.danger) }
+ if let error { Text(error).font(.caption).foregroundStyle(.red).textSelection(.enabled) }
+ if let routine {
+ detail(routine)
+ } else if selected != nil && loaded {
+ Text("This routine was deleted.").foregroundStyle(Palette.secondary)
+ } else {
+ listing
+ }
+ }
+ .foregroundStyle(Palette.text)
+ .font(.system(size: 13))
+ .onChange(of: initialId) { _, id in
+ animate { selected = id; webhook = nil; showKey = false; copied = nil }
+ }
+ .task(id: botId) {
+ selected = initialId
+ repeat {
+ await load()
+ do { try await Task.sleep(for: .seconds(3)) } catch { break }
+ } while !Task.isCancelled
+ }
+ .codyncSheet(isPresented: $showSetup) {
+ RoutineEditorView(botId: botId, routine: routine) { saved in
+ routines.removeAll { $0.id == saved.id }
+ routines.append(saved)
+ animate { selected = saved.id; showSetup = false; webhook = nil; showKey = false; copied = nil }
+ Task { await load() }
+ }
+ #if os(macOS)
+ .frame(width: 540, height: 700)
+ #endif
+ }
+ .codyncDialog("Delete routine?", isPresented: $confirmDelete, message: "This deletes the routine and stops its future runs. This can't be undone.") {
+ [DialogAction("Delete routine", destructive: true) {
+ if let routine { action("deleteRoutine", routine) }
+ }]
+ }
+ .codyncSheet(item: $openRun) { run in
+ RepliesView(botId: botId, rootId: run.id) { animate { openRun = nil } }
+ #if os(macOS)
+ .frame(width: 520, height: 580)
+ #endif
+ }
+ }
+
+ private var listing: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ if routines.isEmpty {
+ VStack(alignment: .leading, spacing: 12) {
+ Image(systemName: "clock.arrow.circlepath")
+ .font(.system(size: 22, weight: .light))
+ .foregroundStyle(Palette.secondary)
+ .accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: 6) {
+ Text(loaded ? "No routines yet" : "Loading routines…")
+ .font(.system(size: 13, weight: .medium))
+ Text("Schedule a task, repeat it, or run it on an event.")
+ .font(.system(size: 12))
+ .foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ .lineSpacing(2)
+ }
+ HStack(spacing: 8) {
+ Button("Set up a routine") { animate { showSetup = true } }
+ .buttonStyle(.primary)
+ .disabled(model.isOffline)
+ Spacer(minLength: 0)
+ askInChat
+ }
+ .padding(.top, 2)
+ }
+ .padding(16)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 12))
+ }
+ ForEach(routines) { routine in
+ Button { animate { selected = routine.id } } label: {
+ HStack(alignment: .top, spacing: 10) {
+ Image(systemName: routine.enabled ? "clock.arrow.circlepath" : "pause.circle")
+ .foregroundStyle(Palette.secondary)
+ VStack(alignment: .leading, spacing: 4) {
+ Text(routine.name).foregroundStyle(Palette.text)
+ Text(routine.enabled ? routine.triggerDescriptions.joined(separator: " · ") : "Paused")
+ .font(.caption).foregroundStyle(Palette.secondary)
+ Text(stateDescription(routine)).font(.caption).foregroundStyle(Palette.secondary)
+ }
+ Spacer(minLength: 0)
+ Image(systemName: "chevron.right").font(.caption).foregroundStyle(Palette.tertiary)
+ }
+ .padding(.vertical, 8)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ }
+ if !routines.isEmpty {
+ HStack {
+ Spacer()
+ askInChat
+ }
+ }
+ }
+ }
+
+ private var askInChat: some View {
+ IconButton("Ask in chat", systemImage: "text.bubble") {
+ edit("Help me set up a routine. Ask me what task to run and when, then create it with the routines tool. ")
+ }
+ .disabled(model.isOffline)
+ }
+
+ private func detail(_ routine: Routine) -> some View {
+ VStack(alignment: .leading, spacing: 18) {
+ Label(stateDescription(routine), systemImage: routine.enabled ? "clock" : "pause.circle")
+ .font(.subheadline.weight(.medium))
+ if let error = routine.lastError {
+ Text(error).font(.caption).foregroundStyle(.red).textSelection(.enabled)
+ }
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Instruction").fontWeight(.semibold)
+ Text(routine.instruction).textSelection(.enabled)
+ }
+ VStack(alignment: .leading, spacing: 8) {
+ Text("When to run").fontWeight(.semibold)
+ ForEach(Array(routine.triggerDescriptions.enumerated()), id: \.offset) { _, text in
+ Label(text, systemImage: "clock").foregroundStyle(Palette.secondary)
+ }
+ if routine.enabled, let next = routine.nextRunAt {
+ Text("Next: \(Date(milliseconds: next).formatted(date: .abbreviated, time: .shortened))")
+ .font(.caption).foregroundStyle(Palette.tertiary)
+ }
+ }
+ HStack(spacing: 16) {
+ IconButton(routine.enabled ? "Pause" : "Resume", systemImage: routine.enabled ? "pause" : "play") {
+ action("setRoutineEnabled", routine, enabled: !routine.enabled)
+ }
+ IconButton("Edit", systemImage: "pencil") { animate { showSetup = true } }
+ IconButton("Test run", systemImage: "play.circle") { action("runRoutine", routine) }
+ .disabled(runs.contains { $0.routineId == routine.id && $0.isActive })
+ Spacer()
+ IconButton("Delete routine", systemImage: "trash") { animate { confirmDelete = true } }
+ }
+ .disabled(busy || model.isOffline)
+ Button("Edit with bot", systemImage: "text.bubble") {
+ edit("Help me edit routine \(routine.name) (ID: \(routine.id)). Read its current settings with list_routines and ask what I want to change. Update this routine instead of creating a duplicate. ")
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(Palette.secondary)
+ .disabled(model.isOffline)
+ if routine.triggers.contains(where: { $0.type == "webhook" || $0.type == "event" }) {
+ VStack(alignment: .leading, spacing: 8) {
+ Button("Webhook connection", systemImage: "link") {
+ Task {
+ do {
+ guard let client = model.client else { return }
+ let value = try await client.routineWebhook(botId: botId, id: routine.id)
+ animate { webhook = value }
+ } catch { self.error = error.localizedDescription }
+ }
+ }.buttonStyle(.plain)
+ if let webhook {
+ HStack {
+ Text("Local endpoint").fontWeight(.semibold)
+ Spacer()
+ IconButton(copied == "url" ? "URL copied" : "Copy URL", systemImage: copied == "url" ? "checkmark" : "doc.on.doc") {
+ Pasteboard.copy(webhook.url)
+ animate { copied = "url" }
+ }
+ }
+ Text(webhook.url).font(.caption.monospaced()).textSelection(.enabled)
+ Text("Send JSON with Authorization: Bearer <key>. This address is local to the host.").font(.caption).foregroundStyle(Palette.secondary)
+ Button(showKey ? "Hide key" : "Show key") { animate { showKey.toggle() } }.buttonStyle(.plain)
+ if showKey {
+ HStack(alignment: .top) {
+ Text(webhook.key).font(.caption.monospaced()).textSelection(.enabled)
+ IconButton(copied == "key" ? "Key copied" : "Copy key", systemImage: copied == "key" ? "checkmark" : "doc.on.doc") {
+ Pasteboard.copy(webhook.key)
+ animate { copied = "key" }
+ }
+ }
+ }
+ Text("For external senders, verify a real delivery. Test run only checks the task.")
+ .font(.caption).foregroundStyle(Palette.secondary)
+ }
+ }
+ }
+ let history = runs.filter { $0.routineId == routine.id }
+ if history.isEmpty {
+ Text("No runs recorded yet. Use Test run to execute this task now, or wait for its trigger.")
+ .font(.caption).foregroundStyle(Palette.secondary)
+ } else {
+ VStack(alignment: .leading, spacing: 10) {
+ Text("Runs").fontWeight(.semibold)
+ ForEach(history) { run in
+ VStack(alignment: .leading, spacing: 3) {
+ HStack {
+ Text(runLabel(run))
+ Spacer()
+ Text(Date(milliseconds: run.createdAt), style: .relative).foregroundStyle(Palette.tertiary)
+ if let root = run.rootId {
+ IconButton("Open run conversation", systemImage: "text.bubble") { animate { openRun = ThreadTarget(id: root) } }
+ }
+ }
+ if let detail = run.detail { Text(detail).font(.caption).foregroundStyle(Palette.secondary) }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private func runLabel(_ run: RoutineRun) -> String {
+ switch run.status {
+ case "pending": "Queued"
+ case "starting": "Starting"
+ case "running": "Running"
+ case "recovering": "Resuming after restart"
+ case "succeeded": "Completed"
+ case "failed": "Failed"
+ case "interrupted": "Interrupted"
+ case "cancelled": "Cancelled"
+ default: run.status.capitalized
+ }
+ }
+
+ private func stateDescription(_ routine: Routine) -> String {
+ let history = runs.filter { $0.routineId == routine.id }
+ if let active = history.first(where: \.isActive) { return runLabel(active) }
+ if routine.lastError != nil { return "Schedule needs attention" }
+ if !routine.enabled { return "Paused" }
+ if let last = history.first, ["failed", "interrupted"].contains(last.status) { return "Last run: \(runLabel(last).lowercased())" }
+ if let next = routine.nextRunAt {
+ return "Next: \(Date(milliseconds: next).formatted(date: .abbreviated, time: .shortened))"
+ }
+ if routine.triggers.contains(where: { $0.type == "webhook" || $0.type == "event" }) { return "Waiting for an event" }
+ return "Schedule completed"
+ }
+
+ private func animate(_ change: () -> Void) { withAnimation(Motion.reduced(Motion.layout, reduceMotion), change) }
+ private func edit(_ text: String) {
+ animate {
+ model.routineDrafts[botId] = text
+ close?()
+ }
+ }
+ private func action(_ method: String, _ routine: Routine, enabled: Bool? = nil) {
+ guard !busy, let client = model.client else { return }
+ busy = true
+ Task {
+ defer { busy = false }
+ do {
+ try await client.routineAction(method, botId: botId, id: routine.id, enabled: enabled)
+ if method == "deleteRoutine" { animate { selected = nil; webhook = nil } }
+ error = nil
+ await load()
+ } catch { self.error = error.localizedDescription }
+ }
+ }
+ private func load() async {
+ guard let client = model.client else { return }
+ do {
+ let result = try await client.routines(botId: botId)
+ routines = result.routines
+ runs = result.runs
+ loaded = true
+ loadError = nil
+ } catch is CancellationError {} catch { self.loadError = error.localizedDescription }
+ }
+}
diff --git a/kit/Sources/CodyncUI/Store/AccountStore.swift b/kit/Sources/CodyncUI/Store/AccountStore.swift
index 9405a84a..baf20657 100644
--- a/kit/Sources/CodyncUI/Store/AccountStore.swift
+++ b/kit/Sources/CodyncUI/Store/AccountStore.swift
@@ -127,7 +127,7 @@ public final class AccountStore {
persist()
close(id)
accessPolls.removeValue(forKey: id)?.cancel()
- pendingAccess[id] = nil
+ setPending(id, nil)
if selection?.computerId == id { selection = nil }
refreshList()
}
@@ -162,7 +162,7 @@ public final class AccountStore {
do {
let list = try await cloud.computers()
guard !retired else { return }
- cloudComputers = list
+ if list != cloudComputers { Motion.animate { cloudComputers = list } }
if asksForAccess { await askForAccess() }
} catch {
lastError = error.localizedDescription
@@ -177,7 +177,7 @@ public final class AccountStore {
}
let ticket = try await cloud.requestAccess(id, signKey: target.signKey)
guard !retired else { throw CancellationError() }
- pendingAccess[id] = ticket
+ setPending(id, ticket)
accessPolls[id]?.cancel()
accessPolls[id] = Task { [weak self] in await self?.awaitApproval(ticket, target: target, cloud: cloud) }
return ticket
@@ -186,10 +186,19 @@ public final class AccountStore {
/// An offline account computer named like one this device uses or sees online: most likely the same
/// machine under an earlier identity (its host keys were reset), left behind in the account.
public func isOlderCopy(_ computer: CloudComputer) -> Bool {
- !computer.isOnline && cloudComputers.contains { other in
- other.computerId != computer.computerId && other.name == computer.name
- && (stores[other.computerId] != nil || other.isOnline)
- }
+ guard !computer.isOnline else { return false }
+ // The current copy may be QR-paired without being listed in the account.
+ return computers.contains { $0.id != computer.computerId && $0.name == computer.name }
+ || cloudComputers.contains { other in
+ other.computerId != computer.computerId && other.name == computer.name
+ && (stores[other.computerId] != nil || other.isOnline)
+ }
+ }
+
+ /// Access requests appear and settle with an animation, like connection changes.
+ private func setPending(_ id: ComputerID, _ ticket: AccessTicket?) {
+ guard pendingAccess[id] != ticket else { return }
+ Motion.animate { pendingAccess[id] = ticket }
}
/// Takes a computer out of the account (its grants and pending requests go with it).
@@ -197,7 +206,7 @@ public final class AccountStore {
guard let cloud else { return }
do {
try await cloud.removeComputer(id)
- pendingAccess[id] = nil
+ setPending(id, nil)
await refreshCloud()
} catch {
lastError = error.localizedDescription
@@ -223,7 +232,7 @@ public final class AccountStore {
public func cancelAccess(_ id: ComputerID) async {
guard let ticket = pendingAccess[id] else { return }
accessPolls.removeValue(forKey: id)?.cancel()
- pendingAccess[id] = nil
+ setPending(id, nil)
do {
try await cloud?.cancelAccess(ticket.requestId)
} catch {
@@ -241,7 +250,7 @@ public final class AccountStore {
case .pending:
continue
case .approved:
- pendingAccess[ticket.computerId] = nil
+ setPending(ticket.computerId, nil)
// Pin the key the SAS was computed with; the first hello brings its mailbox key and addresses.
let computer = Computer(id: ticket.computerId, name: target.name, signKey: ticket.signKey,
cloud: cloud.baseURL, device: target.device)
@@ -250,7 +259,7 @@ public final class AccountStore {
await refreshCloud()
return
case .denied, .expired, .cancelled:
- pendingAccess[ticket.computerId] = nil
+ setPending(ticket.computerId, nil)
lastError = status.status == .denied ? "\(target.name) declined the request." : "The request expired. Ask again."
return
}
@@ -329,7 +338,8 @@ public final class AccountStore {
}
private func refreshList() {
- computers = attached + saved.filter { c in !attached.contains { $0.id == c.id } }
+ let merged = attached + saved.filter { c in !attached.contains { $0.id == c.id } }
+ if merged != computers { Motion.animate { computers = merged } }
rosterChanged()
}
diff --git a/kit/Sources/CodyncUI/Store/BotStore.swift b/kit/Sources/CodyncUI/Store/BotStore.swift
index 60376121..63cc2387 100644
--- a/kit/Sources/CodyncUI/Store/BotStore.swift
+++ b/kit/Sources/CodyncUI/Store/BotStore.swift
@@ -58,6 +58,7 @@ public final class BotStore {
public private(set) var installedSkills: [InstalledSkill] = []
/// Bots whose older history has been fully paged in.
public private(set) var historyComplete: Set<String> = []
+ public var routineDrafts: [String: String] = [:]
public var lastError: String?
/// The open conversation (iOS navigation path / Mac sidebar selection).
public var selection: String?
@@ -219,7 +220,7 @@ public final class BotStore {
public func restartStream() {
guard isActive, !retired else { return }
stopTransport()
- if connection != .online { connection = .connecting }
+ if connection != .online { setConnection(.connecting) }
streamTask = Task { [weak self] in await self?.runStream() }
}
@@ -242,11 +243,11 @@ public final class BotStore {
transport = try await makeTransport()
break
} catch HostError.unauthorized(let message) {
- if !Task.isCancelled, !retired { connection = .unauthorized(message) }
+ if !Task.isCancelled, !retired { setConnection(.unauthorized(message)) }
return
} catch {
guard !Task.isCancelled, !retired else { return }
- connection = .offline(error.localizedDescription)
+ setConnection(.offline(error.localizedDescription))
try? await Task.sleep(for: .seconds(backoff))
backoff = min(backoff * 2, 30)
guard !Task.isCancelled else { return }
@@ -264,9 +265,9 @@ public final class BotStore {
guard !Task.isCancelled, !retired else { return }
switch state {
case let .ready(route):
- hostRoute = route
+ setHostRoute(route)
if eventsTask == nil {
- if connection != .online { connection = .connecting }
+ if connection != .online { setConnection(.connecting) }
eventsTask = Task { [weak self] in await self?.runEvents(client) }
// Mailbox outcomes that happened while this app wasn't listening (§10.2).
if let remote = transport as? any RemoteTransport {
@@ -276,27 +277,38 @@ public final class BotStore {
onConnected?(self)
case .connecting:
stopEvents()
- connection = .connecting
+ setConnection(.connecting)
case let .hostOffline(lastSeen):
stopEvents()
- connection = .computerOffline(lastSeen: lastSeen)
+ setConnection(.computerOffline(lastSeen: lastSeen))
if let remote = transport as? any RemoteTransport {
Task { [weak self] in await self?.reconcileQueued(remote) }
}
case let .unauthorized(message):
stopEvents()
- connection = .unauthorized(message)
+ setConnection(.unauthorized(message))
case let .failed(message):
stopEvents()
- connection = .offline(message)
+ setConnection(.offline(message))
}
}
}
+ /// Connection changes animate wherever they show (banners, headers, captions, rows).
+ private func setConnection(_ new: Connection) {
+ guard new != connection else { return }
+ Motion.animate { connection = new }
+ }
+
+ private func setHostRoute(_ new: HostRoute?) {
+ guard new != hostRoute else { return }
+ Motion.animate { hostRoute = new }
+ }
+
private func stopEvents() {
eventsTask?.cancel()
eventsTask = nil
- hostRoute = nil
+ setHostRoute(nil)
}
/// The channel's side streams: merged computer info and mailbox outcomes.
@@ -349,7 +361,7 @@ public final class BotStore {
}
for try await event in client.events(since: rev, client: clientKind) {
guard !Task.isCancelled, !retired else { return }
- connection = .online
+ setConnection(.online)
backoff = 1
apply(event)
}
@@ -359,16 +371,16 @@ public final class BotStore {
if Task.isCancelled || retired { return }
log.info("stream ended: \(error.localizedDescription)")
if case let HostError.unauthorized(message) = error {
- connection = .unauthorized(message)
+ setConnection(.unauthorized(message))
return
}
// On the channel the link state speaks for itself; loopback has no other signal.
if case .loopback = route {
if case HostError.http(401, _) = error {
- connection = .offline(error.localizedDescription)
+ setConnection(.offline(error.localizedDescription))
return
}
- connection = .offline(error.localizedDescription)
+ setConnection(.offline(error.localizedDescription))
}
}
try? await Task.sleep(for: .seconds(backoff))
@@ -600,14 +612,37 @@ public final class BotStore {
screen = try await require().setScreenEnabled(on)
}
+ /// Quick reactions offered on every message (Slack's hover bar).
+ public static let quickReactions = ["👍", "❤️", "😂", "🎉", "👀", "✅"]
+
+ /// Toggles the user's reaction; shown at once, then replaced by the host's copy.
+ public func react(_ entry: Entry, _ emoji: String) {
+ guard let i = entries[entry.botId]?.firstIndex(where: { $0.id == entry.id }) else { return }
+ var reactions = entries[entry.botId]?[i].data.reactions ?? []
+ if let at = reactions.firstIndex(of: emoji) { reactions.remove(at: at) } else { reactions.append(emoji) }
+ entries[entry.botId]?[i].data.reactions = reactions
+ perform { client in
+ let e = try await client.react(entryId: entry.id, emoji: emoji)
+ self.upsert(e)
+ }
+ }
+
public func respond(_ entry: Entry, option: String?) {
perform { try await $0.respondPermission(entryId: entry.id, optionId: option) }
}
- public func markRead(_ botId: String) {
+ /// The main chat on screen (or the thread on `thread`) is read; the host ignores it
+ /// when nothing there is unread.
+ public func markRead(_ botId: String, thread: String? = nil) {
+ guard (bots[botId]?.unread ?? 0) > 0 else { return }
+ perform { try await $0.markRead(botId, threadId: thread) }
+ }
+
+ /// The roster's "Mark as read": the chat and all its threads.
+ public func markAllRead(_ botId: String) {
guard (bots[botId]?.unread ?? 0) > 0 else { return }
bots[botId]?.unread = 0
- perform { try await $0.markRead(botId) }
+ perform { try await $0.markRead(botId, all: true) }
}
public func setPinned(_ bot: Bot, _ pinned: Bool) {
@@ -674,14 +709,36 @@ public final class BotStore {
try await require().marketSkills()
}
- public func installConnector(_ item: MarketConnector, option: String, inputs: [String: String]) async throws {
- try await require().installConnector(registryName: item.name, option: option, inputs: inputs)
+ @discardableResult
+ public func installConnector(_ item: MarketConnector, option: String, inputs: [String: String]) async throws -> InstalledConnector {
+ let c = try await require().installConnector(registryName: item.name, option: option, inputs: inputs)
await refreshPlugins()
+ return c
}
- public func addConnector(name: String, command: String?, url: String?, env: [String: String]) async throws {
- try await require().addConnector(name: name, command: command, url: url, env: env)
+ @discardableResult
+ public func addConnector(name: String, command: String?, url: String?, env: [String: String], headers: [String: String]) async throws -> InstalledConnector {
+ let c = try await require().addConnector(name: name, command: command, url: url, env: env, headers: headers)
await refreshPlugins()
+ return c
+ }
+
+ public func connectorSignIn(_ id: String) async throws -> ConnectorSignIn {
+ try await require().connectorSignIn(id)
+ }
+
+ public func finishConnectorSignIn(state: String, code: String?, error: String?) async throws {
+ try await require().finishConnectorSignIn(state: state, code: code, error: error)
+ await refreshPlugins()
+ }
+
+ /// Waits while the user signs in in the computer's browser (the host catches the return).
+ public func waitForSignIn(_ id: String) async throws {
+ for _ in 0..<150 {
+ try await Task.sleep(for: .seconds(2))
+ await refreshPlugins()
+ if installedConnectors.first(where: { $0.id == id })?.needsSignIn == false { return }
+ }
}
public func removeConnector(_ id: String) async throws {
diff --git a/kit/Sources/CodyncUI/Thread/ChatRows.swift b/kit/Sources/CodyncUI/Thread/ChatRows.swift
index 43c3497d..93e8c8b2 100644
--- a/kit/Sources/CodyncUI/Thread/ChatRows.swift
+++ b/kit/Sources/CodyncUI/Thread/ChatRows.swift
@@ -13,6 +13,7 @@ struct ChatRow: View {
/// Main chat only: start (or open) the thread on this message.
var openThread: ((Entry) -> Void)?
@Environment(BotStore.self) private var model
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
let reply = openThread.map { open in { open(entry) } }
@@ -20,15 +21,22 @@ struct ChatRow: View {
case "user":
VStack(alignment: .trailing, spacing: 4) {
UserBubble(entry: entry, botWorking: chat?.isWorking == true, reply: reply)
+ ReactionsRow(entry: entry)
threadChip
}
+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: entry.data.reactions)
.padding(.top, groupStart ? 12 : 4)
case "agent":
VStack(alignment: .leading, spacing: 4) {
if chat?.isGroup == true, groupStart { AuthorLabel(botId: entry.data.author) }
AgentBubble(entry: entry, openTrace: openTrace, reply: reply)
- threadChip.padding(.leading, chat?.isGroup == true ? 34 : 0)
+ Group {
+ ReactionsRow(entry: entry)
+ threadChip
+ }
+ .padding(.leading, chat?.isGroup == true ? 34 : 0)
}
+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: entry.data.reactions)
.padding(.top, groupStart ? 12 : 4)
case "permission":
VStack(alignment: .leading, spacing: 4) {
@@ -71,6 +79,7 @@ struct ThreadChip: View {
let summary: ThreadSummary
let open: () -> Void
@Environment(BotStore.self) private var model
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
Button(action: open) {
@@ -83,9 +92,16 @@ struct ThreadChip: View {
Text(summary.count == 1 ? "1 reply" : "\(summary.count) replies")
.font(.footnote.weight(.semibold))
.foregroundStyle(Palette.accent)
- Text(RelativeTime.day(Date(milliseconds: summary.lastAt)))
- .font(.footnote)
- .foregroundStyle(Palette.tertiary)
+ if let unread = summary.unread, unread > 0 {
+ Text("\(unread) new")
+ .font(.footnote.weight(.semibold))
+ .foregroundStyle(Palette.text)
+ .transition(.opacity)
+ } else {
+ Text(RelativeTime.day(Date(milliseconds: summary.lastAt)))
+ .font(.footnote)
+ .foregroundStyle(Palette.tertiary)
+ }
Image(systemName: "chevron.right").font(.caption2).foregroundStyle(Palette.tertiary)
}
.padding(.horizontal, 10)
@@ -94,7 +110,11 @@ struct ThreadChip: View {
.contentShape(Capsule())
}
.buttonStyle(PressScale())
- .accessibilityLabel("View thread, \(summary.count) \(summary.count == 1 ? "reply" : "replies")")
+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: summary.unread)
+ .accessibilityLabel(
+ "View thread, \(summary.count) \(summary.count == 1 ? "reply" : "replies")"
+ + ((summary.unread ?? 0) > 0 ? ", \(summary.unread ?? 0) new" : "")
+ )
.help("View thread")
}
}
@@ -104,6 +124,7 @@ struct UserBubble: View {
let botWorking: Bool
var reply: (() -> Void)?
@Environment(BotStore.self) private var model
+ @State private var hovering = false
var body: some View {
VStack(alignment: .trailing, spacing: 4) {
@@ -114,13 +135,24 @@ 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))
- .contextActions {
- var items = [MenuItem("Copy", icon: "doc.on.doc") { Pasteboard.copy(entry.data.text) }]
- if let reply { items.append(MenuItem("Reply in thread", icon: "bubble.left.and.bubble.right", action: reply)) }
+ .contextActions(reactions: model.reactionPick(entry)) {
+ var items = [MenuItem("Copy", icon: "square.on.square") { Pasteboard.copy(entry.data.text) }]
+ if let reply { items.append(MenuItem("Reply in thread", icon: "arrowshape.turn.up.left", action: reply)) }
return items
}
- status
+ #if os(macOS)
+ HStack(spacing: 6) {
+ if hovering, entry.data.status == nil || entry.data.status == "sent" {
+ MessageActions(reactions: model.reactionPick(entry), reply: reply) { Pasteboard.copy(entry.data.text) }
+ }
+ status
+ }
+ .frame(minHeight: MessageActions.height)
+ #else
+ status
+ #endif
}
+ .hoverTracking($hovering)
.frame(maxWidth: .infinity, alignment: .trailing)
.padding(.leading, 56)
}
@@ -167,6 +199,8 @@ struct AgentBubble: View {
let entry: Entry
let openTrace: () -> Void
var reply: (() -> Void)?
+ @Environment(BotStore.self) private var model
+ @State private var hovering = false
var body: some View {
VStack(alignment: .leading, spacing: 4) {
@@ -174,19 +208,27 @@ 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))
- .contextActions {
+ .contextActions(reactions: model.reactionPick(entry)) {
var items = [
- MenuItem("Copy", icon: "doc.on.doc") { Pasteboard.copy(entry.data.text) },
- MenuItem("Show what it did", icon: "list.bullet.rectangle", action: openTrace),
+ MenuItem("Copy", icon: "square.on.square") { Pasteboard.copy(entry.data.text) },
+ MenuItem("Show what it did", icon: "list.bullet", action: openTrace),
]
- if let reply { items.insert(MenuItem("Reply in thread", icon: "bubble.left.and.bubble.right", action: reply), at: 1) }
+ if let reply { items.insert(MenuItem("Reply in thread", icon: "arrowshape.turn.up.left", action: reply), at: 1) }
return items
}
#if os(macOS)
- Text(entry.date, style: .time)
- .font(.system(size: 10))
- .foregroundStyle(Palette.tertiary)
- .padding(.leading, 12)
+ HStack(spacing: 6) {
+ Text(entry.date, style: .time)
+ .font(.system(size: 10))
+ .foregroundStyle(Palette.tertiary)
+ if hovering {
+ MessageActions(reactions: model.reactionPick(entry), reply: reply, trace: openTrace) {
+ Pasteboard.copy(entry.data.text)
+ }
+ }
+ }
+ .padding(.leading, 12)
+ .frame(minHeight: MessageActions.height)
#endif
}
.frame(maxWidth: .infinity, alignment: .leading)
@@ -236,33 +278,158 @@ struct NoticeRow: View {
}
}
-/// The bot's live activity line: a turning orb, what it's doing and for how long.
+/// The bot's live activity line: a turning orb, what it's doing and for how long. Tapping it
+/// unfolds what the bot is thinking right now (the whole trace stays in "Full conversation").
struct WorkingIndicator: View {
let bot: Bot
- let openTrace: () -> Void
+ /// The running turn's latest thinking, if the agent shares it.
+ var thinking: String?
+ @State private var expanded = false
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
HStack(alignment: .center, spacing: 10) {
- Button(action: openTrace) {
- HStack(spacing: 8) {
- ThinkingOrb(state: bot.needsInput ? .listening : .working, size: 16, color: bot.needsInput ? Palette.warning : Palette.secondary)
- Text(bot.activity.isEmpty ? "Working…" : bot.activity)
- .font(.subheadline)
- .foregroundStyle(bot.needsInput ? Palette.warning : Palette.secondary)
- .lineLimit(1)
- if let started = bot.startedAt {
- Text(Date(milliseconds: started), style: .timer)
- .font(.footnote.monospacedDigit())
- .foregroundStyle(Palette.tertiary)
+ Button {
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { expanded.toggle() }
+ } label: {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 8) {
+ ThinkingOrb(state: bot.needsInput ? .listening : .working, size: 16, color: bot.needsInput ? Palette.warning : Palette.secondary)
+ Text(bot.activity.isEmpty ? "Working…" : bot.activity)
+ .font(.subheadline)
+ .foregroundStyle(bot.needsInput ? Palette.warning : Palette.secondary)
+ .lineLimit(1)
+ if let started = bot.startedAt {
+ Text(Date(milliseconds: started), style: .timer)
+ .font(.footnote.monospacedDigit())
+ .foregroundStyle(Palette.tertiary)
+ }
+ if thinking != nil {
+ Image(systemName: "chevron.down")
+ .font(.caption2.weight(.semibold))
+ .foregroundStyle(Palette.tertiary)
+ .rotationEffect(.degrees(expanded ? 180 : 0))
+ }
+ }
+ if expanded, let thinking {
+ ScrollView {
+ Text(thinking)
+ .font(.footnote)
+ .foregroundStyle(Palette.secondary)
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .defaultScrollAnchor(.bottom)
+ .frame(maxHeight: 180)
+ .fixedSize(horizontal: false, vertical: true)
+ .transition(.opacity)
}
- Image(systemName: "chevron.right").font(.caption2).foregroundStyle(Palette.tertiary)
}
.padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 16))
.padding(.vertical, 12)
.background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
}
.buttonStyle(.plain)
- Spacer()
+ .disabled(thinking == nil)
+ .accessibilityHint(thinking == nil ? "" : expanded ? "Hides its thinking" : "Shows its thinking")
+ Spacer(minLength: 40)
+ }
+ }
+}
+
+extension BotStore {
+ /// The latest thinking of the turn running in a chat (`thread` nil) or thread: the newest
+ /// thought since the last message.
+ func currentThinking(_ botId: String, thread: String?) -> String? {
+ for e in allEntries(botId).reversed() where e.threadId == thread {
+ if e.kind == "user" || (e.kind == "agent" && e.data.final == true) { return nil }
+ if e.kind == "thought", let text = e.data.text, !text.isEmpty { return text }
+ }
+ return nil
+ }
+}
+
+extension BotStore {
+ /// The quick-reaction row for a message.
+ func reactionPick(_ entry: Entry) -> ReactionPick {
+ ReactionPick(emoji: Self.quickReactions, chosen: entry.data.reactions ?? []) { self.react(entry, $0) }
+ }
+}
+
+/// The user's reactions under a message; tapping one takes it back.
+struct ReactionsRow: View {
+ let entry: Entry
+ @Environment(BotStore.self) private var model
+
+ var body: some View {
+ if let reactions = entry.data.reactions, !reactions.isEmpty {
+ HStack(spacing: 4) {
+ ForEach(reactions, id: \.self) { emoji in
+ Button { model.react(entry, emoji) } label: {
+ Text(emoji)
+ .font(.system(size: InterfaceMetrics.value(mac: 13, mobile: 15)))
+ .padding(.horizontal, 8)
+ .padding(.vertical, 3)
+ .background(Palette.surface, in: Capsule())
+ .contentShape(Capsule())
+ }
+ .buttonStyle(PressScale())
+ .help("Remove \(emoji)")
+ .accessibilityLabel("Remove reaction \(emoji)")
+ .transition(.scale.combined(with: .opacity))
+ }
+ }
}
}
}
+
+extension View {
+ /// Mac: follows the pointer over the message (bubble and its footer), animated.
+ func hoverTracking(_ hovering: Binding<Bool>) -> some View {
+ modifier(HoverTracking(hovering: hovering))
+ }
+}
+
+private struct HoverTracking: ViewModifier {
+ @Binding var hovering: Bool
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ func body(content: Content) -> some View {
+ #if os(macOS)
+ content
+ .contentShape(Rectangle())
+ .onHover { h in withAnimation(Motion.reduced(Motion.hover, reduceMotion)) { hovering = h } }
+ #else
+ content
+ #endif
+ }
+}
+
+/// Mac: a message's quick actions, in its footer beside the time while the pointer is over it
+/// (next to the bubble, never on it): reactions, reply in thread, what it did, copy.
+struct MessageActions: View {
+ static let height: CGFloat = 26
+ let reactions: ReactionPick
+ let reply: (() -> Void)?
+ var trace: (() -> Void)?
+ let copy: () -> Void
+
+ var body: some View {
+ HStack(spacing: 0) {
+ ReactionStrip(pick: reactions)
+ Rectangle().fill(Palette.text.opacity(0.12)).frame(width: 1, height: 12).padding(.horizontal, 4)
+ if let reply { action("Reply in thread", "arrowshape.turn.up.left", reply) }
+ if let trace { action("Show what it did", "list.bullet", trace) }
+ action("Copy", "square.on.square", copy)
+ }
+ .fixedSize()
+ .transition(.opacity)
+ }
+
+ private func action(_ title: String, _ icon: String, _ run: @escaping () -> Void) -> some View {
+ Button(title, systemImage: icon, action: run)
+ .labelStyle(.iconOnly)
+ .buttonStyle(IconButtonStyle(size: Self.height))
+ .help(title)
+ }
+}
diff --git a/kit/Sources/CodyncUI/Thread/Composer.swift b/kit/Sources/CodyncUI/Thread/Composer.swift
index 29e9e592..5ab9dcb0 100644
--- a/kit/Sources/CodyncUI/Thread/Composer.swift
+++ b/kit/Sources/CodyncUI/Thread/Composer.swift
@@ -107,6 +107,12 @@ struct Composer: View {
.padding(.leading, InterfaceMetrics.value(mac: 14, mobile: 18))
.padding(.trailing, 6)
.padding(.vertical, InterfaceMetrics.value(mac: 4, mobile: 6))
+ .onChange(of: model.routineDrafts[botId]) { _, value in
+ guard thread == nil, let value else { return }
+ draft = draft.isEmpty ? value : draft + "\n" + value
+ model.routineDrafts.removeValue(forKey: botId)
+ focused = true
+ }
.composerSurface(in: RoundedRectangle(cornerRadius: 24, style: .continuous))
.padding(.horizontal, 16)
.padding(.top, 6)
diff --git a/kit/Sources/CodyncUI/Thread/RepliesView.swift b/kit/Sources/CodyncUI/Thread/RepliesView.swift
index b28fae21..eb56cd9e 100644
--- a/kit/Sources/CodyncUI/Thread/RepliesView.swift
+++ b/kit/Sources/CodyncUI/Thread/RepliesView.swift
@@ -51,7 +51,7 @@ struct RepliesView: View {
}
}
if let chat, chat.isWorking(in: botId, thread: rootId), !model.isOffline {
- WorkingIndicator(bot: chat) { showTrace = true }.padding(.top, 6)
+ WorkingIndicator(bot: chat, thinking: model.currentThinking(botId, thread: rootId)).padding(.top, 6)
}
Color.clear.frame(height: 8)
}
@@ -64,9 +64,9 @@ struct RepliesView: View {
}
.background(Palette.background)
.task(id: rootId) { await model.loadThread(botId, root: rootId) }
- // Replies count as unread too: reading the thread reads them.
- .onAppear { model.markRead(botId) }
- .onChange(of: replies.last?.id) { _, _ in model.markRead(botId) }
+ // A thread is read on its own: having it open reads its replies.
+ .onAppear { model.markRead(botId, thread: rootId) }
+ .onChange(of: replies.last?.id) { _, _ in model.markRead(botId, thread: rootId) }
.codyncSheet(isPresented: $showTrace) {
TraceView(botId: botId, thread: rootId)
#if os(macOS)
diff --git a/kit/Sources/CodyncUI/Thread/ThreadView.swift b/kit/Sources/CodyncUI/Thread/ThreadView.swift
index 65451d85..af4d553a 100644
--- a/kit/Sources/CodyncUI/Thread/ThreadView.swift
+++ b/kit/Sources/CodyncUI/Thread/ThreadView.swift
@@ -24,6 +24,9 @@ public struct ThreadView: View {
@State private var compactDetails = false
@State private var calling = false
@State private var showMenu = false
+ @State private var showRoutines = false
+ @State private var routineId: String?
+ @State private var routineRequest = UUID()
@Environment(\.accessibilityReduceMotion) private var reduceMotion
private var bot: Bot? { model.bots[botId] }
@@ -101,7 +104,7 @@ public struct ThreadView: View {
}
// Offline, "working" is only what the computer last said; don't show it as live.
if let bot, bot.isWorking(in: botId, thread: nil), !model.isOffline {
- WorkingIndicator(bot: bot) { showTrace = true }
+ WorkingIndicator(bot: bot, thinking: model.currentThinking(botId, thread: nil))
.padding(.top, 6)
.id("working")
}
@@ -214,6 +217,16 @@ public struct ThreadView: View {
message: "The conversation stays here, but the agent starts with a fresh context.") {
[DialogAction("New session") { model.newSession(botId) }]
}
+ .codyncSheet(isPresented: $showRoutines) {
+ ScrollView {
+ RoutinesView(botId: botId, initialId: routineId) {
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { showRoutines = false }
+ }.padding(20)
+ }
+ #if os(macOS)
+ .frame(width: 440, height: 580)
+ #endif
+ }
.deleteBotConfirmation($confirmDelete) { dismiss() }
}
@@ -229,10 +242,19 @@ public struct ThreadView: View {
.padding(.top, 18)
.padding(.bottom, 6)
case .entry(let e, let groupStart):
- ChatRow(entry: e, groupStart: groupStart, chat: bot) {
- showTrace = true
- } openThread: { root in
- withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { openThread = ThreadTarget(id: root.id) }
+ if e.kind == "notice", let id = e.data.routineId {
+ Button {
+ openRoutine(id)
+ } label: {
+ Label(e.data.text ?? "Routine", systemImage: "clock.arrow.circlepath")
+ .font(.footnote).foregroundStyle(Palette.secondary).padding(.vertical, 10)
+ }.buttonStyle(.plain)
+ } else {
+ ChatRow(entry: e, groupStart: groupStart, chat: bot) {
+ showTrace = true
+ } openThread: { root in
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { openThread = ThreadTarget(id: root.id) }
+ }
}
}
}
@@ -275,13 +297,29 @@ public struct ThreadView: View {
/// Its own view so it stays live inside the compact modal (which captures its content).
private var detailsPanel: some View {
- DetailsPanel(botId: botId, editing: $editingDetails, editGroup: { editingGroup = true }) {
+ DetailsPanel(botId: botId, routineId: routineId, editing: $editingDetails, editGroup: { editingGroup = true }) {
withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { showSettings = false }
compactDetails = false
}
+ .id(routineRequest)
}
#endif
+ private func openRoutine(_ id: String?) {
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) {
+ routineId = id
+ routineRequest = UUID()
+ #if os(macOS)
+ editingDetails = false
+ openThread = nil
+ showSettings = true
+ if availableWidth < 680 { compactDetails = true }
+ #else
+ showRoutines = true
+ #endif
+ }
+ }
+
private var menuItems: [MenuItem] {
var items = [MenuItem("Full conversation", icon: "list.bullet.rectangle") { showTrace = true }]
if let bot, bot.isGroup {
@@ -304,6 +342,9 @@ public struct ThreadView: View {
})
items.append(MenuItem(bot.pinned ? "Unpin" : "Pin", icon: "pin") { model.setPinned(bot, !bot.pinned) })
}
+ items.append(MenuItem("Routines", icon: "clock.arrow.circlepath") {
+ openRoutine(nil)
+ })
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
@@ -456,6 +497,7 @@ private struct IntroCard: View {
/// The Mac inspector beside a conversation: the computer, the agent, and the bot's settings.
private struct DetailsPanel: View {
let botId: String
+ let routineId: String?
@Binding var editing: Bool
let editGroup: () -> Void
let close: () -> Void
@@ -472,9 +514,11 @@ private struct DetailsPanel: View {
Text("Settings").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.text)
Spacer()
} else if bot?.isGroup == true {
+ panelTitle("Members")
Spacer()
IconButton("Edit group", systemImage: "gearshape", action: editGroup)
} else {
+ panelTitle("Details")
Spacer()
IconButton("Bot settings", systemImage: "gearshape") { setEditing(true) }
}
@@ -504,43 +548,99 @@ private struct DetailsPanel: View {
withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { editing = on }
}
+ private func panelTitle(_ title: String) -> some View {
+ Text(title)
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(Palette.secondary)
+ .padding(.leading, 4)
+ }
+
private var details: some View {
ScrollView {
- VStack(alignment: .leading, spacing: 22) {
- VStack(spacing: 12) {
- VStack(spacing: 12) {
- Image(systemName: "desktopcomputer")
- .font(.system(size: 32, weight: .light))
- Text(computerStatus)
- .font(.system(size: 12))
- .multilineTextAlignment(.center)
- .foregroundStyle(Palette.secondary)
- }
- .frame(maxWidth: .infinity)
- .frame(height: 164)
- .background(Palette.surface, in: RoundedRectangle(cornerRadius: 8))
+ VStack(alignment: .leading, spacing: 28) {
+ computerSummary
+ RoutinesView(botId: botId, initialId: routineId)
+ if let bot { agentSummary(bot) }
+ }
+ .padding(.horizontal, 16)
+ .padding(.top, 8)
+ .padding(.bottom, 24)
+ }
+ }
+
+ private var computerSummary: some View {
+ VStack(alignment: .leading, spacing: 16) {
+ HStack(spacing: 12) {
+ // Laptop, Mac mini, Linux…: the computer's own icon and color, as everywhere else.
+ ComputerBadge(model.computer, size: 32)
+ VStack(alignment: .leading, spacing: 4) {
Text(model.hostName)
- .font(.caption)
- .foregroundStyle(Palette.tertiary)
- }
- if let bot {
- VStack(alignment: .leading, spacing: 8) {
- Text("Agent").font(.system(size: 13, weight: .semibold))
- Text(model.backendName(bot.backend)).foregroundStyle(Palette.secondary)
- Text(bot.cwd)
- .font(.system(size: 12))
- .foregroundStyle(Palette.secondary)
- .textSelection(.enabled)
- if !bot.description.isEmpty {
- Text(bot.description).foregroundStyle(Palette.secondary)
- }
- }
- .font(.system(size: 13))
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(Palette.text)
+ .lineLimit(2)
+ Text("Remote screen")
+ .font(.system(size: 11))
+ .foregroundStyle(Palette.secondary)
}
}
- .padding(.horizontal, 16)
- .padding(.bottom, 16)
+ Label(computerStatus, systemImage: computerStatusSymbol)
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(Palette.text)
+ .fixedSize(horizontal: false, vertical: true)
+ if screenReady {
+ Text("View and control this Mac from your iPhone.")
+ .font(.system(size: 11))
+ .foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.top, -8)
+ }
}
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(16)
+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 12))
+ }
+
+ private func agentSummary(_ bot: Bot) -> some View {
+ VStack(alignment: .leading, spacing: 14) {
+ Text("Agent")
+ .font(.system(size: 13, weight: .semibold))
+ .foregroundStyle(Palette.text)
+ HStack {
+ Text("Runtime").foregroundStyle(Palette.secondary)
+ Spacer(minLength: 12)
+ Text(model.backendName(bot.backend)).foregroundStyle(Palette.text)
+ }
+ .font(.system(size: 12))
+ VStack(alignment: .leading, spacing: 6) {
+ Label("Working folder", systemImage: "folder")
+ .font(.system(size: 11))
+ .foregroundStyle(Palette.secondary)
+ Text(bot.cwd)
+ .font(.system(size: 11, design: .monospaced))
+ .foregroundStyle(Palette.text)
+ .fixedSize(horizontal: false, vertical: true)
+ .textSelection(.enabled)
+ }
+ if !bot.description.isEmpty {
+ Text(bot.description)
+ .font(.system(size: 12))
+ .foregroundStyle(Palette.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+
+ private var screenReady: Bool {
+ !model.isOffline && model.screen?.enabled == true
+ && model.screen?.connected == true && model.screen?.capture == true
+ }
+
+ private var computerStatusSymbol: String {
+ if model.isOffline { return "wifi.slash" }
+ guard let screen = model.screen, screen.enabled else { return "power" }
+ if !screen.connected { return "arrow.triangle.2.circlepath" }
+ if !screen.capture { return "exclamationmark.circle" }
+ return screen.agentBot == botId ? "cursorarrow.motionlines" : "checkmark.circle"
}
private var computerStatus: String {
@@ -548,7 +648,7 @@ private struct DetailsPanel: View {
guard let screen = model.screen, screen.enabled else { return "Remote screen is off" }
guard screen.connected else { return "Connecting to computer…" }
guard screen.capture else { return "Screen recording permission needed" }
- return screen.agentBot == botId ? "This bot is using your Mac" : "Ready · View this Mac from your iPhone"
+ return screen.agentBot == botId ? "This bot is using your Mac" : "Ready to connect"
}
}
#endif
diff --git a/kit/Tests/CodyncKitTests/AgentModelsTests.swift b/kit/Tests/CodyncKitTests/AgentModelsTests.swift
new file mode 100644
index 00000000..04f0c720
--- /dev/null
+++ b/kit/Tests/CodyncKitTests/AgentModelsTests.swift
@@ -0,0 +1,24 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+
+@Test func modelCatalogDecodesAgentNamesAndIDs() throws {
+ let data = Data(#"{"models":[{"id":"opus[1m]","name":"Agent model","description":"From the agent"}],"currentModelId":"opus[1m]"}"#.utf8)
+ let catalog = try JSONDecoder().decode(AgentModels.self, from: data)
+ #expect(catalog.models.first?.id == "opus[1m]")
+ #expect(catalog.models.first?.name == "Agent model")
+ #expect(catalog.currentModelId == "opus[1m]")
+}
+
+@Test func modelDefaultExplicitlyClearsSavedOverride() throws {
+ var draft = BotDraft(name: "Example", cwd: "/tmp")
+ draft.id = "bot-id"
+ let data = try JSONEncoder().encode(BotUpdate(draft: draft))
+ let body = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
+ #expect(body["model"] is NSNull)
+ #expect(body["id"] as? String == "bot-id")
+ #expect(body["name"] as? String == "Example")
+ draft.model = "agent-model"
+ let selected = try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode(BotUpdate(draft: draft))) as? [String: Any])
+ #expect(selected["model"] as? String == "agent-model")
+}
diff --git a/kit/Tests/CodyncKitTests/RoutineTests.swift b/kit/Tests/CodyncKitTests/RoutineTests.swift
new file mode 100644
index 00000000..3a2bf6cc
--- /dev/null
+++ b/kit/Tests/CodyncKitTests/RoutineTests.swift
@@ -0,0 +1,62 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+
+@Test func routinesDecodeMixedTriggersAndRunHistory() throws {
+ let data = Data(#"{"routines":[{"id":"r","botId":"b","name":"Check","instruction":"Check status","triggers":[{"type":"cron","expression":"20 14 * * 0","timeZone":"Asia/Taipei"},{"type":"webhook"}],"enabled":true,"createdAt":0,"updatedAt":0,"triggerDescriptions":["Every Sunday","When a webhook fires"],"nextRunAt":1000}],"runs":[{"id":"run","routineId":"r","botId":"b","status":"pending","createdAt":0,"event":{"source":"schedule"}}]}"#.utf8)
+ let listing = try JSONDecoder().decode(RoutineListing.self, from: data)
+ #expect(listing.routines[0].triggers[0].timeZone == "Asia/Taipei")
+ #expect(listing.routines[0].triggers[1].type == "webhook")
+ #expect(listing.runs[0].isActive)
+ #expect(listing.runs[0].rootId == nil)
+}
+
+@Test func routineTranscriptLinkSurvivesRoundTrip() throws {
+ let data = Data(#"{"text":"Created routine","routineId":"r","runId":"run","style":"info"}"#.utf8)
+ let entry = try JSONDecoder().decode(EntryData.self, from: data)
+ let restored = try JSONDecoder().decode(EntryData.self, from: JSONEncoder().encode(entry))
+ #expect(restored.routineId == "r")
+ #expect(restored.runId == "run")
+}
+
+@Test func routineScheduleEditsKeepExactIntervalsAndCalendarTimes() throws {
+ let interval = RoutineTrigger(type: "interval", seconds: 5400)
+ let draft = RoutineScheduleDraft(triggers: [interval])
+ #expect(draft.amount == "90")
+ #expect(draft.unit == 60)
+ #expect(try draft.triggers() == [interval])
+ let weekly = RoutineTrigger(type: "cron", expression: "20 14 * * 0", timeZone: "Asia/Taipei")
+ let calendar = RoutineScheduleDraft(triggers: [weekly])
+ #expect(calendar.calendarStyle == "weekly")
+ #expect(calendar.weekday == 0)
+ #expect(try calendar.triggers() == [weekly])
+ let custom = RoutineTrigger(type: "cron", expression: "*/15 9-17 * * 1-5", timeZone: "America/New_York")
+ #expect(try RoutineScheduleDraft(triggers: [custom]).triggers() == [custom])
+ #expect(try RoutineScheduleDraft(triggers: [weekly, interval]).triggers() == [weekly, interval])
+}
+
+@Test func routineScheduleConvertsUnitsAndRejectsOverflow() throws {
+ var draft = RoutineScheduleDraft()
+ draft.amount = "2"
+ draft.unit = 3600
+ #expect(try draft.triggers().first?.seconds == 7200)
+ draft.amount = String(Int64.max)
+ #expect(throws: (any Error).self) { try draft.triggers() }
+ draft.amount = "0"
+ #expect(throws: (any Error).self) { try draft.triggers() }
+ draft.kind = "cron"
+ draft.zone = "invalid/zone"
+ #expect(throws: (any Error).self) { try draft.triggers() }
+}
+
+@Test func editingAnExpiredOneTimeRoutinePreservesItsTimestamp() throws {
+ let once = RoutineTrigger(type: "once", at: 1_779_000_000_001)
+ #expect(try RoutineScheduleDraft(triggers: [once]).triggers() == [once])
+}
+
+@Test func weekdayScheduleKeepsItsZoneAndWorkingDays() throws {
+ let weekday = RoutineTrigger(type: "cron", expression: "30 8 * * 1-5", timeZone: "America/New_York")
+ let draft = RoutineScheduleDraft(triggers: [weekday])
+ #expect(draft.calendarStyle == "weekdays")
+ #expect(try draft.triggers() == [weekday])
+}