Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
Tidy shared UI code and the Mac host controller
leepokai27b68402246f
diff --git a/.gitignore b/.gitignoreindex a7d6d1dd..a4569a74 100644--- a/.gitignore+++ b/.gitignore@@ -14,3 +14,4 @@ Package.resolved*.p8.dev.vars.wrangler/+.claude/worktrees/diff --git a/Codync-iOS/Views/BotListView.swift b/Codync-iOS/Views/BotListView.swiftindex 22f7770d..e619d58f 100644--- a/Codync-iOS/Views/BotListView.swift+++ b/Codync-iOS/Views/BotListView.swift@@ -79,17 +79,7 @@ struct BotListView: View {.sheet(isPresented: $showSettings) {NavigationStack { SettingsView() }}- .confirmationDialog(- "Delete \(confirmDelete?.name ?? "")?",- isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } }),- titleVisibility: .visible- ) {- Button("Delete bot and its conversation", role: .destructive) {- if let bot = confirmDelete { model.delete(bot) }- }- } message: {- Text("Files it changed on your computer stay as they are.")- }+ .deleteBotConfirmation($confirmDelete)}}diff --git a/Codync-iOS/Views/RootView.swift b/Codync-iOS/Views/RootView.swiftindex fbeb3928..28c28a94 100644--- a/Codync-iOS/Views/RootView.swift+++ b/Codync-iOS/Views/RootView.swift@@ -24,10 +24,6 @@ struct RootView: View {}}.background(Palette.background)- .alert("Something went wrong", isPresented: Binding(get: { model.lastError != nil }, set: { if !$0 { model.lastError = nil } })) {- Button("OK", role: .cancel) {}- } message: {- Text(model.lastError ?? "")- }+ .storeErrorAlert(model)}}diff --git a/Codync-macOS/ChatWindow.swift b/Codync-macOS/ChatWindow.swiftindex 9757c1a3..50be7bcf 100644--- a/Codync-macOS/ChatWindow.swift+++ b/Codync-macOS/ChatWindow.swift@@ -87,17 +87,7 @@ private struct ChatSplitView: View {NavigationStack { BotEditorView(draft: request.draft) }.frame(minWidth: 520, minHeight: 640)}- .confirmationDialog("Delete \(confirmDelete?.name ?? "")?", isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } })) {- Button("Delete Bot and Conversation", role: .destructive) {- if let bot = confirmDelete { model.delete(bot) }- }- } message: {- Text("Files it changed on this computer stay as they are.")- }- .alert("Something went wrong", isPresented: Binding(get: { model.lastError != nil }, set: { if !$0 { model.lastError = nil } })) {- Button("OK", role: .cancel) {}- } message: {- Text(model.lastError ?? "")- }+ .deleteBotConfirmation($confirmDelete)+ .storeErrorAlert(model)}}diff --git a/Codync-macOS/CodyncMacApp.swift b/Codync-macOS/CodyncMacApp.swiftindex 8bde6109..79393f44 100644--- a/Codync-macOS/CodyncMacApp.swift+++ b/Codync-macOS/CodyncMacApp.swift@@ -158,7 +158,7 @@ struct MenuView: View {HStack(spacing: 8) {Text("\(p.name) \(w.label)").font(.caption).foregroundStyle(Palette.secondary).frame(width: 130, alignment: .leading)ProgressView(value: min(w.percent, 100), total: 100)- .tint(w.percent >= 90 ? Palette.danger : w.percent >= 70 ? Palette.warning : Palette.accent)+ .tint(Palette.usageTint(w.percent))Text("\(Int(w.percent.rounded()))%").font(.caption.monospacedDigit()).frame(width: 36, alignment: .trailing)}}diff --git a/Codync-macOS/HostController.swift b/Codync-macOS/HostController.swiftindex dffb8f01..8aafedf1 100644--- a/Codync-macOS/HostController.swift+++ b/Codync-macOS/HostController.swift@@ -17,11 +17,6 @@ final class HostController {case failed(String)}- struct PairInfo: Decodable {- var urls: [String]- var pairingUrl: String- }-/// `CODYNC_PORT` / `CODYNC_HOME` point the app at a dev host started with `codync-host serve`.static let devPort = ProcessInfo.processInfo.environment["CODYNC_PORT"].flatMap(Int.init)static let port = devPort ?? 19222@@ -31,7 +26,7 @@ final class HostController {private(set) var state: State = .starting/// Live mirror of the host (same store the iPhone uses), once it's reachable.private(set) var store: BotStore?- private(set) var pairInfo: PairInfo?+ private(set) var pairInfo: PairingInfo?private(set) var version: String?var launchAtLogin: Bool = SMAppService.mainApp.status == .enabled@@ -112,11 +107,8 @@ final class HostController {}func loadPairing() {- guard let bin = binaryURL else { return }- Task {- let result = await Self.run(bin, ["pair", "--json", "--port", "\(Self.port)"])- pairInfo = try? JSONDecoder().decode(PairInfo.self, from: Data(result.output.utf8))- }+ guard let client = client() else { return }+ Task { pairInfo = try? await client.pairing() }}func setLaunchAtLogin(_ on: Bool) {@@ -170,12 +162,7 @@ final class HostController {let p = Process()p.executableURL = binp.arguments = args- // GUI apps get a minimal PATH; give the service the usual tool locations.- var env = ProcessInfo.processInfo.environment- let home = FileManager.default.homeDirectoryForCurrentUser.path- let extra = ["/opt/homebrew/bin", "/usr/local/bin", "\(home)/.local/bin", "\(home)/.cargo/bin", "\(home)/.bun/bin", "\(home)/.opencode/bin"]- env["PATH"] = (extra + [loginShellPath() ?? "/usr/bin:/bin:/usr/sbin:/sbin"]).joined(separator: ":")- p.environment = env+ // The host rebuilds PATH from the login shell itself (backends::hydrate_path).let pipe = Pipe()p.standardOutput = pipep.standardError = pipe@@ -186,19 +173,4 @@ final class HostController {do { try p.run() } catch { cont.resume(returning: (-1, error.localizedDescription)) }}}-- /// The user's interactive PATH (nvm, asdf, …) so npx/claude/codex resolve in the service.- nonisolated static func loginShellPath() -> String? {- let shell = ProcessInfo.processInfo.environment["SHELL"] ?? "/bin/zsh"- let p = Process()- p.executableURL = URL(filePath: shell)- p.arguments = ["-ilc", "printf %s \"$PATH\""]- let pipe = Pipe()- p.standardOutput = pipe- p.standardError = FileHandle.nullDevice- guard (try? p.run()) != nil else { return nil }- p.waitUntilExit()- let out = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)- return out.isEmpty ? nil : out- }}diff --git a/CodyncKit/Sources/CodyncKit/HostClient.swift b/CodyncKit/Sources/CodyncKit/HostClient.swiftindex ada49863..4ce22a17 100644--- a/CodyncKit/Sources/CodyncKit/HostClient.swift+++ b/CodyncKit/Sources/CodyncKit/HostClient.swift@@ -241,6 +241,9 @@ public extension HostClient {try await call("usage", ["refresh": refresh])}+ /// Pairing link + candidate addresses for showing a QR code on this computer.+ func pairing() async throws -> PairingInfo { try await call("pairing") }+func listDirs(_ path: String?) async throws -> DirListing {struct Body: Encodable { var path: String? }return try await call("listDirs", Body(path: path))diff --git a/CodyncKit/Sources/CodyncKit/Models.swift b/CodyncKit/Sources/CodyncKit/Models.swiftindex 4fc16707..5c3a763b 100644--- a/CodyncKit/Sources/CodyncKit/Models.swift+++ b/CodyncKit/Sources/CodyncKit/Models.swift@@ -188,6 +188,11 @@ public struct SyncResponse: Codable, Sendable {public var usage: Usage}+public struct PairingInfo: Codable, Sendable {+ public var pairingUrl: String+ public var urls: [String]+}+public struct DirListing: Codable, Sendable {public var path: Stringpublic var parent: String?diff --git a/CodyncKit/Sources/CodyncKit/UsageStyle.swift b/CodyncKit/Sources/CodyncKit/UsageStyle.swiftnew file mode 100644index 00000000..d195da1b--- /dev/null+++ b/CodyncKit/Sources/CodyncKit/UsageStyle.swift@@ -0,0 +1,36 @@+import SwiftUI++/// One place for "how full is this limit" colors, shared by the apps, the menu bar and widgets.+public extension Palette {+ /// Fill for bars: lime, orange from 70%, red from 90%.+ static func usageFill(_ percent: Double) -> Color {+ percent >= 90 ? danger : percent >= 70 ? warning : accentFill+ }++ /// Tint for gauges and progress views (readable lime on light backgrounds).+ static func usageTint(_ percent: Double) -> Color {+ percent >= 90 ? danger : percent >= 70 ? warning : accent+ }+}++public struct UsageBar: View {+ let percent: Double+ let height: CGFloat++ public init(percent: Double, height: CGFloat = 6) {+ self.percent = percent+ self.height = height+ }++ public var body: some View {+ GeometryReader { geo in+ ZStack(alignment: .leading) {+ Capsule().fill(Palette.bubbleAgent)+ Capsule()+ .fill(Palette.usageFill(percent))+ .frame(width: geo.size.width * min(1, max(0.02, percent / 100)))+ }+ }+ .frame(height: height)+ }+}diff --git a/CodyncKit/Sources/CodyncUI/ChatRows.swift b/CodyncKit/Sources/CodyncUI/ChatRows.swiftnew file mode 100644index 00000000..b06a97f5--- /dev/null+++ b/CodyncKit/Sources/CodyncUI/ChatRows.swift@@ -0,0 +1,161 @@+import CodyncKit+import SwiftUI++/// The rows a conversation is made of.++struct UserBubble: View {+ let entry: Entry+ let botWorking: Bool+ @Environment(BotStore.self) private var model++ var body: some View {+ VStack(alignment: .trailing, spacing: 4) {+ Text(entry.data.text ?? "")+ .font(.body)+ .foregroundStyle(Palette.onAccent)+ .textSelection(.enabled)+ .padding(.horizontal, 13)+ .padding(.vertical, 9)+ .background(Palette.accentFill, in: RoundedRectangle(cornerRadius: 18, style: .continuous))+ .contextMenu {+ Button("Copy", systemImage: "doc.on.doc") { Pasteboard.copy(entry.data.text) }+ }+ status+ }+ .frame(maxWidth: .infinity, alignment: .trailing)+ .padding(.leading, 48)+ }++ @ViewBuilder private var status: some View {+ switch entry.data.status {+ case "sending":+ Text("Sending…").font(.caption2).foregroundStyle(Palette.tertiary)+ case "queued" where botWorking:+ Text("Waiting to send — it'll read this when it's done").font(.caption2).foregroundStyle(Palette.tertiary)+ case "failed":+ HStack(spacing: 10) {+ Text("Failed to send").foregroundStyle(Palette.danger)+ Button("Resend", systemImage: "arrow.clockwise") { model.retry(entry) }.labelStyle(.iconOnly).help("Resend")+ Button("Delete", systemImage: "trash") { model.discard(entry) }.labelStyle(.iconOnly).help("Delete")+ }+ .font(.caption2.bold())+ case "cancelled":+ Text("Not sent — stopped").font(.caption2).foregroundStyle(Palette.tertiary)+ default:+ EmptyView()+ }+ }+}++struct AgentBubble: View {+ let entry: Entry+ let bot: Bot?+ let showAvatar: Bool+ let openTrace: () -> Void++ var body: some View {+ HStack(alignment: .bottom, spacing: 8) {+ Group {+ if showAvatar, let bot {+ CharacterAvatar(bot: bot, size: 28, animated: false)+ } else {+ Color.clear+ }+ }+ .frame(width: 28, height: 28)+ MarkdownText(entry.data.text ?? "")+ .padding(.horizontal, 13)+ .padding(.vertical, 9)+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18, style: .continuous))+ .contextMenu {+ Button("Copy", systemImage: "doc.on.doc") { Pasteboard.copy(entry.data.text) }+ Button("Show what it did", systemImage: "list.bullet.rectangle", action: openTrace)+ }+ Spacer(minLength: 24)+ }+ }+}++struct NoticeRow: View {+ let entry: Entry++ var body: some View {+ let text = entry.data.text ?? ""+ switch entry.data.style {+ case "divider":+ HStack(spacing: 10) {+ Rectangle().fill(Palette.border).frame(height: 1)+ Text(text)+ .font(.caption2)+ .foregroundStyle(Palette.tertiary)+ .multilineTextAlignment(.center)+ .fixedSize(horizontal: false, vertical: true)+ .frame(maxWidth: 260)+ .layoutPriority(1)+ Rectangle().fill(Palette.border).frame(height: 1)+ }+ .padding(.vertical, 6)+ case "error":+ Label {+ Text(text).font(.footnote).foregroundStyle(Palette.text).textSelection(.enabled)+ } icon: {+ Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(Palette.danger)+ }+ .padding(12)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Palette.danger.opacity(0.12), in: RoundedRectangle(cornerRadius: 12))+ default:+ Text(text)+ .font(.caption)+ .foregroundStyle(Palette.tertiary)+ .frame(maxWidth: .infinity)+ }+ }+}++/// Grok Bot's typing bubble, plus the live activity line and elapsed time.+struct WorkingIndicator: View {+ let bot: Bot+ let openTrace: () -> Void++ var body: some View {+ HStack(alignment: .center, spacing: 8) {+ CharacterAvatar(bot: bot, size: 28)+ VStack(alignment: .leading, spacing: 4) {+ TypingDots()+ .padding(.horizontal, 12)+ .padding(.vertical, 11)+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 14, style: .continuous))+ Button(action: openTrace) {+ HStack(spacing: 4) {+ Text(bot.activity.isEmpty ? "Working…" : bot.activity).lineLimit(1)+ if let started = bot.startedAt {+ Text("·")+ Text(Date(milliseconds: started), style: .timer).monospacedDigit()+ }+ Image(systemName: "chevron.right").font(.caption2)+ }+ .font(.caption)+ .foregroundStyle(bot.needsInput ? Palette.warning : Palette.secondary)+ }+ .buttonStyle(.plain)+ }+ Spacer()+ }+ }+}++struct TypingDots: View {+ var body: some View {+ HStack(spacing: 4) {+ ForEach(0..<3, id: \.self) { i in+ Circle()+ .fill(Palette.secondary)+ .frame(width: 6, height: 6)+ .phaseAnimator([0.3, 1.0]) { view, phase in+ view.opacity(phase)+ } animation: { _ in .easeInOut(duration: 0.5).delay(Double(i) * 0.15) }+ }+ }+ }+}diff --git a/CodyncKit/Sources/CodyncUI/Dialogs.swift b/CodyncKit/Sources/CodyncUI/Dialogs.swiftnew file mode 100644index 00000000..884f6dd1--- /dev/null+++ b/CodyncKit/Sources/CodyncUI/Dialogs.swift@@ -0,0 +1,40 @@+import CodyncKit+import SwiftUI++public extension View {+ /// The one "Delete <bot>?" confirmation, used wherever a bot can be deleted.+ /// Setting `bot` presents it; `onDeleted` runs after the store deletes it.+ func deleteBotConfirmation(_ bot: Binding<Bot?>, onDeleted: @escaping () -> Void = {}) -> some View {+ modifier(DeleteBotConfirmation(bot: bot, onDeleted: onDeleted))+ }++ /// Shows `BotStore.lastError` as an alert.+ func storeErrorAlert(_ model: BotStore) -> some View {+ alert("Something went wrong", isPresented: Binding(get: { model.lastError != nil }, set: { if !$0 { model.lastError = nil } })) {+ Button("OK", role: .cancel) {}+ } message: {+ Text(model.lastError ?? "")+ }+ }+}++private struct DeleteBotConfirmation: ViewModifier {+ @Binding var bot: Bot?+ let onDeleted: () -> Void+ @Environment(BotStore.self) private var model++ func body(content: Content) -> some View {+ content.confirmationDialog(+ "Delete \(bot?.name ?? "bot")?",+ isPresented: Binding(get: { bot != nil }, set: { if !$0 { bot = nil } }),+ titleVisibility: .visible+ ) {+ Button("Delete bot and its conversation", role: .destructive) {+ if let bot { model.delete(bot) }+ onDeleted()+ }+ } message: {+ Text("Files it changed on your computer stay as they are.")+ }+ }+}diff --git a/CodyncKit/Sources/CodyncUI/ThreadView.swift b/CodyncKit/Sources/CodyncUI/ThreadView.swiftindex fb8a7f72..6cc5160a 100644--- a/CodyncKit/Sources/CodyncUI/ThreadView.swift+++ b/CodyncKit/Sources/CodyncUI/ThreadView.swift@@ -13,7 +13,7 @@ public struct ThreadView: View {@State private var showTrace = false@State private var editing: EditorRequest?@State private var confirmNewSession = false- @State private var confirmDelete = false+ @State private var confirmDelete: Bot?@FocusState private var composerFocused: Boolprivate var bot: Bot? { model.bots[botId] }@@ -78,12 +78,7 @@ public struct ThreadView: View {} message: {Text("The conversation stays here, but the agent starts with a fresh context.")}- .confirmationDialog("Delete \(bot?.name ?? "bot")?", isPresented: $confirmDelete, titleVisibility: .visible) {- Button("Delete bot and its conversation", role: .destructive) {- if let bot { model.delete(bot) }- dismiss()- }- }+ .deleteBotConfirmation($confirmDelete) { dismiss() }}// MARK: rows@@ -147,7 +142,7 @@ public struct ThreadView: View {}Button("New session", systemImage: "arrow.counterclockwise") { confirmNewSession = true }Divider()- Button("Delete bot", systemImage: "trash", role: .destructive) { confirmDelete = true }+ Button("Delete bot", systemImage: "trash", role: .destructive) { confirmDelete = bot }} label: {Image(systemName: "ellipsis.circle")}@@ -228,165 +223,6 @@ struct ChatItem: Identifiable {}}-// MARK: - Rows--struct UserBubble: View {- let entry: Entry- let botWorking: Bool- @Environment(BotStore.self) private var model-- var body: some View {- VStack(alignment: .trailing, spacing: 4) {- Text(entry.data.text ?? "")- .font(.body)- .foregroundStyle(Palette.onAccent)- .textSelection(.enabled)- .padding(.horizontal, 13)- .padding(.vertical, 9)- .background(Palette.accentFill, in: RoundedRectangle(cornerRadius: 18, style: .continuous))- .contextMenu {- Button("Copy", systemImage: "doc.on.doc") { Pasteboard.copy(entry.data.text) }- }- status- }- .frame(maxWidth: .infinity, alignment: .trailing)- .padding(.leading, 48)- }-- @ViewBuilder private var status: some View {- switch entry.data.status {- case "sending":- Text("Sending…").font(.caption2).foregroundStyle(Palette.tertiary)- case "queued" where botWorking:- Text("Waiting to send — it'll read this when it's done").font(.caption2).foregroundStyle(Palette.tertiary)- case "failed":- HStack(spacing: 10) {- Text("Failed to send").foregroundStyle(Palette.danger)- Button("Resend", systemImage: "arrow.clockwise") { model.retry(entry) }.labelStyle(.iconOnly).help("Resend")- Button("Delete", systemImage: "trash") { model.discard(entry) }.labelStyle(.iconOnly).help("Delete")- }- .font(.caption2.bold())- case "cancelled":- Text("Not sent — stopped").font(.caption2).foregroundStyle(Palette.tertiary)- default:- EmptyView()- }- }-}--struct AgentBubble: View {- let entry: Entry- let bot: Bot?- let showAvatar: Bool- let openTrace: () -> Void-- var body: some View {- HStack(alignment: .bottom, spacing: 8) {- Group {- if showAvatar, let bot {- CharacterAvatar(bot: bot, size: 28, animated: false)- } else {- Color.clear- }- }- .frame(width: 28, height: 28)- MarkdownText(entry.data.text ?? "")- .padding(.horizontal, 13)- .padding(.vertical, 9)- .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18, style: .continuous))- .contextMenu {- Button("Copy", systemImage: "doc.on.doc") { Pasteboard.copy(entry.data.text) }- Button("Show what it did", systemImage: "list.bullet.rectangle", action: openTrace)- }- Spacer(minLength: 24)- }- }-}--struct NoticeRow: View {- let entry: Entry-- var body: some View {- let text = entry.data.text ?? ""- switch entry.data.style {- case "divider":- HStack(spacing: 10) {- Rectangle().fill(Palette.border).frame(height: 1)- Text(text)- .font(.caption2)- .foregroundStyle(Palette.tertiary)- .multilineTextAlignment(.center)- .fixedSize(horizontal: false, vertical: true)- .frame(maxWidth: 260)- .layoutPriority(1)- Rectangle().fill(Palette.border).frame(height: 1)- }- .padding(.vertical, 6)- case "error":- Label {- Text(text).font(.footnote).foregroundStyle(Palette.text).textSelection(.enabled)- } icon: {- Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(Palette.danger)- }- .padding(12)- .frame(maxWidth: .infinity, alignment: .leading)- .background(Palette.danger.opacity(0.12), in: RoundedRectangle(cornerRadius: 12))- default:- Text(text)- .font(.caption)- .foregroundStyle(Palette.tertiary)- .frame(maxWidth: .infinity)- }- }-}--/// Grok Bot's typing bubble, plus the live activity line and elapsed time.-struct WorkingIndicator: View {- let bot: Bot- let openTrace: () -> Void-- var body: some View {- HStack(alignment: .center, spacing: 8) {- CharacterAvatar(bot: bot, size: 28)- VStack(alignment: .leading, spacing: 4) {- TypingDots()- .padding(.horizontal, 12)- .padding(.vertical, 11)- .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 14, style: .continuous))- Button(action: openTrace) {- HStack(spacing: 4) {- Text(bot.activity.isEmpty ? "Working…" : bot.activity).lineLimit(1)- if let started = bot.startedAt {- Text("·")- Text(Date(milliseconds: started), style: .timer).monospacedDigit()- }- Image(systemName: "chevron.right").font(.caption2)- }- .font(.caption)- .foregroundStyle(bot.needsInput ? Palette.warning : Palette.secondary)- }- .buttonStyle(.plain)- }- Spacer()- }- }-}--struct TypingDots: View {- var body: some View {- HStack(spacing: 4) {- ForEach(0..<3, id: \.self) { i in- Circle()- .fill(Palette.secondary)- .frame(width: 6, height: 6)- .phaseAnimator([0.3, 1.0]) { view, phase in- view.opacity(phase)- } animation: { _ in .easeInOut(duration: 0.5).delay(Double(i) * 0.15) }- }- }- }-}-private struct IntroCard: View {let bot: Bot@Environment(BotStore.self) private var modeldiff --git a/CodyncKit/Sources/CodyncUI/UsageViews.swift b/CodyncKit/Sources/CodyncUI/UsageViews.swiftindex c1acc8f8..f3060636 100644--- a/CodyncKit/Sources/CodyncUI/UsageViews.swift+++ b/CodyncKit/Sources/CodyncUI/UsageViews.swift@@ -33,24 +33,6 @@ public struct UsageCard: View {}}-public struct UsageBar: View {- let percent: Double-- public init(percent: Double) { self.percent = percent }-- public var body: some View {- GeometryReader { geo in- ZStack(alignment: .leading) {- Capsule().fill(Palette.bubbleAgent)- Capsule()- .fill(percent >= 90 ? Palette.danger : percent >= 70 ? Palette.warning : Palette.accentFill)- .frame(width: geo.size.width * min(1, max(0.02, percent / 100)))- }- }- .frame(height: 6)- }-}-/// Compact usage chips at the top of the roster.public struct UsageStrip: View {let usage: Usage@@ -67,7 +49,7 @@ public struct UsageStrip: View {.gaugeStyle(.accessoryCircularCapacity).scaleEffect(0.42).frame(width: 22, height: 22)- .tint(w.percent >= 90 ? Palette.danger : w.percent >= 70 ? Palette.warning : Palette.accent)+ .tint(Palette.usageTint(w.percent))VStack(alignment: .leading, spacing: 0) {Text("\(p.name) \(w.label)").font(.caption2).foregroundStyle(Palette.tertiary)Text("\(Int(w.percent.rounded()))%").font(.caption.bold().monospacedDigit()).foregroundStyle(Palette.text)diff --git a/CodyncWidgets/CodyncWidgets.swift b/CodyncWidgets/CodyncWidgets.swiftindex 029769df..33589405 100644--- a/CodyncWidgets/CodyncWidgets.swift+++ b/CodyncWidgets/CodyncWidgets.swift@@ -114,15 +114,7 @@ struct UsageWidgetView: View {}.font(.caption2).foregroundStyle(Palette.text)- GeometryReader { geo in- ZStack(alignment: .leading) {- Capsule().fill(Palette.bubbleAgent)- Capsule()- .fill(item.window.percent >= 90 ? Palette.danger : item.window.percent >= 70 ? Palette.warning : Palette.accentFill)- .frame(width: geo.size.width * min(1, max(0.02, item.window.percent / 100)))- }- }- .frame(height: 5)+ UsageBar(percent: item.window.percent, height: 5)if family == .systemMedium, let reset = item.window.resetDescription {Text(reset).font(.system(size: 9)).foregroundStyle(Palette.tertiary)}diff --git a/linux/src/client.rs b/linux/src/client.rsindex 659ec6e0..1293a6eb 100644--- a/linux/src/client.rs+++ b/linux/src/client.rs@@ -10,7 +10,13 @@ use std::time::Duration;pub fn runtime() -> &'static tokio::runtime::Runtime {static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();- RT.get_or_init(|| tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap())+ RT.get_or_init(|| {+ tokio::runtime::Builder::new_multi_thread()+ .worker_threads(2)+ .enable_all()+ .build()+ .unwrap()+ })}pub fn data_dir() -> PathBuf {@@ -20,7 +26,10 @@ pub fn data_dir() -> PathBuf {}pub fn port() -> u16 {- std::env::var("CODYNC_PORT").ok().and_then(|p| p.parse().ok()).unwrap_or(19222)+ std::env::var("CODYNC_PORT")+ .ok()+ .and_then(|p| p.parse().ok())+ .unwrap_or(19222)}/// `CODYNC_URL` overrides the host address (e.g. a host outside a container).@@ -29,7 +38,10 @@ pub fn base() -> String {}pub fn token() -> Option<String> {- std::fs::read_to_string(data_dir().join("token")).ok().map(|t| t.trim().to_owned()).filter(|t| !t.is_empty())+ std::fs::read_to_string(data_dir().join("token"))+ .ok()+ .map(|t| t.trim().to_owned())+ .filter(|t| !t.is_empty())}fn http() -> &'static reqwest::Client {@@ -49,7 +61,11 @@ async fn call_async(method: String, body: Value) -> Result<Value, String> {.map_err(|_| "Can't reach the Codync host.".to_owned())?;let ok = res.status().is_success();let v: Value = res.json().await.unwrap_or(Value::Null);- if ok { Ok(v) } else { Err(v["error"].as_str().unwrap_or("Host error").to_owned()) }+ if ok {+ Ok(v)+ } else {+ Err(v["error"].as_str().unwrap_or("Host error").to_owned())+ }}/// Runs a host command off the main thread and hands the result back on it.@@ -82,7 +98,11 @@ pub fn stream(tx: async_channel::Sender<Event>) {runtime().spawn(async move {loop {if let Some(token) = token() {- let url = format!("{}/events?since={}&client=linux", base(), REV.load(Ordering::Relaxed));+ let url = format!(+ "{}/events?since={}&client=linux",+ base(),+ REV.load(Ordering::Relaxed)+ );if let Ok(res) = http().get(url).bearer_auth(token).send().await&& res.status().is_success(){diff --git a/linux/src/dialogs.rs b/linux/src/dialogs.rsindex 5005bb33..4d802648 100644--- a/linux/src/dialogs.rs+++ b/linux/src/dialogs.rs@@ -8,11 +8,20 @@ use serde_json::{Value, json};use std::cell::RefCell;use std::rc::Rc;-fn header_dialog(title: &str, width: i32, height: i32) -> (adw::Dialog, adw::ToolbarView, adw::HeaderBar) {+fn header_dialog(+ title: &str,+ width: i32,+ height: i32,+) -> (adw::Dialog, adw::ToolbarView, adw::HeaderBar) {let header = adw::HeaderBar::new();let view = adw::ToolbarView::new();view.add_top_bar(&header);- let dialog = adw::Dialog::builder().title(title).content_width(width).content_height(height).child(&view).build();+ let dialog = adw::Dialog::builder()+ .title(title)+ .content_width(width)+ .content_height(height)+ .child(&view)+ .build();(dialog, view, header)}@@ -20,7 +29,10 @@ fn header_dialog(title: &str, width: i32, height: i32) -> (adw::Dialog, adw::Toopub fn editor(ui: &App, bot: Option<Value>) {let is_new = bot.is_none();- let backends: Vec<Value> = ui.state.borrow().hello["backends"].as_array().cloned().unwrap_or_default();+ let backends: Vec<Value> = ui.state.borrow().hello["backends"]+ .as_array()+ .cloned()+ .unwrap_or_default();let d = Rc::new(RefCell::new(bot.clone().unwrap_or_else(|| {let n = client_seed();json!({@@ -31,7 +43,8 @@ pub fn editor(ui: &App, bot: Option<Value>) {})})));- let (dialog, view, header) = header_dialog(if is_new { "New Bot" } else { "Edit Bot" }, 560, 720);+ let (dialog, view, header) =+ header_dialog(if is_new { "New Bot" } else { "Edit Bot" }, 560, 720);let save = gtk::Button::builder().icon_name("object-select-symbolic").tooltip_text(if is_new { "Create" } else { "Save" })@@ -41,7 +54,10 @@ pub fn editor(ui: &App, bot: Option<Value>) {let page = adw::PreferencesPage::new();// Profile- let preview = gtk::Box::builder().halign(gtk::Align::Center).margin_bottom(8).build();+ let preview = gtk::Box::builder()+ .halign(gtk::Align::Center)+ .margin_bottom(8)+ .build();let redraw_preview = {let (preview, d) = (preview.clone(), d.clone());move || {@@ -49,17 +65,40 @@ pub fn editor(ui: &App, bot: Option<Value>) {preview.remove(&c);}let b = d.borrow();- preview.append(&avatar::widget(b["avatarShape"].as_str().unwrap_or("blob"), b["avatarColor"].as_str().unwrap_or("blue"), 84, true, ""));+ preview.append(&avatar::widget(+ b["avatarShape"].as_str().unwrap_or("blob"),+ b["avatarColor"].as_str().unwrap_or("blue"),+ 84,+ true,+ "",+ ));}};redraw_preview();let profile = adw::PreferencesGroup::new();profile.add(&preview);- let name = adw::EntryRow::builder().title("Name").text(d.borrow()["name"].as_str().unwrap_or("")).build();+ let name = adw::EntryRow::builder()+ .title("Name")+ .text(d.borrow()["name"].as_str().unwrap_or(""))+ .build();profile.add(&name);- let shapes = gtk::FlowBox::builder().selection_mode(gtk::SelectionMode::None).max_children_per_line(8).margin_top(8).build();+ let shapes = gtk::FlowBox::builder()+ .selection_mode(gtk::SelectionMode::None)+ .max_children_per_line(8)+ .margin_top(8)+ .build();for s in avatar::SHAPES {- let btn = gtk::Button::builder().child(&avatar::widget(s, d.borrow()["avatarColor"].as_str().unwrap_or("blue"), 30, false, "")).css_classes(["flat"]).tooltip_text(*s).build();+ let btn = gtk::Button::builder()+ .child(&avatar::widget(+ s,+ d.borrow()["avatarColor"].as_str().unwrap_or("blue"),+ 30,+ false,+ "",+ ))+ .css_classes(["flat"])+ .tooltip_text(*s)+ .build();let (d2, redraw) = (d.clone(), redraw_preview.clone());btn.connect_clicked(move |_| {d2.borrow_mut()["avatarShape"] = (*s).into();@@ -68,17 +107,33 @@ pub fn editor(ui: &App, bot: Option<Value>) {shapes.insert(&btn, -1);}profile.add(&shapes);- let colors = gtk::FlowBox::builder().selection_mode(gtk::SelectionMode::None).max_children_per_line(11).build();+ let colors = gtk::FlowBox::builder()+ .selection_mode(gtk::SelectionMode::None)+ .max_children_per_line(11)+ .build();for (cname, hex) in avatar::COLORS {- let swatch = gtk::DrawingArea::builder().content_width(22).content_height(22).build();+ let swatch = gtk::DrawingArea::builder()+ .content_width(22)+ .content_height(22)+ .build();let hex = *hex;swatch.set_draw_func(move |_, cr, w, h| {let (r, g, b) = avatar::rgb(hex);- cr.arc(w as f64 / 2.0, h as f64 / 2.0, w as f64 / 2.0, 0.0, 2.0 * std::f64::consts::PI);+ cr.arc(+ w as f64 / 2.0,+ h as f64 / 2.0,+ w as f64 / 2.0,+ 0.0,+ 2.0 * std::f64::consts::PI,+ );cr.set_source_rgb(r, g, b);cr.fill().ok();});- let btn = gtk::Button::builder().child(&swatch).css_classes(["flat", "circular"]).tooltip_text(*cname).build();+ let btn = gtk::Button::builder()+ .child(&swatch)+ .css_classes(["flat", "circular"])+ .tooltip_text(*cname)+ .build();let (d2, redraw) = (d.clone(), redraw_preview.clone());btn.connect_clicked(move |_| {d2.borrow_mut()["avatarColor"] = (*cname).into();@@ -94,17 +149,42 @@ pub fn editor(ui: &App, bot: Option<Value>) {.title("Standing instructions").description("Rules that always apply. Put task-specific requests in the chat.").build();- let instructions = gtk::TextView::builder().wrap_mode(gtk::WrapMode::WordChar).top_margin(8).bottom_margin(8).left_margin(8).right_margin(8).build();- instructions.buffer().set_text(d.borrow()["description"].as_str().unwrap_or(""));- instructions_group.add(>k::Frame::builder().child(>k::ScrolledWindow::builder().min_content_height(90).child(&instructions).build()).build());+ let instructions = gtk::TextView::builder()+ .wrap_mode(gtk::WrapMode::WordChar)+ .top_margin(8)+ .bottom_margin(8)+ .left_margin(8)+ .right_margin(8)+ .build();+ instructions+ .buffer()+ .set_text(d.borrow()["description"].as_str().unwrap_or(""));+ instructions_group.add(+ >k::Frame::builder()+ .child(+ >k::ScrolledWindow::builder()+ .min_content_height(90)+ .child(&instructions)+ .build(),+ )+ .build(),+ );page.add(&instructions_group);// Agent: installed harnesses first, then the registry, then a custom command.- let agent = adw::PreferencesGroup::builder().title("Coding agent").build();+ let agent = adw::PreferencesGroup::builder()+ .title("Coding agent")+ .build();let mut ids: Vec<String> = vec![];let names = gtk::StringList::new(&[]);for b in &backends {- let tag = if b["installed"] == true { "" } else if b["available"] == true { " — installs automatically" } else { " — needs setup" };+ let tag = if b["installed"] == true {+ ""+ } else if b["available"] == true {+ " — installs automatically"+ } else {+ " — needs setup"+ };names.append(&format!("{}{tag}", b["name"].as_str().unwrap_or("")));ids.push(b["id"].as_str().unwrap_or("").to_owned());}@@ -117,20 +197,45 @@ pub fn editor(ui: &App, bot: Option<Value>) {.enable_search(true).selected(ids.iter().position(|i| *i == current).unwrap_or(0) as u32).build();- let hint = gtk::Label::builder().wrap(true).xalign(0.0).css_classes(["small", "dim-label"]).margin_top(6).build();- let command = adw::EntryRow::builder().title("ACP command").text(d.borrow()["command"].as_str().unwrap_or("")).build();- let model = adw::EntryRow::builder().title("Model (optional)").text(d.borrow()["model"].as_str().unwrap_or("")).build();+ let hint = gtk::Label::builder()+ .wrap(true)+ .xalign(0.0)+ .css_classes(["small", "dim-label"])+ .margin_top(6)+ .build();+ let command = adw::EntryRow::builder()+ .title("ACP command")+ .text(d.borrow()["command"].as_str().unwrap_or(""))+ .build();+ let model = adw::EntryRow::builder()+ .title("Model (optional)")+ .text(d.borrow()["model"].as_str().unwrap_or(""))+ .build();agent.add(&harness);agent.add(&command);agent.add(&model);agent.add(&hint);let sync_harness = {- let (ids, backends, d, hint, command, harness) = (ids.clone(), backends.clone(), d.clone(), hint.clone(), command.clone(), harness.clone());+ let (ids, backends, d, hint, command, harness) = (+ ids.clone(),+ backends.clone(),+ d.clone(),+ hint.clone(),+ command.clone(),+ harness.clone(),+ );move || {- let id = ids.get(harness.selected() as usize).cloned().unwrap_or_default();+ let id = ids+ .get(harness.selected() as usize)+ .cloned()+ .unwrap_or_default();command.set_visible(id == "custom");let b = backends.iter().find(|b| b["id"] == id.as_str());- hint.set_label(b.filter(|b| b["installed"] != true).and_then(|b| b["installHint"].as_str()).unwrap_or(""));+ hint.set_label(+ b.filter(|b| b["installed"] != true)+ .and_then(|b| b["installHint"].as_str())+ .unwrap_or(""),+ );d.borrow_mut()["backend"] = id.into();}};@@ -139,9 +244,24 @@ pub fn editor(ui: &App, bot: Option<Value>) {page.add(&agent);// Project folder (native folder chooser: the host runs on this computer)- let project = adw::PreferencesGroup::builder().title("Project folder").build();- let folder_row = adw::ActionRow::builder().title(d.borrow()["cwd"].as_str().filter(|s| !s.is_empty()).unwrap_or("Choose a folder…")).activatable(true).build();- let choose = gtk::Button::builder().icon_name("folder-open-symbolic").tooltip_text("Choose folder").css_classes(["flat"]).valign(gtk::Align::Center).build();+ let project = adw::PreferencesGroup::builder()+ .title("Project folder")+ .build();+ let folder_row = adw::ActionRow::builder()+ .title(+ d.borrow()["cwd"]+ .as_str()+ .filter(|s| !s.is_empty())+ .unwrap_or("Choose a folder…"),+ )+ .activatable(true)+ .build();+ let choose = gtk::Button::builder()+ .icon_name("folder-open-symbolic")+ .tooltip_text("Choose folder")+ .css_classes(["flat"])+ .valign(gtk::Align::Center)+ .build();folder_row.add_suffix(&choose);project.add(&folder_row);{@@ -167,14 +287,19 @@ pub fn editor(ui: &App, bot: Option<Value>) {page.add(&project);// Permissions- let perms = adw::PreferencesGroup::builder().title("Permissions").build();+ let perms = adw::PreferencesGroup::builder()+ .title("Permissions")+ .build();let auto = adw::SwitchRow::builder().title("Approve automatically").subtitle("Otherwise you get an approval card and a notification each time the agent asks.").active(d.borrow()["permission"] == "auto").build();perms.add(&auto);- let notify = adw::SwitchRow::builder().title("Notifications").active(d.borrow()["notify"].as_bool().unwrap_or(true)).build();+ let notify = adw::SwitchRow::builder()+ .title("Notifications")+ .active(d.borrow()["notify"].as_bool().unwrap_or(true))+ .build();perms.add(¬ify);page.add(&perms);@@ -185,43 +310,66 @@ pub fn editor(ui: &App, bot: Option<Value>) {let mut body = d.borrow().clone();let buf = instructions.buffer();body["name"] = name.text().trim().into();- body["description"] = buf.text(&buf.start_iter(), &buf.end_iter(), false).trim().into();+ body["description"] = buf+ .text(&buf.start_iter(), &buf.end_iter(), false)+ .trim()+ .into();body["permission"] = if auto.is_active() { "auto" } else { "ask" }.into();body["notify"] = notify.is_active().into();let m = model.text().trim().to_owned();body["model"] = if m.is_empty() { Value::Null } else { m.into() };- body["command"] = if body["backend"] == "custom" { command.text().trim().into() } else { Value::Null };- for k in ["status", "activity", "unread", "lastMessage", "lastAt", "rev", "deleted", "startedAt"] {+ body["command"] = if body["backend"] == "custom" {+ command.text().trim().into()+ } else {+ Value::Null+ };+ for k in [+ "status",+ "activity",+ "unread",+ "lastMessage",+ "lastAt",+ "rev",+ "deleted",+ "startedAt",+ ] {body.as_object_mut().unwrap().remove(k);}btn.set_sensitive(false);let (ui3, dialog3, btn2) = (ui2.clone(), dialog2.clone(), btn.clone());- client::call(if is_new { "createBot" } else { "updateBot" }, body, move |r| match r {- Ok(v) => {- let bot = v["bot"].clone();- let id = bot["id"].as_str().unwrap_or_default().to_owned();- {- let mut st = ui3.state.borrow_mut();- st.bots.insert(id.clone(), bot);- if is_new {- st.current = Some(id);+ client::call(+ if is_new { "createBot" } else { "updateBot" },+ body,+ move |r| match r {+ Ok(v) => {+ let bot = v["bot"].clone();+ let id = bot["id"].as_str().unwrap_or_default().to_owned();+ {+ let mut st = ui3.state.borrow_mut();+ st.bots.insert(id.clone(), bot);+ if is_new {+ st.current = Some(id);+ }}+ dialog3.close();+ ui3.split.set_show_content(true);+ ui::schedule(&ui3);}- dialog3.close();- ui3.split.set_show_content(true);- ui::schedule(&ui3);- }- Err(e) => {- btn2.set_sensitive(true);- ui::toast(&ui3, &e);- }- });+ Err(e) => {+ btn2.set_sensitive(true);+ ui::toast(&ui3, &e);+ }+ },+ );});dialog.present(Some(&ui.window));}fn client_seed() -> usize {- std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos() as usize).unwrap_or(0)+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.subsec_nanos() as usize)+ .unwrap_or(0)}// MARK: trace@@ -230,7 +378,14 @@ pub fn trace(ui: &App) {let st = ui.state.borrow();let Some(id) = st.current.clone() else { return };let (dialog, view, _) = header_dialog("Full conversation", 560, 760);- let list = gtk::Box::builder().orientation(gtk::Orientation::Vertical).spacing(10).margin_start(16).margin_end(16).margin_top(12).margin_bottom(16).build();+ let list = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(10)+ .margin_start(16)+ .margin_end(16)+ .margin_top(12)+ .margin_bottom(16)+ .build();let entries = st.entries.get(&id).cloned().unwrap_or_default();let mut turn = -1i64;let mut group = adw::PreferencesGroup::new();@@ -238,41 +393,132 @@ pub fn trace(ui: &App) {let t = e["turn"].as_i64().unwrap_or(0);if t != turn {turn = t;- let title = entries.iter().find(|x| x["turn"] == t && x["kind"] == "user").and_then(|x| x["data"]["text"].as_str()).unwrap_or("");- group = adw::PreferencesGroup::builder().title(gtk::glib::markup_escape_text(&title.chars().take(80).collect::<String>())).build();+ let title = entries+ .iter()+ .find(|x| x["turn"] == t && x["kind"] == "user")+ .and_then(|x| x["data"]["text"].as_str())+ .unwrap_or("");+ group = adw::PreferencesGroup::builder()+ .title(gtk::glib::markup_escape_text(+ &title.chars().take(80).collect::<String>(),+ ))+ .build();list.append(&group);}let d = &e["data"];let widget: gtk::Widget = match e["kind"].as_str().unwrap_or("") {"tool" => {- let status = match d["status"].as_str() { Some("completed") => "✓", Some("failed") => "✕", _ => "…" };- let row = adw::ExpanderRow::builder().title(gtk::glib::markup_escape_text(d["title"].as_str().unwrap_or("Tool"))).subtitle(status).build();+ let status = match d["status"].as_str() {+ Some("completed") => "✓",+ Some("failed") => "✕",+ _ => "…",+ };+ let row = adw::ExpanderRow::builder()+ .title(gtk::glib::markup_escape_text(+ d["title"].as_str().unwrap_or("Tool"),+ ))+ .subtitle(status)+ .build();let mut body = String::new();for diff in d["diffs"].as_array().into_iter().flatten() {- body.push_str(&format!("{} +{} −{}\n{}\n", diff["path"].as_str().unwrap_or(""), diff["added"], diff["removed"], diff["patch"].as_str().unwrap_or("")));+ body.push_str(&format!(+ "{} +{} −{}\n{}\n",+ diff["path"].as_str().unwrap_or(""),+ diff["added"],+ diff["removed"],+ diff["patch"].as_str().unwrap_or("")+ ));}body.push_str(d["output"].as_str().unwrap_or(""));if !body.trim().is_empty() {- row.add_row(>k::Label::builder().label(body.trim()).xalign(0.0).wrap(true).selectable(true).css_classes(["codebox"]).margin_start(8).margin_end(8).margin_top(6).margin_bottom(6).build());+ row.add_row(+ >k::Label::builder()+ .label(body.trim())+ .xalign(0.0)+ .wrap(true)+ .selectable(true)+ .css_classes(["codebox"])+ .margin_start(8)+ .margin_end(8)+ .margin_top(6)+ .margin_bottom(6)+ .build(),+ );}row.upcast()}"thought" => {let row = adw::ExpanderRow::builder().title("Thinking").build();- row.add_row(>k::Label::builder().label(d["text"].as_str().unwrap_or("")).xalign(0.0).wrap(true).css_classes(["dim-label"]).margin_start(8).margin_end(8).margin_top(6).margin_bottom(6).build());+ row.add_row(+ >k::Label::builder()+ .label(d["text"].as_str().unwrap_or(""))+ .xalign(0.0)+ .wrap(true)+ .css_classes(["dim-label"])+ .margin_start(8)+ .margin_end(8)+ .margin_top(6)+ .margin_bottom(6)+ .build(),+ );row.upcast()}- "agent" => gtk::Label::builder().use_markup(true).label(markup::to_pango(d["text"].as_str().unwrap_or(""))).xalign(0.0).wrap(true).selectable(true).margin_start(12).margin_end(12).margin_top(8).margin_bottom(8).build().upcast(),+ "agent" => gtk::Label::builder()+ .use_markup(true)+ .label(markup::to_pango(d["text"].as_str().unwrap_or("")))+ .xalign(0.0)+ .wrap(true)+ .selectable(true)+ .margin_start(12)+ .margin_end(12)+ .margin_top(8)+ .margin_bottom(8)+ .build()+ .upcast(),"plan" => {- let text: Vec<String> = d["entries"].as_array().into_iter().flatten().map(|p| format!("{} {}", if p["status"] == "completed" { "✅" } else { "○" }, p["content"].as_str().unwrap_or(""))).collect();- adw::ActionRow::builder().title("Plan").subtitle(gtk::glib::markup_escape_text(&text.join("\n"))).build().upcast()+ let text: Vec<String> = d["entries"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|p| {+ format!(+ "{} {}",+ if p["status"] == "completed" {+ "✅"+ } else {+ "○"+ },+ p["content"].as_str().unwrap_or("")+ )+ })+ .collect();+ adw::ActionRow::builder()+ .title("Plan")+ .subtitle(gtk::glib::markup_escape_text(&text.join("\n")))+ .build()+ .upcast()}- "user" => adw::ActionRow::builder().title(gtk::glib::markup_escape_text(d["text"].as_str().unwrap_or(""))).build().upcast(),- _ => adw::ActionRow::builder().title(gtk::glib::markup_escape_text(d["title"].as_str().or(d["text"].as_str()).unwrap_or(""))).build().upcast(),+ "user" => adw::ActionRow::builder()+ .title(gtk::glib::markup_escape_text(+ d["text"].as_str().unwrap_or(""),+ ))+ .build()+ .upcast(),+ _ => adw::ActionRow::builder()+ .title(gtk::glib::markup_escape_text(+ d["title"].as_str().or(d["text"].as_str()).unwrap_or(""),+ ))+ .build()+ .upcast(),};group.add(&widget);}- view.set_content(Some(>k::ScrolledWindow::builder().child(&list).vexpand(true).build()));+ view.set_content(Some(+ >k::ScrolledWindow::builder()+ .child(&list)+ .vexpand(true)+ .build(),+ ));dialog.present(Some(&ui.window));}@@ -280,12 +526,21 @@ pub fn trace(ui: &App) {pub fn bot_menu(ui: &App) -> gtk::Popover {let pop = gtk::Popover::new();- let col = gtk::Box::builder().orientation(gtk::Orientation::Vertical).spacing(2).build();- let bot = { let st = ui.state.borrow(); st.current.as_ref().and_then(|id| st.bots.get(id)).cloned() };+ let col = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(2)+ .build();+ let bot = {+ let st = ui.state.borrow();+ st.current.as_ref().and_then(|id| st.bots.get(id)).cloned()+ };let Some(bot) = bot else { return pop };let id = bot["id"].as_str().unwrap_or_default().to_owned();let add = |label: &str, destructive: bool, f: Box<dyn Fn()>| {- let b = gtk::Button::builder().label(label).css_classes(["flat"]).build();+ let b = gtk::Button::builder()+ .label(label)+ .css_classes(["flat"])+ .build();if destructive {b.add_css_class("error");}@@ -298,30 +553,55 @@ pub fn bot_menu(ui: &App) -> gtk::Popover {};{let (ui2, bot2) = (ui.clone(), bot.clone());- add("Edit profile", false, Box::new(move || editor(&ui2, Some(bot2.clone()))));+ add(+ "Edit profile",+ false,+ Box::new(move || editor(&ui2, Some(bot2.clone()))),+ );}{let (id2, pinned) = (id.clone(), bot["pinned"].as_bool().unwrap_or(false));- add(if pinned { "Unpin" } else { "Pin" }, false, Box::new(move || client::call("updateBot", json!({"id": id2, "pinned": !pinned}), |_| {})));+ add(+ if pinned { "Unpin" } else { "Pin" },+ false,+ Box::new(move || {+ client::call("updateBot", json!({"id": id2, "pinned": !pinned}), |_| {})+ }),+ );}{let id2 = id.clone();- add("New session", false, Box::new(move || client::call("newSession", json!({"botId": id2}), |_| {})));+ add(+ "New session",+ false,+ Box::new(move || client::call("newSession", json!({"botId": id2}), |_| {})),+ );}{- let (ui2, id2, name) = (ui.clone(), id.clone(), bot["name"].as_str().unwrap_or("").to_owned());- add("Delete bot…", true, Box::new(move || {- let alert = adw::AlertDialog::new(Some(&format!("Delete {name}?")), Some("The conversation is removed. Files it changed stay as they are."));- alert.add_responses(&[("cancel", "Cancel"), ("delete", "Delete")]);- alert.set_response_appearance("delete", adw::ResponseAppearance::Destructive);- let id3 = id2.clone();- alert.connect_response(None, move |_, r| {- if r == "delete" {- client::call("deleteBot", json!({"botId": id3}), |_| {});- }- });- alert.present(Some(&ui2.window));- }));+ let (ui2, id2, name) = (+ ui.clone(),+ id.clone(),+ bot["name"].as_str().unwrap_or("").to_owned(),+ );+ add(+ "Delete bot…",+ true,+ Box::new(move || {+ let alert = adw::AlertDialog::new(+ Some(&format!("Delete {name}?")),+ Some("The conversation is removed. Files it changed stay as they are."),+ );+ alert.add_responses(&[("cancel", "Cancel"), ("delete", "Delete")]);+ alert.set_response_appearance("delete", adw::ResponseAppearance::Destructive);+ let id3 = id2.clone();+ alert.connect_response(None, move |_, r| {+ if r == "delete" {+ client::call("deleteBot", json!({"botId": id3}), |_| {});+ }+ });+ alert.present(Some(&ui2.window));+ }),+ );}pop.set_child(Some(&col));pop@@ -332,10 +612,24 @@ pub fn bot_menu(ui: &App) -> gtk::Popover {pub fn settings(ui: &App) {let (dialog, view, _) = header_dialog("Settings", 520, 720);let page = adw::PreferencesPage::new();- let pair = adw::PreferencesGroup::builder().title("Pair your iPhone").description("Scan with the Codync app or the iPhone Camera.").build();- let qr_area = gtk::DrawingArea::builder().content_width(220).content_height(220).halign(gtk::Align::Center).margin_top(8).build();+ let pair = adw::PreferencesGroup::builder()+ .title("Pair your iPhone")+ .description("Scan with the Codync app or the iPhone Camera.")+ .build();+ let qr_area = gtk::DrawingArea::builder()+ .content_width(220)+ .content_height(220)+ .halign(gtk::Align::Center)+ .margin_top(8)+ .build();pair.add(&qr_area);- let copy = gtk::Button::builder().icon_name("edit-copy-symbolic").tooltip_text("Copy pairing link").css_classes(["flat", "circular"]).halign(gtk::Align::Center).margin_top(8).build();+ let copy = gtk::Button::builder()+ .icon_name("edit-copy-symbolic")+ .tooltip_text("Copy pairing link")+ .css_classes(["flat", "circular"])+ .halign(gtk::Align::Center)+ .margin_top(8)+ .build();pair.add(©);page.add(&pair);client::call("pairing", client::empty(), move |r| {@@ -344,7 +638,11 @@ pub fn settings(ui: &App) {&& let Ok(code) = qrcode::QrCode::new(url.as_bytes()){let width = code.width();- let dark: Vec<bool> = code.to_colors().iter().map(|c| *c == qrcode::Color::Dark).collect();+ let dark: Vec<bool> = code+ .to_colors()+ .iter()+ .map(|c| *c == qrcode::Color::Dark)+ .collect();qr_area.set_draw_func(move |_, cr, w, _| {let cell = w as f64 / (width + 4) as f64;cr.set_source_rgb(1.0, 1.0, 1.0);@@ -352,7 +650,12 @@ pub fn settings(ui: &App) {cr.set_source_rgb(0.0, 0.0, 0.0);for (i, on) in dark.iter().enumerate() {if *on {- cr.rectangle(((i % width) + 2) as f64 * cell, ((i / width) + 2) as f64 * cell, cell, cell);+ cr.rectangle(+ ((i % width) + 2) as f64 * cell,+ ((i / width) + 2) as f64 * cell,+ cell,+ cell,+ );}}cr.fill().ok();@@ -364,11 +667,29 @@ pub fn settings(ui: &App) {});let st = ui.state.borrow();- let agents = adw::PreferencesGroup::builder().title("Coding agents on this computer").build();- for b in st.hello["backends"].as_array().into_iter().flatten().filter(|b| b["installed"] == true) {- agents.add(&adw::ActionRow::builder().title(b["name"].as_str().unwrap_or("")).subtitle(gtk::glib::markup_escape_text(b["path"].as_str().unwrap_or(""))).build());+ let agents = adw::PreferencesGroup::builder()+ .title("Coding agents on this computer")+ .build();+ for b in st.hello["backends"]+ .as_array()+ .into_iter()+ .flatten()+ .filter(|b| b["installed"] == true)+ {+ agents.add(+ &adw::ActionRow::builder()+ .title(b["name"].as_str().unwrap_or(""))+ .subtitle(gtk::glib::markup_escape_text(+ b["path"].as_str().unwrap_or(""),+ ))+ .build(),+ );}- let rescan = gtk::Button::builder().icon_name("view-refresh-symbolic").tooltip_text("Re-scan this computer").css_classes(["flat"]).build();+ let rescan = gtk::Button::builder()+ .icon_name("view-refresh-symbolic")+ .tooltip_text("Re-scan this computer")+ .css_classes(["flat"])+ .build();agents.set_header_suffix(Some(&rescan));{let (ui2, dialog2) = (ui.clone(), dialog.clone());@@ -385,23 +706,50 @@ pub fn settings(ui: &App) {}page.add(&agents);- let usage = adw::PreferencesGroup::builder().title("Usage limits").build();+ let usage = adw::PreferencesGroup::builder()+ .title("Usage limits")+ .build();for p in st.usage["providers"].as_array().into_iter().flatten() {for w in p["windows"].as_array().into_iter().flatten() {- let reset = w["resetsText"].as_str().map(|s| format!("resets {s}")).unwrap_or_default();+ let reset = w["resetsText"]+ .as_str()+ .map(|s| format!("resets {s}"))+ .unwrap_or_default();let row = adw::ActionRow::builder()- .title(format!("{} {}", p["name"].as_str().unwrap_or(""), w["label"].as_str().unwrap_or("")))+ .title(format!(+ "{} {}",+ p["name"].as_str().unwrap_or(""),+ w["label"].as_str().unwrap_or("")+ )).subtitle(gtk::glib::markup_escape_text(&reset)).build();- let bar = gtk::LevelBar::builder().min_value(0.0).max_value(100.0).value(w["percent"].as_f64().unwrap_or(0.0)).width_request(120).valign(gtk::Align::Center).build();+ let bar = gtk::LevelBar::builder()+ .min_value(0.0)+ .max_value(100.0)+ .value(w["percent"].as_f64().unwrap_or(0.0))+ .width_request(120)+ .valign(gtk::Align::Center)+ .build();row.add_suffix(&bar);- row.add_suffix(>k::Label::new(Some(&format!("{:.0}%", w["percent"].as_f64().unwrap_or(0.0)))));+ row.add_suffix(>k::Label::new(Some(&format!(+ "{:.0}%",+ w["percent"].as_f64().unwrap_or(0.0)+ ))));usage.add(&row);}}page.add(&usage);let about = adw::PreferencesGroup::new();- about.add(&adw::ActionRow::builder().title("codync-host").subtitle(format!("{} · {}", st.hello["version"].as_str().unwrap_or(""), st.hello["os"].as_str().unwrap_or(""))).build());+ about.add(+ &adw::ActionRow::builder()+ .title("codync-host")+ .subtitle(format!(+ "{} · {}",+ st.hello["version"].as_str().unwrap_or(""),+ st.hello["os"].as_str().unwrap_or("")+ ))+ .build(),+ );page.add(&about);view.set_content(Some(&page));dialog.present(Some(&ui.window));@@ -411,10 +759,16 @@ pub fn settings(ui: &App) {pub fn host_missing(ui: &App) {let status = adw::StatusPage::builder().title("Start the Codync host")- .description("Codync runs your coding agents through a small background service on this computer.")+ .description(+ "Codync runs your coding agents through a small background service on this computer.",+ ).icon_name("computer-symbolic").build();- let btn = gtk::Button::builder().label("Install & start host").css_classes(["pill", "accent-fill"]).halign(gtk::Align::Center).build();+ let btn = gtk::Button::builder()+ .label("Install & start host")+ .css_classes(["pill", "accent-fill"])+ .halign(gtk::Align::Center)+ .build();status.set_child(Some(&btn));let (dialog, view, _) = header_dialog("Codync", 460, 420);view.set_content(Some(&status));diff --git a/linux/src/main.rs b/linux/src/main.rsindex 13330418..5e1520dd 100644--- a/linux/src/main.rs+++ b/linux/src/main.rs@@ -4,6 +4,7 @@ mod avatar;mod client;mod dialogs;mod markup;+mod rows;mod ui;use adw::prelude::*;diff --git a/linux/src/markup.rs b/linux/src/markup.rsindex b71b2e3b..1c3f246b 100644--- a/linux/src/markup.rs+++ b/linux/src/markup.rs@@ -22,7 +22,11 @@ fn inline(line: &str) -> String {fn emphasis(s: &str) -> String {let mut out = String::new();for (i, part) in s.split("**").enumerate() {- if i % 2 == 1 { out.push_str(&format!("<b>{part}</b>")) } else { out.push_str(&links(part)) }+ if i % 2 == 1 {+ out.push_str(&format!("<b>{part}</b>"))+ } else {+ out.push_str(&links(part))+ }}out}@@ -32,8 +36,12 @@ fn links(s: &str) -> String {let mut out = String::new();let mut rest = s;while let Some(open) = rest.find('[') {- let Some(close) = rest[open..].find("](").map(|i| open + i) else { break };- let Some(end) = rest[close..].find(')').map(|i| close + i) else { break };+ let Some(close) = rest[open..].find("](").map(|i| open + i) else {+ break;+ };+ let Some(end) = rest[close..].find(')').map(|i| close + i) else {+ break;+ };let url = &rest[close + 2..end];if !url.starts_with("http") {break;@@ -57,7 +65,11 @@ pub fn to_pango(src: &str) -> String {}if in_code {out.push(format!("<tt>{}</tt>", markup_escape_text(line)));- } else if let Some(h) = t.strip_prefix("### ").or_else(|| t.strip_prefix("## ")).or_else(|| t.strip_prefix("# ")) {+ } else if let Some(h) = t+ .strip_prefix("### ")+ .or_else(|| t.strip_prefix("## "))+ .or_else(|| t.strip_prefix("# "))+ {out.push(format!("<b>{}</b>", inline(h)));} else if let Some(item) = t.strip_prefix("- ").or_else(|| t.strip_prefix("* ")) {out.push(format!(" • {}", inline(item)));@@ -73,7 +85,13 @@ mod tests {#[test]fn converts_common_markdown() {assert_eq!(super::to_pango("**hi** `a<b`"), "<b>hi</b> <tt>a<b</tt>");- assert_eq!(super::to_pango("- x\n```\nfn()\n```"), " • x\n<tt>fn()</tt>");- assert_eq!(super::to_pango("[doc](https://a.b)"), "<a href=\"https://a.b\">doc</a>");+ assert_eq!(+ super::to_pango("- x\n```\nfn()\n```"),+ " • x\n<tt>fn()</tt>"+ );+ assert_eq!(+ super::to_pango("[doc](https://a.b)"),+ "<a href=\"https://a.b\">doc</a>"+ );}}diff --git a/linux/src/rows.rs b/linux/src/rows.rsnew file mode 100644index 00000000..779b0c41--- /dev/null+++ b/linux/src/rows.rs@@ -0,0 +1,243 @@+//! The rows a conversation is made of: bubbles, notices and approval cards.++use crate::client;+use crate::ui::{App, State, folder, toast};+use crate::{avatar, markup};+use adw::prelude::*;+use serde_json::{Value, json};++pub fn user_bubble(e: &Value, bot_working: bool, start: bool) -> gtk::Widget {+ let col = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .halign(gtk::Align::End)+ .margin_start(60)+ .margin_top(if start { 12 } else { 2 })+ .build();+ col.append(+ >k::Label::builder()+ .label(e["data"]["text"].as_str().unwrap_or(""))+ .wrap(true)+ .wrap_mode(gtk::pango::WrapMode::WordChar)+ .selectable(true)+ .xalign(0.0)+ .css_classes(["bubble", "bubble-user"])+ .build(),+ );+ let status = match e["data"]["status"].as_str() {+ Some("sending") => "Sending…",+ Some("queued") if bot_working => "Waiting to send — it'll read this when it's done",+ Some("failed") => "Failed to send",+ Some("cancelled") => "Not sent — stopped",+ _ => "",+ };+ if !status.is_empty() {+ col.append(+ >k::Label::builder()+ .label(status)+ .css_classes(["small", "muted"])+ .halign(gtk::Align::End)+ .build(),+ );+ }+ col.upcast()+}++pub fn agent_bubble(e: &Value, bot: &Value, start: bool) -> gtk::Widget {+ let row = gtk::Box::builder()+ .spacing(8)+ .margin_end(60)+ .margin_top(if start { 12 } else { 2 })+ .build();+ if start {+ row.append(&avatar::widget(+ bot["avatarShape"].as_str().unwrap_or("blob"),+ bot["avatarColor"].as_str().unwrap_or("blue"),+ 28,+ false,+ "",+ ));+ } else {+ row.append(>k::Box::builder().width_request(28).build());+ }+ let label = gtk::Label::builder()+ .use_markup(true)+ .label(markup::to_pango(e["data"]["text"].as_str().unwrap_or("")))+ .wrap(true)+ .wrap_mode(gtk::pango::WrapMode::WordChar)+ .selectable(true)+ .xalign(0.0)+ .css_classes(["bubble", "bubble-agent"])+ .valign(gtk::Align::End)+ .build();+ row.append(&label);+ row.upcast()+}++pub fn notice(e: &Value) -> gtk::Widget {+ let text = e["data"]["text"].as_str().unwrap_or("");+ let label = gtk::Label::builder()+ .label(text)+ .wrap(true)+ .selectable(true)+ .margin_top(10)+ .build();+ match e["data"]["style"].as_str() {+ Some("error") => {+ label.add_css_class("notice-error");+ label.set_xalign(0.0);+ }+ _ => label.add_css_class("dim-label"),+ }+ label.upcast()+}++pub fn permission_card(ui: &App, st: &State, e: &Value) -> gtk::Widget {+ let d = &e["data"];+ let pending = d["status"] == "pending";+ let card = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(6)+ .css_classes(["card"])+ .margin_start(36)+ .margin_top(12)+ .build();+ if pending {+ card.add_css_class("pending");+ }+ let headline = match d["toolKind"].as_str() {+ Some("execute") => "Wants to run a command",+ Some("edit" | "delete" | "move") => "Wants to change files",+ Some("fetch") => "Wants to access the web",+ Some("read" | "search") => "Wants to read files",+ _ => "Wants to use a tool",+ };+ card.append(+ >k::Label::builder()+ .label(format!("✋ {headline}"))+ .xalign(0.0)+ .css_classes(["heading"])+ .build(),+ );+ card.append(+ >k::Label::builder()+ .label(d["title"].as_str().unwrap_or(""))+ .xalign(0.0)+ .wrap(true)+ .build(),+ );+ let host = st.hello["name"].as_str().unwrap_or("this computer");+ card.append(+ >k::Label::builder()+ .label(format!(+ "Runs on {host} · {}",+ folder(d["cwd"].as_str().unwrap_or(""))+ ))+ .xalign(0.0)+ .css_classes(["small", "muted"])+ .build(),+ );+ let mut detail = String::new();+ if let Some(c) = d["command"].as_str() {+ detail.push_str(c);+ }+ for diff in d["diffs"].as_array().into_iter().flatten() {+ detail.push_str(&format!(+ "\n{} +{} −{}\n{}",+ diff["path"].as_str().unwrap_or(""),+ diff["added"],+ diff["removed"],+ diff["patch"].as_str().unwrap_or("")+ ));+ }+ if !detail.trim().is_empty() {+ let exp = gtk::Expander::new(Some("Details"));+ exp.set_child(Some(+ >k::Label::builder()+ .label(detail.trim())+ .xalign(0.0)+ .selectable(true)+ .wrap(true)+ .css_classes(["codebox"])+ .build(),+ ));+ card.append(&exp);+ }+ if pending {+ let buttons = gtk::FlowBox::builder()+ .selection_mode(gtk::SelectionMode::None)+ .max_children_per_line(4)+ .column_spacing(8)+ .row_spacing(8)+ .homogeneous(true)+ .build();+ let mut opts: Vec<&Value> = d["options"].as_array().into_iter().flatten().collect();+ let rank = |k: &str| match k {+ "allow_once" => 0,+ "allow_always" => 1,+ "reject_once" => 2,+ _ => 3,+ };+ opts.sort_by_key(|o| rank(o["kind"].as_str().unwrap_or("")));+ for o in opts {+ let kind = o["kind"].as_str().unwrap_or("");+ let label = match kind {+ "allow_once" => "Allow once",+ "allow_always" => "Always allow",+ "reject_once" => "Deny",+ "reject_always" => "Never",+ _ => o["name"].as_str().unwrap_or("OK"),+ };+ let btn = gtk::Button::with_label(label);+ if kind == "allow_once" {+ btn.add_css_class("accent-fill");+ } else if kind.starts_with("reject") {+ btn.add_css_class("destructive-action");+ }+ let (entry_id, opt) = (+ e["id"].as_str().unwrap_or("").to_owned(),+ o["optionId"].clone(),+ );+ let ui2 = ui.clone();+ btn.connect_clicked(move |b| {+ b.set_sensitive(false);+ let ui3 = ui2.clone();+ client::call(+ "respondPermission",+ json!({"entryId": entry_id, "optionId": opt}),+ move |r| {+ if let Err(e) = r {+ toast(&ui3, &e);+ }+ },+ );+ });+ buttons.insert(&btn, -1);+ }+ card.append(&buttons);+ } else {+ let chosen = d["options"]+ .as_array()+ .into_iter()+ .flatten()+ .find(|o| o["optionId"] == d["selected"]);+ let outcome = match (+ d["status"].as_str(),+ chosen.and_then(|o| o["kind"].as_str()),+ ) {+ (Some("answered"), Some("allow_once")) => "Allowed once",+ (Some("answered"), Some("allow_always")) => "Always allowed",+ (Some("answered"), Some("reject_once")) => "Denied",+ (Some("answered"), _) => "Answered",+ (Some("cancelled"), _) => "Cancelled",+ _ => "Expired — the agent moved on",+ };+ card.append(+ >k::Label::builder()+ .label(outcome)+ .xalign(0.0)+ .css_classes(["small", "dim-label"])+ .build(),+ );+ }+ card.upcast()+}diff --git a/linux/src/ui.rs b/linux/src/ui.rsindex 4b598de6..282367f7 100644--- a/linux/src/ui.rs+++ b/linux/src/ui.rs@@ -1,7 +1,8 @@//! Main window: roster sidebar + conversation (Grok Bot's desktop layout).use crate::client::{self, Event};-use crate::{avatar, dialogs, markup};+use crate::rows::{agent_bubble, notice, permission_card, user_bubble};+use crate::{avatar, dialogs};use adw::prelude::*;use serde_json::{Value, json};use std::cell::RefCell;@@ -44,16 +45,37 @@ pub type App = Rc<Ui>;pub fn build(app: &adw::Application) {// Sidebar- let roster = gtk::ListBox::builder().css_classes(["navigation-sidebar"]).build();- let usage_box = gtk::Box::builder().spacing(6).margin_start(12).margin_end(12).margin_bottom(6).build();- let usage_scroll = gtk::ScrolledWindow::builder().vscrollbar_policy(gtk::PolicyType::Never).child(&usage_box).build();+ let roster = gtk::ListBox::builder()+ .css_classes(["navigation-sidebar"])+ .build();+ let usage_box = gtk::Box::builder()+ .spacing(6)+ .margin_start(12)+ .margin_end(12)+ .margin_bottom(6)+ .build();+ let usage_scroll = gtk::ScrolledWindow::builder()+ .vscrollbar_policy(gtk::PolicyType::Never)+ .child(&usage_box)+ .build();let banner = adw::Banner::new("Reconnecting to the Codync host…");let sidebar_box = gtk::Box::new(gtk::Orientation::Vertical, 0);sidebar_box.append(&banner);sidebar_box.append(&usage_scroll);- sidebar_box.append(>k::ScrolledWindow::builder().vexpand(true).child(&roster).build());- let new_btn = gtk::Button::builder().icon_name("document-edit-symbolic").tooltip_text("New bot").build();- let settings_btn = gtk::Button::builder().icon_name("emblem-system-symbolic").tooltip_text("Settings & pairing").build();+ sidebar_box.append(+ >k::ScrolledWindow::builder()+ .vexpand(true)+ .child(&roster)+ .build(),+ );+ let new_btn = gtk::Button::builder()+ .icon_name("document-edit-symbolic")+ .tooltip_text("New bot")+ .build();+ let settings_btn = gtk::Button::builder()+ .icon_name("emblem-system-symbolic")+ .tooltip_text("Settings & pairing")+ .build();let side_header = adw::HeaderBar::new();side_header.pack_start(&settings_btn);side_header.pack_end(&new_btn);@@ -68,8 +90,14 @@ pub fn build(app: &adw::Application) {let head = gtk::Box::builder().spacing(8).build();head.append(&head_avatar);head.append(&title);- let trace_btn = gtk::Button::builder().icon_name("view-list-symbolic").tooltip_text("Full conversation").build();- let menu_btn = gtk::MenuButton::builder().icon_name("view-more-symbolic").tooltip_text("More").build();+ let trace_btn = gtk::Button::builder()+ .icon_name("view-list-symbolic")+ .tooltip_text("Full conversation")+ .build();+ let menu_btn = gtk::MenuButton::builder()+ .icon_name("view-more-symbolic")+ .tooltip_text("More")+ .build();let content_header = adw::HeaderBar::builder().title_widget(&head).build();content_header.pack_end(&menu_btn);content_header.pack_end(&trace_btn);@@ -81,9 +109,21 @@ pub fn build(app: &adw::Application) {.margin_top(12).margin_bottom(12).build();- let clamp = adw::Clamp::builder().maximum_size(760).child(&thread).build();- let scroller = gtk::ScrolledWindow::builder().vexpand(true).child(&clamp).build();- let composer = gtk::TextView::builder().wrap_mode(gtk::WrapMode::WordChar).accepts_tab(false).hexpand(true).top_margin(4).bottom_margin(4).build();+ let clamp = adw::Clamp::builder()+ .maximum_size(760)+ .child(&thread)+ .build();+ let scroller = gtk::ScrolledWindow::builder()+ .vexpand(true)+ .child(&clamp)+ .build();+ let composer = gtk::TextView::builder()+ .wrap_mode(gtk::WrapMode::WordChar)+ .accepts_tab(false)+ .hexpand(true)+ .top_margin(4)+ .bottom_margin(4)+ .build();let composer_frame = gtk::ScrolledWindow::builder().child(&composer).max_content_height(160)@@ -92,9 +132,25 @@ pub fn build(app: &adw::Application) {.css_classes(["composer"]).hexpand(true).build();- let send_btn = gtk::Button::builder().icon_name("go-up-symbolic").tooltip_text("Send").css_classes(["round", "accent-fill"]).valign(gtk::Align::End).build();- let stop_btn = gtk::Button::builder().icon_name("media-playback-stop-symbolic").tooltip_text("Stop").css_classes(["round"]).valign(gtk::Align::End).build();- let composer_row = gtk::Box::builder().spacing(8).margin_start(12).margin_end(12).margin_top(8).margin_bottom(12).build();+ let send_btn = gtk::Button::builder()+ .icon_name("go-up-symbolic")+ .tooltip_text("Send")+ .css_classes(["round", "accent-fill"])+ .valign(gtk::Align::End)+ .build();+ let stop_btn = gtk::Button::builder()+ .icon_name("media-playback-stop-symbolic")+ .tooltip_text("Stop")+ .css_classes(["round"])+ .valign(gtk::Align::End)+ .build();+ let composer_row = gtk::Box::builder()+ .spacing(8)+ .margin_start(12)+ .margin_end(12)+ .margin_top(8)+ .margin_bottom(12)+ .build();composer_row.append(&composer_frame);composer_row.append(&stop_btn);composer_row.append(&send_btn);@@ -115,11 +171,25 @@ pub fn build(app: &adw::Application) {content_view.set_content(Some(&content_stack));let content_page = adw::NavigationPage::new(&content_view, "Chat");- let split = adw::NavigationSplitView::builder().sidebar(&sidebar_page).content(&content_page).min_sidebar_width(260.0).build();+ let split = adw::NavigationSplitView::builder()+ .sidebar(&sidebar_page)+ .content(&content_page)+ .min_sidebar_width(260.0)+ .build();let toasts = adw::ToastOverlay::new();toasts.set_child(Some(&split));- let window = adw::ApplicationWindow::builder().application(app).title("Codync").default_width(1100).default_height(760).content(&toasts).build();- let bp = adw::Breakpoint::new(adw::BreakpointCondition::new_length(adw::BreakpointConditionLengthType::MaxWidth, 640.0, adw::LengthUnit::Sp));+ let window = adw::ApplicationWindow::builder()+ .application(app)+ .title("Codync")+ .default_width(1100)+ .default_height(760)+ .content(&toasts)+ .build();+ let bp = adw::Breakpoint::new(adw::BreakpointCondition::new_length(+ adw::BreakpointConditionLengthType::MaxWidth,+ 640.0,+ adw::LengthUnit::Sp,+ ));bp.add_setter(&split, "collapsed", Some(&true.to_value()));window.add_breakpoint(bp);@@ -186,7 +256,9 @@ pub fn build(app: &adw::Application) {let ui2 = ui.clone();let keys = gtk::EventControllerKey::new();keys.connect_key_pressed(move |_, key, _, mods| {- if (key == gtk::gdk::Key::Return || key == gtk::gdk::Key::KP_Enter) && !mods.contains(gtk::gdk::ModifierType::SHIFT_MASK) {+ if (key == gtk::gdk::Key::Return || key == gtk::gdk::Key::KP_Enter)+ && !mods.contains(gtk::gdk::ModifierType::SHIFT_MASK)+ {send(&ui2);return gtk::glib::Propagation::Stop;}@@ -196,7 +268,9 @@ pub fn build(app: &adw::Application) {}{let ui2 = ui.clone();- ui.composer.buffer().connect_changed(move |_| update_composer(&ui2));+ ui.composer+ .buffer()+ .connect_changed(move |_| update_composer(&ui2));}// Keep relative times fresh.{@@ -284,8 +358,17 @@ fn notify(ui: &App, old: &Value, new: &Value) {}let name = new["name"].as_str().unwrap_or("Bot");let (title, body) = match (old["status"].as_str(), new["status"].as_str()) {- (Some(o), Some("needsInput")) if o != "needsInput" => (format!("{name} needs you"), new["activity"].as_str().unwrap_or("").to_owned()),- (Some("working" | "needsInput"), Some("idle")) => (name.to_owned(), new["lastMessage"].as_str().unwrap_or("Finished.").to_owned()),+ (Some(o), Some("needsInput")) if o != "needsInput" => (+ format!("{name} needs you"),+ new["activity"].as_str().unwrap_or("").to_owned(),+ ),+ (Some("working" | "needsInput"), Some("idle")) => (+ name.to_owned(),+ new["lastMessage"]+ .as_str()+ .unwrap_or("Finished.")+ .to_owned(),+ ),_ => return,};let n = gtk::gio::Notification::new(&title);@@ -337,7 +420,7 @@ pub fn render(ui: &App) {render_thread(ui);}-fn working(b: &Value) -> bool {+pub fn working(b: &Value) -> bool {matches!(b["status"].as_str(), Some("working" | "needsInput"))}@@ -350,12 +433,18 @@ pub fn backend_name(st: &State, id: &str) -> String {.to_owned()}-fn folder(p: &str) -> String {- std::path::Path::new(p).file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| p.to_owned())+pub fn folder(p: &str) -> String {+ std::path::Path::new(p)+ .file_name()+ .map(|s| s.to_string_lossy().into_owned())+ .unwrap_or_else(|| p.to_owned())}pub fn ago(ms: i64) -> String {- let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as i64;+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_millis() as i64;let s = ((now - ms) / 1000).max(0);match s {0..60 => "now".into(),@@ -373,9 +462,26 @@ fn render_usage(ui: &App) {for p in st.usage["providers"].as_array().into_iter().flatten() {for w in p["windows"].as_array().into_iter().flatten().take(2) {let pct = w["percent"].as_f64().unwrap_or(0.0);- let chip = gtk::Box::builder().orientation(gtk::Orientation::Vertical).css_classes(["chip"]).build();- chip.append(>k::Label::builder().label(format!("{} {}", p["name"].as_str().unwrap_or(""), w["label"].as_str().unwrap_or(""))).css_classes(["small", "muted"]).xalign(0.0).build());- let value = gtk::Label::builder().label(format!("{pct:.0}%")).xalign(0.0).css_classes(["heading"]).build();+ let chip = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .css_classes(["chip"])+ .build();+ chip.append(+ >k::Label::builder()+ .label(format!(+ "{} {}",+ p["name"].as_str().unwrap_or(""),+ w["label"].as_str().unwrap_or("")+ ))+ .css_classes(["small", "muted"])+ .xalign(0.0)+ .build(),+ );+ let value = gtk::Label::builder()+ .label(format!("{pct:.0}%"))+ .xalign(0.0)+ .css_classes(["heading"])+ .build();if pct >= 90.0 {value.add_css_class("error");} else if pct >= 70.0 {@@ -389,36 +495,119 @@ fn render_usage(ui: &App) {fn render_roster(ui: &App) {let st = ui.state.borrow();- let mut bots: Vec<&Value> = st.bots.values().filter(|b| !b["hidden"].as_bool().unwrap_or(false)).collect();- bots.sort_by_key(|b| (!b["pinned"].as_bool().unwrap_or(false), -b["lastAt"].as_i64().unwrap_or(0)));+ let mut bots: Vec<&Value> = st+ .bots+ .values()+ .filter(|b| !b["hidden"].as_bool().unwrap_or(false))+ .collect();+ bots.sort_by_key(|b| {+ (+ !b["pinned"].as_bool().unwrap_or(false),+ -b["lastAt"].as_i64().unwrap_or(0),+ )+ });while let Some(c) = ui.roster.first_child() {ui.roster.remove(&c);}for b in bots {let id = b["id"].as_str().unwrap_or_default();let unread = b["unread"].as_i64().unwrap_or(0);- let status = if b["status"] == "needsInput" { "needs" } else if unread > 0 { "unread" } else { "" };- let row_box = gtk::Box::builder().spacing(10).margin_top(6).margin_bottom(6).build();- row_box.append(&avatar::widget(b["avatarShape"].as_str().unwrap_or("blob"), b["avatarColor"].as_str().unwrap_or("blue"), 40, working(b), status));- let text = gtk::Box::builder().orientation(gtk::Orientation::Vertical).hexpand(true).build();+ let status = if b["status"] == "needsInput" {+ "needs"+ } else if unread > 0 {+ "unread"+ } else {+ ""+ };+ let row_box = gtk::Box::builder()+ .spacing(10)+ .margin_top(6)+ .margin_bottom(6)+ .build();+ row_box.append(&avatar::widget(+ b["avatarShape"].as_str().unwrap_or("blob"),+ b["avatarColor"].as_str().unwrap_or("blue"),+ 40,+ working(b),+ status,+ ));+ let text = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .hexpand(true)+ .build();let top = gtk::Box::builder().spacing(6).build();- top.append(>k::Label::builder().label(b["name"].as_str().unwrap_or("")).xalign(0.0).hexpand(true).ellipsize(gtk::pango::EllipsizeMode::End).css_classes(["heading"]).build());- let time = gtk::Label::builder().label(ago(b["lastAt"].as_i64().unwrap_or(0))).css_classes(["small", "muted"]).build();+ top.append(+ >k::Label::builder()+ .label(b["name"].as_str().unwrap_or(""))+ .xalign(0.0)+ .hexpand(true)+ .ellipsize(gtk::pango::EllipsizeMode::End)+ .css_classes(["heading"])+ .build(),+ );+ let time = gtk::Label::builder()+ .label(ago(b["lastAt"].as_i64().unwrap_or(0)))+ .css_classes(["small", "muted"])+ .build();top.append(&time);text.append(&top);let (preview, class) = match b["status"].as_str() {- Some("needsInput") => (format!("✋ {}", b["activity"].as_str().filter(|s| !s.is_empty()).unwrap_or("Needs your approval")), "needs-text"),- Some("working") => (b["activity"].as_str().filter(|s| !s.is_empty()).unwrap_or("Working…").to_owned(), "accent-text"),- Some("error") => (b["lastMessage"].as_str().unwrap_or("Something went wrong").to_owned(), "error"),+ Some("needsInput") => (+ format!(+ "✋ {}",+ b["activity"]+ .as_str()+ .filter(|s| !s.is_empty())+ .unwrap_or("Needs your approval")+ ),+ "needs-text",+ ),+ Some("working") => (+ b["activity"]+ .as_str()+ .filter(|s| !s.is_empty())+ .unwrap_or("Working…")+ .to_owned(),+ "accent-text",+ ),+ Some("error") => (+ b["lastMessage"]+ .as_str()+ .unwrap_or("Something went wrong")+ .to_owned(),+ "error",+ ),_ => (- b["lastMessage"].as_str().map(str::to_owned).unwrap_or_else(|| format!("{} · {}", backend_name(&st, b["backend"].as_str().unwrap_or("")), folder(b["cwd"].as_str().unwrap_or("")))),+ b["lastMessage"]+ .as_str()+ .map(str::to_owned)+ .unwrap_or_else(|| {+ format!(+ "{} · {}",+ backend_name(&st, b["backend"].as_str().unwrap_or("")),+ folder(b["cwd"].as_str().unwrap_or(""))+ )+ }),"dim-label",),};let bottom = gtk::Box::builder().spacing(6).build();- bottom.append(>k::Label::builder().label(preview.replace('\n', " ")).xalign(0.0).hexpand(true).ellipsize(gtk::pango::EllipsizeMode::End).css_classes([class]).build());+ bottom.append(+ >k::Label::builder()+ .label(preview.replace('\n', " "))+ .xalign(0.0)+ .hexpand(true)+ .ellipsize(gtk::pango::EllipsizeMode::End)+ .css_classes([class])+ .build(),+ );if unread > 0 {- bottom.append(>k::Label::builder().label(unread.to_string()).css_classes(["badge"]).build());+ bottom.append(+ >k::Label::builder()+ .label(unread.to_string())+ .css_classes(["badge"])+ .build(),+ );}text.append(&bottom);row_box.append(&text);@@ -449,7 +638,10 @@ fn render_thread(ui: &App) {};ui.content_stack.set_visible_child_name("chat");ui.chat_buttons.iter().for_each(|b| b.set_visible(true));- let switched = ui.shown_bot.replace(bot["id"].as_str().unwrap_or_default().to_owned()) != bot["id"].as_str().unwrap_or_default();+ let switched = ui+ .shown_bot+ .replace(bot["id"].as_str().unwrap_or_default().to_owned())+ != bot["id"].as_str().unwrap_or_default();let near_bottom = switched || {let adj = ui.scroller.vadjustment();adj.upper() - adj.value() - adj.page_size() < 120.0@@ -458,22 +650,41 @@ fn render_thread(ui: &App) {let sub = match bot["status"].as_str() {Some("needsInput") => "Needs you".to_owned(),Some("working") => "Working".to_owned(),- _ => format!("{} · {}", backend_name(&st, bot["backend"].as_str().unwrap_or("")), folder(bot["cwd"].as_str().unwrap_or(""))),+ _ => format!(+ "{} · {}",+ backend_name(&st, bot["backend"].as_str().unwrap_or("")),+ folder(bot["cwd"].as_str().unwrap_or(""))+ ),};ui.title.set_subtitle(&sub);while let Some(c) = ui.head_avatar.first_child() {ui.head_avatar.remove(&c);}- ui.head_avatar.append(&avatar::widget(bot["avatarShape"].as_str().unwrap_or("blob"), bot["avatarColor"].as_str().unwrap_or("blue"), 28, working(bot), ""));+ ui.head_avatar.append(&avatar::widget(+ bot["avatarShape"].as_str().unwrap_or("blob"),+ bot["avatarColor"].as_str().unwrap_or("blue"),+ 28,+ working(bot),+ "",+ ));while let Some(c) = ui.thread.first_child() {ui.thread.remove(&c);}- let entries: Vec<&Value> = st.entries.get(bot["id"].as_str().unwrap_or_default()).map(|l| l.iter().filter(|e| is_chat(e)).collect()).unwrap_or_default();+ let entries: Vec<&Value> = st+ .entries+ .get(bot["id"].as_str().unwrap_or_default())+ .map(|l| l.iter().filter(|e| is_chat(e)).collect())+ .unwrap_or_default();if entries.is_empty() {let intro = adw::StatusPage::builder().title(bot["name"].as_str().unwrap_or(""))- .description(format!("{} in {}\n\n{}\n\nTell it what you need.", backend_name(&st, bot["backend"].as_str().unwrap_or("")), bot["cwd"].as_str().unwrap_or(""), bot["description"].as_str().unwrap_or("")))+ .description(format!(+ "{} in {}\n\n{}\n\nTell it what you need.",+ backend_name(&st, bot["backend"].as_str().unwrap_or("")),+ bot["cwd"].as_str().unwrap_or(""),+ bot["description"].as_str().unwrap_or("")+ )).build();ui.thread.append(&intro);}@@ -482,13 +693,24 @@ fn render_thread(ui: &App) {for e in entries {let at = e["createdAt"].as_i64().unwrap_or(0);if at - last_time > 3_600_000 {- ui.thread.append(>k::Label::builder().label(ago(at)).css_classes(["small", "muted"]).margin_top(12).margin_bottom(6).build());+ ui.thread.append(+ >k::Label::builder()+ .label(ago(at))+ .css_classes(["small", "muted"])+ .margin_top(12)+ .margin_bottom(6)+ .build(),+ );last_author = "";}last_time = at;let kind = e["kind"].as_str().unwrap_or_default();let start = kind != last_author;- last_author = if kind == "user" || kind == "agent" { kind } else { "" };+ last_author = if kind == "user" || kind == "agent" {+ kind+ } else {+ ""+ };match kind {"user" => ui.thread.append(&user_bubble(e, working(bot), start)),"agent" => ui.thread.append(&agent_bubble(e, bot, start)),@@ -498,11 +720,39 @@ fn render_thread(ui: &App) {}if working(bot) {let row = gtk::Box::builder().spacing(8).margin_top(10).build();- row.append(&avatar::widget(bot["avatarShape"].as_str().unwrap_or("blob"), bot["avatarColor"].as_str().unwrap_or("blue"), 28, true, ""));+ row.append(&avatar::widget(+ bot["avatarShape"].as_str().unwrap_or("blob"),+ bot["avatarColor"].as_str().unwrap_or("blue"),+ 28,+ true,+ "",+ ));let col = gtk::Box::new(gtk::Orientation::Vertical, 2);- col.append(>k::Label::builder().label("•••").css_classes(["bubble", "bubble-agent", "muted"]).halign(gtk::Align::Start).build());- let act = bot["activity"].as_str().filter(|s| !s.is_empty()).unwrap_or("Working…");- col.append(>k::Label::builder().label(act).xalign(0.0).css_classes(["small", if bot["status"] == "needsInput" { "needs-text" } else { "dim-label" }]).build());+ col.append(+ >k::Label::builder()+ .label("•••")+ .css_classes(["bubble", "bubble-agent", "muted"])+ .halign(gtk::Align::Start)+ .build(),+ );+ let act = bot["activity"]+ .as_str()+ .filter(|s| !s.is_empty())+ .unwrap_or("Working…");+ col.append(+ >k::Label::builder()+ .label(act)+ .xalign(0.0)+ .css_classes([+ "small",+ if bot["status"] == "needsInput" {+ "needs-text"+ } else {+ "dim-label"+ },+ ])+ .build(),+ );row.append(&col);ui.thread.append(&row);}@@ -513,132 +763,11 @@ fn render_thread(ui: &App) {gtk::glib::idle_add_local_once(move || {adj.set_value(adj.upper());let adj2 = adj.clone();- gtk::glib::timeout_add_local_once(std::time::Duration::from_millis(60), move || adj2.set_value(adj2.upper()));- });- }-}--fn user_bubble(e: &Value, bot_working: bool, start: bool) -> gtk::Widget {- let col = gtk::Box::builder().orientation(gtk::Orientation::Vertical).halign(gtk::Align::End).margin_start(60).margin_top(if start { 12 } else { 2 }).build();- col.append(>k::Label::builder().label(e["data"]["text"].as_str().unwrap_or("")).wrap(true).wrap_mode(gtk::pango::WrapMode::WordChar).selectable(true).xalign(0.0).css_classes(["bubble", "bubble-user"]).build());- let status = match e["data"]["status"].as_str() {- Some("sending") => "Sending…",- Some("queued") if bot_working => "Waiting to send — it'll read this when it's done",- Some("failed") => "Failed to send",- Some("cancelled") => "Not sent — stopped",- _ => "",- };- if !status.is_empty() {- col.append(>k::Label::builder().label(status).css_classes(["small", "muted"]).halign(gtk::Align::End).build());- }- col.upcast()-}--fn agent_bubble(e: &Value, bot: &Value, start: bool) -> gtk::Widget {- let row = gtk::Box::builder().spacing(8).margin_end(60).margin_top(if start { 12 } else { 2 }).build();- if start {- row.append(&avatar::widget(bot["avatarShape"].as_str().unwrap_or("blob"), bot["avatarColor"].as_str().unwrap_or("blue"), 28, false, ""));- } else {- row.append(>k::Box::builder().width_request(28).build());- }- let label = gtk::Label::builder()- .use_markup(true)- .label(markup::to_pango(e["data"]["text"].as_str().unwrap_or("")))- .wrap(true)- .wrap_mode(gtk::pango::WrapMode::WordChar)- .selectable(true)- .xalign(0.0)- .css_classes(["bubble", "bubble-agent"])- .valign(gtk::Align::End)- .build();- row.append(&label);- row.upcast()-}--fn notice(e: &Value) -> gtk::Widget {- let text = e["data"]["text"].as_str().unwrap_or("");- let label = gtk::Label::builder().label(text).wrap(true).selectable(true).margin_top(10).build();- match e["data"]["style"].as_str() {- Some("error") => {- label.add_css_class("notice-error");- label.set_xalign(0.0);- }- _ => label.add_css_class("dim-label"),- }- label.upcast()-}--fn permission_card(ui: &App, st: &State, e: &Value) -> gtk::Widget {- let d = &e["data"];- let pending = d["status"] == "pending";- let card = gtk::Box::builder().orientation(gtk::Orientation::Vertical).spacing(6).css_classes(["card"]).margin_start(36).margin_top(12).build();- if pending {- card.add_css_class("pending");- }- let headline = match d["toolKind"].as_str() {- Some("execute") => "Wants to run a command",- Some("edit" | "delete" | "move") => "Wants to change files",- Some("fetch") => "Wants to access the web",- Some("read" | "search") => "Wants to read files",- _ => "Wants to use a tool",- };- card.append(>k::Label::builder().label(format!("✋ {headline}")).xalign(0.0).css_classes(["heading"]).build());- card.append(>k::Label::builder().label(d["title"].as_str().unwrap_or("")).xalign(0.0).wrap(true).build());- let host = st.hello["name"].as_str().unwrap_or("this computer");- card.append(>k::Label::builder().label(format!("Runs on {host} · {}", folder(d["cwd"].as_str().unwrap_or("")))).xalign(0.0).css_classes(["small", "muted"]).build());- let mut detail = String::new();- if let Some(c) = d["command"].as_str() {- detail.push_str(c);- }- for diff in d["diffs"].as_array().into_iter().flatten() {- detail.push_str(&format!("\n{} +{} −{}\n{}", diff["path"].as_str().unwrap_or(""), diff["added"], diff["removed"], diff["patch"].as_str().unwrap_or("")));- }- if !detail.trim().is_empty() {- let exp = gtk::Expander::new(Some("Details"));- exp.set_child(Some(>k::Label::builder().label(detail.trim()).xalign(0.0).selectable(true).wrap(true).css_classes(["codebox"]).build()));- card.append(&exp);- }- if pending {- let buttons = gtk::FlowBox::builder().selection_mode(gtk::SelectionMode::None).max_children_per_line(4).column_spacing(8).row_spacing(8).homogeneous(true).build();- let mut opts: Vec<&Value> = d["options"].as_array().into_iter().flatten().collect();- let rank = |k: &str| match k { "allow_once" => 0, "allow_always" => 1, "reject_once" => 2, _ => 3 };- opts.sort_by_key(|o| rank(o["kind"].as_str().unwrap_or("")));- for o in opts {- let kind = o["kind"].as_str().unwrap_or("");- let label = match kind { "allow_once" => "Allow once", "allow_always" => "Always allow", "reject_once" => "Deny", "reject_always" => "Never", _ => o["name"].as_str().unwrap_or("OK") };- let btn = gtk::Button::with_label(label);- if kind == "allow_once" {- btn.add_css_class("accent-fill");- } else if kind.starts_with("reject") {- btn.add_css_class("destructive-action");- }- let (entry_id, opt) = (e["id"].as_str().unwrap_or("").to_owned(), o["optionId"].clone());- let ui2 = ui.clone();- btn.connect_clicked(move |b| {- b.set_sensitive(false);- let ui3 = ui2.clone();- client::call("respondPermission", json!({"entryId": entry_id, "optionId": opt}), move |r| {- if let Err(e) = r {- toast(&ui3, &e);- }- });+ gtk::glib::timeout_add_local_once(std::time::Duration::from_millis(60), move || {+ adj2.set_value(adj2.upper())});- buttons.insert(&btn, -1);- }- card.append(&buttons);- } else {- let chosen = d["options"].as_array().into_iter().flatten().find(|o| o["optionId"] == d["selected"]);- let outcome = match (d["status"].as_str(), chosen.and_then(|o| o["kind"].as_str())) {- (Some("answered"), Some("allow_once")) => "Allowed once",- (Some("answered"), Some("allow_always")) => "Always allowed",- (Some("answered"), Some("reject_once")) => "Denied",- (Some("answered"), _) => "Answered",- (Some("cancelled"), _) => "Cancelled",- _ => "Expired — the agent moved on",- };- card.append(>k::Label::builder().label(outcome).xalign(0.0).css_classes(["small", "dim-label"]).build());+ });}- card.upcast()}fn update_composer(ui: &App) {@@ -650,7 +779,10 @@ fn update_composer(ui: &App) {fn update_composer_for(ui: &App, bot: &Value) {let buf = ui.composer.buffer();- let has_text = !buf.text(&buf.start_iter(), &buf.end_iter(), false).trim().is_empty();+ let has_text = !buf+ .text(&buf.start_iter(), &buf.end_iter(), false)+ .trim()+ .is_empty();ui.stop_btn.set_visible(working(bot) && !has_text);ui.send_btn.set_visible(!working(bot) || has_text);ui.send_btn.set_sensitive(has_text);@@ -658,8 +790,13 @@ fn update_composer_for(ui: &App, bot: &Value) {fn send(ui: &App) {let buf = ui.composer.buffer();- let text = buf.text(&buf.start_iter(), &buf.end_iter(), false).trim().to_owned();- let Some(bot) = ui.state.borrow().current.clone() else { return };+ let text = buf+ .text(&buf.start_iter(), &buf.end_iter(), false)+ .trim()+ .to_owned();+ let Some(bot) = ui.state.borrow().current.clone() else {+ return;+ };if text.is_empty() {return;}@@ -672,23 +809,34 @@ fn send(ui: &App) {);schedule(ui);let ui2 = ui.clone();- client::call("send", json!({"botId": bot, "text": text, "clientNonce": nonce}), move |r| {- let mut st = ui2.state.borrow_mut();- match r {- Ok(v) => upsert(&mut st, v["entry"].clone()),- Err(_) => {- if let Some(e) = st.entries.get_mut(&bot).and_then(|l| l.iter_mut().find(|e| e["id"] == format!("local-{nonce}"))) {- e["data"]["status"] = "failed".into();+ client::call(+ "send",+ json!({"botId": bot, "text": text, "clientNonce": nonce}),+ move |r| {+ let mut st = ui2.state.borrow_mut();+ match r {+ Ok(v) => upsert(&mut st, v["entry"].clone()),+ Err(_) => {+ if let Some(e) = st+ .entries+ .get_mut(&bot)+ .and_then(|l| l.iter_mut().find(|e| e["id"] == format!("local-{nonce}")))+ {+ e["data"]["status"] = "failed".into();+ }}}- }- drop(st);- schedule(&ui2);- });+ drop(st);+ schedule(&ui2);+ },+ );}fn now_ms() -> i64 {- std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as i64+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_millis() as i64}pub fn mark_read(ui: &App) {