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
refactor(desktop): replace the Mac and Linux apps with the desktop app
leepokai41135acf3a57
diff --git a/.github/workflows/kit.yml b/.github/workflows/kit.ymlindex bd2dd20b..7ae9998a 100644--- a/.github/workflows/kit.yml+++ b/.github/workflows/kit.yml@@ -1,22 +1,25 @@-name: CodyncKit+name: iOS Kit+# The iPhone app's Swift package (apps/ios/Kit): models, client, stores and screens.on:push:branches: [main, v2]- paths: ["kit/**", "docs/reference/fixtures/remote-relay-vectors.json", ".github/workflows/kit.yml"]+ paths: ["apps/ios/Kit/**", "docs/reference/fixtures/remote-relay-vectors.json", ".github/workflows/kit.yml"]pull_request:- paths: ["kit/**", "docs/reference/fixtures/remote-relay-vectors.json"]+ paths: ["apps/ios/Kit/**", "docs/reference/fixtures/remote-relay-vectors.json"]jobs:test:runs-on: macos-latestdefaults:run:- working-directory: kit+ working-directory: apps/ios/Kitsteps:- uses: actions/checkout@v4- uses: maxim-lobanov/setup-xcode@v1with:xcode-version: latest-stable- - run: swift build- - run: swift test+ - name: Test on an iPhone simulator+ run: |+ DEVICE=$(xcrun simctl list devices available | grep -m1 -oE 'iPhone [^(]+\(([0-9A-F-]{36})\)' | grep -oE '[0-9A-F-]{36}')+ xcodebuild test -scheme CodyncKit-Package -destination "platform=iOS Simulator,id=$DEVICE" -quietdiff --git a/.github/workflows/screen-macos.yml b/.github/workflows/screen-macos.ymlindex bf636c8c..b4e4c281 100644--- a/.github/workflows/screen-macos.yml+++ b/.github/workflows/screen-macos.yml@@ -10,15 +10,15 @@ on:paths:- "apps/screen-macos/**"- "apps/project.yml"- - "kit/Package.swift"- - "kit/Package.resolved"+ - "apps/ios/Kit/Package.swift"+ - "apps/ios/Kit/Package.resolved"- ".github/workflows/screen-macos.yml"pull_request:paths:- "apps/screen-macos/**"- "apps/project.yml"- - "kit/Package.swift"- - "kit/Package.resolved"+ - "apps/ios/Kit/Package.swift"+ - "apps/ios/Kit/Package.resolved"- ".github/workflows/screen-macos.yml"jobs:@@ -37,7 +37,7 @@ jobs:- uses: actions/cache@v4with:path: build/screen-ci/SourcePackages- key: ${{ runner.os }}-screen-packages-${{ hashFiles('apps/project.yml', 'kit/Package.swift', 'kit/Package.resolved') }}+ key: ${{ runner.os }}-screen-packages-${{ hashFiles('apps/project.yml', 'apps/ios/Kit/Package.swift', 'apps/ios/Kit/Package.resolved') }}- name: Build screen helperrun: >-diff --git a/AGENTS.md b/AGENTS.mdindex 53f5126b..78b68290 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -3,8 +3,9 @@## Project Structure & Module Organization- `host/`: Rust daemon, ACP integration, SQLite storage, HTTP/SSE API, and terminal UI; unit tests live alongside modules in `src/`.-- `kit/`: shared Swift package. `CodyncKit` contains models, clients, and design primitives; `CodyncUI` contains shared screens and stores. Tests and fixtures live in `kit/Tests/CodyncKitTests/`.-- `apps/`: iOS, macOS, and Linux clients, plus `screen-macos` and `screen-linux` helpers. Apple assets live in each target’s `Resources/`; widgets live in `apps/ios/Widgets/`.+- `apps/ios/`: iPhone app (SwiftUI); widgets live in `apps/ios/Widgets/`. `apps/ios/Kit/` is its Swift package: `CodyncKit` (models, clients, design primitives) and `CodyncUI` (screens and stores); tests in `apps/ios/Kit/Tests/CodyncKitTests/`.+- `apps/desktop/`: desktop app for macOS and Linux (Electron, React, TypeScript): [docs/architecture/desktop-app.md](docs/architecture/desktop-app.md).+- `apps/screen-macos` and `apps/screen-linux`: Remote screen helpers.- `cloud/`: Cloudflare accounts, encrypted relay, Durable Objects and D1; tests live in `cloud/test/`.- `relay/`: Cloudflare push worker and `test/`; `web/`: website (Next.js); `packaging/`: distribution templates; `docs/`: architecture and naming guidance.@@ -13,50 +14,50 @@Run from the repository root unless a command changes directories:- `xcodegen generate --spec apps/project.yml`: regenerate `apps/Codync.xcodeproj` after editing `apps/project.yml`; never edit `project.pbxproj` directly.-- `xcodebuild build -project apps/Codync.xcodeproj -scheme macOS -configuration Debug`: build the Mac app. Use Xcode’s `iOS` scheme to run on a simulator or device.+- Use Xcode’s `iOS` scheme to run the iPhone app on a simulator or device.+- `cd apps/desktop && npm ci && npm run dev`: run the desktop app; `npm run typecheck && npm test` for its CI checks.- `cd host && cargo build`: build the host; `cargo run -- serve` starts it in the foreground.- `cd host && cargo fmt --check && cargo clippy --all-targets -- -D warnings && cargo test`: run host CI checks.-- `cd kit && swift test`: run shared Swift tests.-- `cd apps/linux && cargo test`: test Linux code; requires GTK 4, libadwaita and VTE GTK 4 development packages.+- `cd apps/ios/Kit && xcodebuild test -scheme CodyncKit-Package -destination 'platform=iOS Simulator,name=<any iPhone>'`: run the iPhone package tests.- `cd cloud && npm ci && npm test && npm run typecheck`: validate the cloud service; see `docs/guides/cloudflare-testing.md` for integration checks.- `cd relay && npm ci && npm test && npm run typecheck`: install dependencies and validate the relay.## Installing a new build: kill the old one first-Always stop the old Mac app, host and iPhone process before running a new build (old host = old protocol, old app = old UI); commands in [docs/guides/development.md](docs/guides/development.md#apple-apps).+Always stop the old desktop app, host and iPhone process before running a new build (old host = old protocol, old app = old UI); commands in [docs/guides/development.md](docs/guides/development.md#apple-apps).Keep only the latest build: in this checkout, Apple builds go to `build/dd` only (no other `-derivedDataPath`, no copies in scratchpads, `/tmp` or Xcode's DerivedData); delete any older Codync build right away, so macOS never launches a stale copy. A git worktree may keep its own single build inside that worktree.## Versioning & releases-- **Every source change ships as a release.** A version bump on `main` is the only release trigger (Auto Tag → DMG, host, Linux app, Homebrew, in-app update), so any change to shipped code (`apps/`, `kit/`, `host/`, `packaging/`) bumps the version before it reaches `main`, without being asked. Docs, `web/`, `cloud/`, `relay/` and CI-only changes don't bump.+- **Every source change ships as a release.** A version bump on `main` is the only release trigger (Auto Tag → desktop app for macOS and Linux, host, Homebrew, in-app update), so any change to shipped code (`apps/`, `host/`, `packaging/`) bumps the version before it reaches `main`, without being asked. Docs, `web/`, `cloud/`, `relay/` and CI-only changes don't bump.- Phone ↔ host compatibility: each side names the oldest version of the other it works with (`minApp` in the host's `hello`, `minHost` in each client). Additive changes need nothing; a rename/removal raises `minApp` in the same release, and hosts hold that release until the App Store has the iPhone app: [docs/reference/compatibility.md](docs/reference/compatibility.md)- Pick the bump yourself: patch for fixes and small tweaks, minor for new features or protocol additions. Never bump major (stay on 2.x). One bump per merge into `main`: if `MARKETING_VERSION` is already ahead of the latest `v*` tag, leave it.-- How: set `MARKETING_VERSION` in `apps/project.yml` and `version` in `host/Cargo.toml` and `apps/linux/Cargo.toml` (+ their `Cargo.lock` entries) to the same value, run `xcodegen generate --spec apps/project.yml`, commit as `build: bump version to X.Y.Z`. Never touch `CURRENT_PROJECT_VERSION` (Xcode Cloud sets the iOS build number). When the iOS app changes, also write that version's section in `apps/ios/WhatsNew.md` (zh-Hant + en-US, what iPhone users notice); it becomes the App Store "What's New".+- How: set `MARKETING_VERSION` in `apps/project.yml` and `version` in `host/Cargo.toml` (+ its `Cargo.lock` entry) and `apps/desktop/package.json` (+ `package-lock.json`) to the same value, run `xcodegen generate --spec apps/project.yml`, commit as `build: bump version to X.Y.Z`. Never touch `CURRENT_PROJECT_VERSION` (Xcode Cloud sets the iOS build number). When the iOS app changes, also write that version's section in `apps/ios/WhatsNew.md` (zh-Hant + en-US, what iPhone users notice); it becomes the App Store "What's New".## Coding Style & Naming Conventions-Use four-space indentation for Swift and Rust. Follow Swift 6 strict concurrency, SwiftUI, and structured `async/await`; avoid unchecked sendability. Rust uses edition 2024, rustfmt, and Clippy; avoid `unwrap()` outside tests.+Use four-space indentation for Swift and Rust, two spaces for TypeScript. Follow Swift 6 strict concurrency, SwiftUI, and structured `async/await`; avoid unchecked sendability. Rust uses edition 2024, rustfmt, and Clippy; avoid `unwrap()` outside tests.Name Swift files after their main `UpperCamelCase` type; use `snake_case.rs` and `kebab-case.ts`. Follow role suffixes such as `View`, `Row`, and `Store`. See `docs/architecture/file-structure.md` and `CLAUDE.md` for architectural conventions.-- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. The macOS menu bar also uses native `MenuBarExtra(.menu)`, menus, pickers and toggles. Keep system authentication and widget containers native. On iOS `.codyncSheet` presents the system sheet (grabber, swipe down). Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.+- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. The desktop app's menu bar/tray menu is the system menu. Keep system authentication and widget containers native. On iOS `.codyncSheet` presents the system sheet (grabber, swipe down). Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `apps/ios/Kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncDialog`, `ToggleStyle.codync`); on the desktop, `apps/desktop/src/renderer/components/` (`Sheet`, `Dialog`, `AnchoredMenu`, `ModalHeader`, `Controls.tsx`, `Icon` for SF Symbols). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.## Cross-platform UI changes-- Any UI change in any client must include the corresponding updates to all other native clients and the TUI in the same change: shared SwiftUI (`kit/Sources/CodyncUI/`), iOS (`apps/ios/`), macOS (`apps/macos/`), Linux GTK (`apps/linux/src/`), and terminal UI (`host/src/tui/`). This applies in every direction; Linux and TUI changes must also be reflected in SwiftUI.+- Any UI change in any client must include the corresponding updates to the other clients in the same change: iOS (`apps/ios/`, `apps/ios/Kit/Sources/CodyncUI/`), desktop (`apps/desktop/src/renderer/`, macOS and Linux), and terminal UI (`host/src/tui/`). This applies in every direction.- Keep shared features, actions, terminology, displayed information, and loading, empty, error, and permission states consistent. Adapt layout, controls, and input to each platform, including terminal keyboard interaction, while preserving the same user-facing behavior.- Inspect every client's corresponding implementation before finishing a UI task. Implement applicable changes together; do not silently defer another client. For a platform-only change or an unsupported capability, document which clients are unaffected and the concrete reason in the change summary.- Validate each affected client with its relevant build/tests and UI checks. Report any checks that could not run and why.-- Shared SwiftUI (`kit/`) builds into both iPhone and Mac: never change a shared view's or control's defaults for one platform, and keep one-platform chrome in platform files ([ui-conventions](docs/design/ui-conventions.md#shared-code-across-iphone-and-mac)).+- The desktop app is one codebase for macOS and Linux: platform differences go through `window.codync.platform` checks or the main process, never a fork of a view.## Testing Guidelines-Use Swift Testing (`@Test`, `#expect`), Rust unit tests, and the relay’s Node assertion tests. Name tests after observable behavior. Add regression coverage for changed logic; no numeric coverage threshold is configured.+Use Swift Testing (`@Test`, `#expect`), Rust unit tests, `node --test` in the desktop app, and the relay’s Node assertion tests. Name tests after observable behavior. Add regression coverage for changed logic; no numeric coverage threshold is configured.## Commit & Pull Request Guidelines-- Conventional Commits: `type(scope): subject`. Types: `feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `build`, `ci`, `chore`. Scope is the area touched: `ios`, `macos`, `kit`, `host`, `linux`, `cloud`, `relay`, `web`, `docs`.+- Conventional Commits: `type(scope): subject`. Types: `feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `build`, `ci`, `chore`. Scope is the area touched: `ios`, `desktop`, `host`, `cloud`, `relay`, `web`, `docs`.- Subject: imperative mood ("add", not "added"), lowercase after the colon, no trailing period, at most 72 characters (aim for 50). Say what changes for the user, not which files moved.- Body (after a blank line, wrapped at 72 columns) when the change isn't obvious from the subject: what and why, not how. Bullets are fine.- One logical change per commit. Don't mix unrelated work, and stage only your own hunks when others have uncommitted changes in the tree.diff --git a/CLAUDE.md b/CLAUDE.mdindex 6cf3bb04..a770e347 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -5,19 +5,20 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess## Language & Syntax- **Swift 6** strict concurrency mode — use latest Swift 6 syntax throughout-- Prefer SwiftUI lifecycle and modern APIs (`MenuBarExtra`, `@Observable`, `@State`, `@Environment`)+- Prefer SwiftUI lifecycle and modern APIs (`@Observable`, `@State`, `@Environment`)- Use structured concurrency (`async/await`, `TaskGroup`) over Combine- Use `sending`, `nonisolated`, `@MainActor` correctly per Swift 6 rules- Avoid `@unchecked Sendable` — prefer proper `Sendable` conformance+- Desktop app (`apps/desktop/`) is Electron + React + strict TypeScript: state in `Observable` models (`src/renderer/store/`), host calls through the `window.codync` bridge (`src/shared/ipc.ts`), main-process code in `src/main/`; CI runs `npm run typecheck` and `npm test`- Host is Rust 2024 edition and follows the `rust-skills` rules (`~/.agents/skills/rust-skills`). Lints live in `host/Cargo.toml` (`[lints]`: default groups + pedantic, `unwrap_used`); CI runs `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings`- Host conventions: no `unwrap()` outside tests (`expect("why this can't fail")` for true invariants); lock std mutexes with `LockExt::locked()` (poison-tolerant); enums, not strings, for states and modes (`BotStatus`, `Permission`, `EntryKind`, `AlertKind`); `tracing` with structured fields (`error = format!("{e:#}")` keeps the context chain); blocking fs/process work goes through `spawn_blocking`; registry JSON is untrusted (paths are validated)## Architecture-- Clients: iOS app, native Mac window (menu bar app), native Linux app (`apps/linux/`, GTK 4 + libadwaita in Rust), terminal UI (`codync-host tui`, `host/src/tui/`, ratatui; layout and state vocabulary modeled on herdr). All talk to the host API; no web UI.-- Shared Swift (`kit/`): `CodyncKit` (models, client, theme, avatars) + `CodyncUI` (`BotStore` + chat screens) used by iOS and macOS. Platform specifics go through `BotStore` hooks or `Platform.swift`.+- Clients: iOS app (SwiftUI), desktop app for macOS and Linux (`apps/desktop/`, Electron: menu bar/tray + chat window; why and how: [docs/architecture/desktop-app.md](docs/architecture/desktop-app.md)), terminal UI (`codync-host tui`, `host/src/tui/`, ratatui; layout and state vocabulary modeled on herdr). All talk to the host API.+- iPhone Swift package (`apps/ios/Kit/`, iOS only): `CodyncKit` (models, client, theme, avatars; also used by the widgets and the notification extension) + `CodyncUI` (`BotStore` + screens).- UI principle: buttons an icon can express are icon-only (with tooltip / accessibility label); text only where an icon would be ambiguous (approval choices).-- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. **iOS menus are always the system ones**: tap menus through `DropdownMenu`/`ChoicePicker` (native `Menu`), long-press through `.contextActions` (native `contextMenu`). Never hand-build a dropdown on iOS and never call `.codyncMenu` there (it is macOS-only and a compile error on iOS): the custom overlay lands in the wrong place (sheets, scroll views, the composer's + menu). The macOS menu bar also uses native `MenuBarExtra(.menu)`, menus, pickers and toggles. Keep system authentication and widget containers native. On iOS `.codyncSheet` presents the system sheet (grabber, swipe down). Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.+- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. **iOS menus are always the system ones**: tap menus through `DropdownMenu`/`ChoicePicker` (native `Menu`), long-press through `.contextActions` (native `contextMenu`). Never hand-build a dropdown on iOS: a custom overlay lands in the wrong place (sheets, scroll views, the composer's + menu). The desktop app's menu bar/tray menu is the system menu. Keep system authentication and widget containers native. On iOS `.codyncSheet` presents the system sheet (grabber, swipe down). Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `apps/ios/Kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncDialog`, `ToggleStyle.codync`); on the desktop, `apps/desktop/src/renderer/components/` (`Sheet`, `Dialog`, `AnchoredMenu`, `ModalHeader`, `Controls.tsx`, `Icon` for SF Symbols). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.- `host/` — **codync-host** (Rust, macOS + Linux). Detects installed harnesses (`agent/backends.rs`: login-shell PATH + known dirs) and the ACP registry (`agent/registry.rs`, cached in `~/.codync/registry.json`, binaries under `~/.codync/agents`). Drives agents over **ACP** (JSON-RPC on stdio, hand-rolled in `agent/acp.rs`, updates kept as `serde_json::Value` so new adapter variants never break parsing). One actor per bot (`agent/bot.rs`) owns the agent process + session and maps `session/update` onto transcript entries.- **Chat ≠ session**: a bot is one endless transcript (SQLite `entries`, ordered by `seq`); the ACP session underneath is resumed with `session/load` or replaced by *New session*.- **Group chats and threads** are host features every client drives through the same methods (`send` with `threadId`, `thread`, `createBot {kind: group}`); clients never route, parse mentions or count replies themselves. A group is a roster row whose members answer in their own sessions (Grok Bot's room turns); a thread on a bot's message is a forked session: [docs/features/groups-and-threads.md](docs/features/groups-and-threads.md).@@ -25,23 +26,23 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess- **Context & memory** (Grok Bot's design): frozen instruction snapshot per session + compaction epoch (Claude gets it as a system prompt), profile edits as update blocks, per-bot memory files written by a keeper agent, busy-time messages folded into one turn, interrupted turns resumed: [docs/features/context-and-memory.md](docs/features/context-and-memory.md).- **Chat shows only**: user messages, the *final* agent message of each turn (`data.final`), permission cards, notices. Narration, thoughts, tool calls, plans are trace entries (Full conversation sheet).- **Sync**: every mutation stamps a global `rev`. Clients call `GET /events?since=<rev>` (catch-up in rev order, then live). Emission happens under `Hub::emit_lock` so events leave in rev order. Clients upsert by id; never skip undecodable events (the iOS app rewinds to rev 0).-- API: `POST /api/<method>` + SSE with the bearer token (`~/.codync/token`) is **loopback only** (Mac app, SSH tunnel, local helpers). Phones and other remote clients use the E2E channel (`/channel` direct, or the Cloudflare relay). Default port **19222**.+- API: `POST /api/<method>` + SSE with the bearer token (`~/.codync/token`) is **loopback only** (desktop app, SSH tunnel, local helpers). Phones and other remote clients use the E2E channel (`/channel` direct, or the Cloudflare relay). Default port **19222**.- Remote access (Cloudflare relay primary, direct LAN/Tailscale alternative, accounts, SSH, public routine webhooks queued in the relay §7.8): [docs/reference/remote-relay.md](docs/reference/remote-relay.md).-- Remote screen (`host/src/screen.rs` is the reference): phones view/control the computer over WebRTC (hardware H.264, non-trickle SDP relayed by `screenOffer`, input on data channels `input` / `input-fast`); bots get the built-in `computer` MCP server (`codync-host mcp computer`, `host/src/mcp.rs`) when their `computer` flag is on. Capture/input live in a helper on `~/.codync/screen.sock`: `apps/screen-macos` (macOS, launchd agent via `SMAppService`, owns the TCC grants) or `apps/screen-linux` (`codync-screen`: portals + GStreamer, started by the host). Off by default; `setScreenEnabled` is accepted only from loopback. An interactive phone takes over (bots may only look).+- Remote screen (`host/src/screen.rs` is the reference): phones view/control the computer over WebRTC (hardware H.264, non-trickle SDP relayed by `screenOffer`, input on data channels `input` / `input-fast`); bots get the built-in `computer` MCP server (`codync-host mcp computer`, `host/src/mcp.rs`) when their `computer` flag is on. Capture/input live in a helper on `~/.codync/screen.sock`: `apps/screen-macos` (macOS, launchd agent the desktop app registers via `SMAppService`, owns the TCC grants) or `apps/screen-linux` (`codync-screen`: portals + GStreamer, started by the host). Off by default; `setScreenEnabled` is accepted only from loopback. An interactive phone takes over (bots may only look).- Multiple computers per account are future work, not a current priority: the product targets one computer. The multi-computer structure (`AccountStore`, `BotReference`) stays because relay/accounts/SSH build on it; don't extend or polish multi-computer features unless asked.-- Environments: **dev** (`dev-api.codync.dev`, Clerk development instance, Debug builds) and **main** (`api.codync.dev`, Clerk production, Release builds); `apps/shared/Config/<env>.plist` becomes `AccountConfig.plist`. Details: [spec §14.0](docs/reference/remote-relay.md).+- Environments: **dev** (`dev-api.codync.dev`, Clerk development instance, Debug builds) and **main** (`api.codync.dev`, Clerk production, Release builds); `apps/shared/Config/<env>.plist` becomes the iOS `AccountConfig.plist` and the desktop `resources/account-config.json` (`tools/account-config.mjs`). Details: [spec §14.0](docs/reference/remote-relay.md).- Push: iOS registers its APNs token with `relay/` → gets an AES-GCM ticket → gives it (plus its X25519 push key) to the host; the host seals title/body to that key and a Notification Service Extension opens it, so `relay/` sees only generic text. Alert kinds: *needs you*, *done*, and *failed*, suppressed while the iOS app is connected. Delivery and lifecycle: [notification design](docs/design/push-and-live-activity.md).-- Voice call (iPhone, Mac): on-device speech, or OpenAI / Gemini realtime on the user's own key (kept in the host's vault, which mints per-call credentials; audio goes device ↔ provider); the host sees plain messages. Grok-style call bar: [docs/features/voice-call.md](docs/features/voice-call.md).+- Voice call (iPhone, desktop): on-device speech (macOS desktop: the `codync-speech` helper), or OpenAI / Gemini realtime on the user's own key (kept in the host's vault, which mints per-call credentials; audio goes device ↔ provider); the host sees plain messages. Grok-style call bar: [docs/features/voice-call.md](docs/features/voice-call.md).- Usage: local only — `claude -p /usage --no-session-persistence`, the Claude status line (`codync-host statusline`, wrapping any existing one), Claude ACP `usage_update` rate-limit meta, Codex rollout files. Never call provider APIs with agent credentials.-- macOS app is thin: embeds `codync-host` in `Contents/MacOS` (Xcode post-build script runs cargo), installs it as a launchd agent via `codync-host install`; menu bar shows status/pairing/usage and opens the native chat window (NavigationSplitView over `CodyncUI`). Not sandboxed, not Mac App Store (the host must spawn CLIs).+- The desktop app is thin: the Mac build bundles `codync-host` in `Contents/Resources` (Linux uses the installed host) and installs it as a launchd/systemd agent via `codync-host install`; the menu bar/tray shows status/pairing/usage and opens the chat window. Not sandboxed, not Mac App Store (the host must spawn CLIs).## Cross-platform UI changes-- Any UI change in any client must include the corresponding updates to all other native clients and the TUI in the same change: shared SwiftUI (`kit/Sources/CodyncUI/`), iOS (`apps/ios/`), macOS (`apps/macos/`), Linux GTK (`apps/linux/src/`), and terminal UI (`host/src/tui/`). This applies in every direction; Linux and TUI changes must also be reflected in SwiftUI.+- Any UI change in any client must include the corresponding updates to the other clients in the same change: iOS (`apps/ios/`, `apps/ios/Kit/Sources/CodyncUI/`), desktop (`apps/desktop/src/renderer/`, macOS and Linux), and terminal UI (`host/src/tui/`). This applies in every direction.- Keep shared features, actions, terminology, displayed information, and loading, empty, error, and permission states consistent. Adapt layout, controls, and input to each platform, including terminal keyboard interaction, while preserving the same user-facing behavior.- Inspect every client's corresponding implementation before finishing a UI task. Implement applicable changes together; do not silently defer another client. For a platform-only change or an unsupported capability, document which clients are unaffected and the concrete reason in the change summary.- Validate each affected client with its relevant build/tests and UI checks. Report any checks that could not run and why.-- Shared SwiftUI (`kit/`) builds into both iPhone and Mac: never change a shared view's or control's defaults for one platform, and keep one-platform chrome in platform files ([ui-conventions](docs/design/ui-conventions.md#shared-code-across-iphone-and-mac)).+- The desktop app is one codebase for macOS and Linux: platform differences go through `window.codync.platform` checks or the main process, never a fork of a view.## Codync 1.x does not exist for us@@ -51,7 +52,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess## Installing a new build: kill the old one first-Always stop the old Mac app, host and iPhone process before running a new build (old host = old protocol, old app = old UI); commands in [docs/guides/development.md](docs/guides/development.md#apple-apps).+Always stop the old desktop app, host and iPhone process before running a new build (old host = old protocol, old app = old UI); commands in [docs/guides/development.md](docs/guides/development.md#apple-apps).Keep only the latest build: in this checkout, Apple builds go to `build/dd` only (no other `-derivedDataPath`, no copies in scratchpads, `/tmp` or Xcode's DerivedData); delete any older Codync build right away, so macOS never launches a stale copy. A git worktree may keep its own single build inside that worktree.@@ -66,19 +67,18 @@ Keep only the latest build: in this checkout, Apple builds go to `build/dd` only## Versioning- Phone ↔ host compatibility: each side names the oldest version of the other it works with (`minApp` in the host's `hello`, `minHost` in each client). Additive changes need nothing; a rename/removal raises `minApp` in the same release, and hosts hold that release until the App Store has the iPhone app: [docs/reference/compatibility.md](docs/reference/compatibility.md)-- **Every source change ships as a release.** A version bump on `main` is the only release trigger (Auto Tag → DMG, host, Linux app, Homebrew, in-app update), so any change to shipped code (`apps/`, `kit/`, `host/`, `packaging/`) bumps the version before it reaches `main`, without being asked. Docs, `web/`, `cloud/`, `relay/` and CI-only changes don't bump.+- **Every source change ships as a release.** A version bump on `main` is the only release trigger (Auto Tag → desktop app for macOS and Linux, host, Homebrew, in-app update), so any change to shipped code (`apps/`, `host/`, `packaging/`) bumps the version before it reaches `main`, without being asked. Docs, `web/`, `cloud/`, `relay/` and CI-only changes don't bump.- Pick the bump yourself: patch for fixes and small tweaks, minor for new features or protocol additions. Never bump major (stay on 2.x). One bump per merge into `main`: if `MARKETING_VERSION` is already ahead of the latest `v*` tag, leave it.-- How: set `MARKETING_VERSION` in `apps/project.yml` and `version` in `host/Cargo.toml` and `apps/linux/Cargo.toml` (+ their `Cargo.lock` entries) to the same value, run `xcodegen generate --spec apps/project.yml`, commit as `build: bump version to X.Y.Z`. Never touch `CURRENT_PROJECT_VERSION` (Xcode Cloud sets the iOS build number). When the iOS app changes, also write that version's section in `apps/ios/WhatsNew.md` (zh-Hant + en-US, what iPhone users notice); it becomes the App Store "What's New".+- How: set `MARKETING_VERSION` in `apps/project.yml` and `version` in `host/Cargo.toml` (+ its `Cargo.lock` entry) and `apps/desktop/package.json` (+ `package-lock.json`) to the same value, run `xcodegen generate --spec apps/project.yml`, commit as `build: bump version to X.Y.Z`. Never touch `CURRENT_PROJECT_VERSION` (Xcode Cloud sets the iOS build number). When the iOS app changes, also write that version's section in `apps/ios/WhatsNew.md` (zh-Hant + en-US, what iPhone users notice); it becomes the App Store "What's New".## Targets-- `macOS` (`apps/macos/`) — menu bar app + embedded host+- `apps/desktop/` — desktop app for macOS and Linux (Electron; `npm run dev`, packaged by `.github/workflows/release-desktop.yml`)- `iOS` (`apps/ios/`) — iOS app-- `Screen` (`apps/screen-macos/`) — Codync Screen: capture, input and WebRTC for Remote screen, embedded in the Mac app (`Contents/Library/LoginItems`)-- `apps/screen-linux/` — `codync-screen` (Rust, GStreamer + xdg portals), the Linux Remote screen helper; build/test in the same container as `apps/linux`+- `Screen` (`apps/screen-macos/`) — Codync Screen: capture, input and WebRTC for Remote screen, embedded in the macOS desktop app (`Contents/Library/LoginItems`)+- `apps/screen-linux/` — `codync-screen` (Rust, GStreamer + xdg portals), the Linux Remote screen helper- `Widgets` (`apps/ios/Widgets/`) — usage widget + bot Live Activity (bundle id `com.pokai.Codync.ios.LiveActivity`)-- `CodyncKit` (`kit/`) — shared Swift package: `CodyncKit` + `CodyncUI` libraries-- `apps/linux/` — `codync` GTK app (build/test in a container with libgtk-4-dev + libadwaita-1-dev + libvte-2.91-gtk4-dev)+- `CodyncKit` (`apps/ios/Kit/`) — the iPhone app's Swift package: `CodyncKit` + `CodyncUI` libraries (tests: `xcodebuild test -scheme CodyncKit-Package` on an iOS simulator)## Layout & naming@@ -86,7 +86,7 @@ Folder layout, file naming and shared terms: [docs/architecture/file-structure.m## Commit messages-- Conventional Commits: `type(scope): subject`. Types: `feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `build`, `ci`, `chore`. Scope is the area touched: `ios`, `macos`, `kit`, `host`, `linux`, `cloud`, `relay`, `web`, `docs`.+- Conventional Commits: `type(scope): subject`. Types: `feat`, `fix`, `refactor`, `perf`, `docs`, `test`, `build`, `ci`, `chore`. Scope is the area touched: `ios`, `desktop`, `host`, `cloud`, `relay`, `web`, `docs`.- Subject: imperative mood ("add", not "added"), lowercase after the colon, no trailing period, at most 72 characters (aim for 50). Say what changes for the user, not which files moved.- Body (after a blank line, wrapped at 72 columns) when the change isn't obvious from the subject: what and why, not how. Bullets are fine.- One logical change per commit. Don't mix unrelated work, and stage only your own hunks when others have uncommitted changes in the tree.diff --git a/README.md b/README.mdindex 8a998b77..d5ef75fc 100644--- a/README.md+++ b/README.md@@ -1,6 +1,6 @@<div align="center">-<img src="apps/linux/data/com.pokai.Codync.svg" width="128" alt="Codync icon">+<img src="apps/desktop/resources/icon.svg" width="128" alt="Codync icon"># Codync@@ -16,7 +16,8 @@ Your coding agents, as teammates you can message.-++<a href="https://youtu.be/awhZJPjJaPc"><img src="docs/screenshots/launch-film.jpg" width="760" alt="Watch the Codync launch film on YouTube (1:26)"></a>@@ -34,7 +35,7 @@ Codync turns the coding agents on your computer — Claude Code, Codex, Cursor,- **Bring any coding agent.** Claude Code, Codex, Cursor, Gemini, Copilot, OpenCode, Pi, Grok Build and ~40 more — everything in the [ACP registry](https://agentclientprotocol.com/registry). Installed agents are found automatically, the rest are fetched on first use, and every bot picks its own. Mix them freely: a Claude bot can ask a Codex bot for a review.- **Many bots, one team.** Run as many bots as you like side by side, each with its own agent, project folder and approvals, all working at once. Put several in a **group chat** and they answer in turn, like a team channel; `@name` picks who replies. Start a **thread** on any message to branch off without cluttering the main chat.- **Built in Rust.** `codync-host` is one small, fast Rust binary for macOS and Linux (static on Linux, runs on any distro) that drives every agent, keeps the transcripts and serves every client.-- **Native on every platform.** SwiftUI on iPhone and Mac, GTK 4 / libadwaita on Linux, and a terminal UI for SSH. No web views, no Electron.+- **One app per kind of device.** Native SwiftUI on the iPhone, one desktop app for Mac and Linux (Electron), and a terminal UI for SSH.- **A 1:1 Grok Bot / Muse alternative.** Persistent named bots, group chats, reply threads, bots asking each other for help, approval cards, per-bot memory, remote screen, voice calls and "needs you / done" notifications — the same features, without being tied to one model or one subscription.- **Reach your computer from anywhere, free.** The hosted Cloudflare relay is included at no cost: no Tailscale, no VPN, no port forwarding. Traffic is end-to-end encrypted between your phone and your computer, so the relay only forwards ciphertext. Same Wi-Fi or Tailscale? The phone connects directly instead.- **Every computer, one app.** Sign in and your iPhone lists every computer on your account (Mac, Linux desktop, server or cloud VM); tap **Connect**, confirm a 6-digit code on that computer, and its bots show up next to the others. A new bot can live on any of them, and the Mac app reaches your SSH machines too. Each computer approves each device itself, so an account alone never unlocks a computer.@@ -47,8 +48,8 @@ Codync turns the coding agents on your computer — Claude Code, Codex, Cursor,| | Platform | App | Highlights ||---|---|---|---|| 📱 | **iPhone** | Native SwiftUI | Chat with bots, approvals, push notifications, Live Activity, widgets, remote screen, voice calls |-| 💻 | **macOS** | Native SwiftUI, menu bar + window | Runs the host, chat window, usage in the menu bar, iPhone pairing |-| 🐧 | **Linux** | Native GTK 4 / libadwaita | Runs the host (desktop or headless server), chat app |+| 💻 | **macOS** | Desktop app (Electron), menu bar + window | Runs the host, chat window, usage in the menu bar, iPhone pairing |+| 🐧 | **Linux** | Desktop app (Electron), tray + window | Chat window, iPhone pairing; the host runs on desktops and headless servers || ⌨️ | **Terminal** | `codync-host tui` | Message your bots from any terminal, over SSH too |The host (`codync-host`, Rust) runs on macOS and Linux; every client talks to it, so all your bots and chats are the same everywhere.@@ -96,7 +97,7 @@ Open Codync: it sets up the host on first launch. **Open Codync** opens the full> **Why the iPhone app can be a version behind:** every iPhone release goes through Apple's App Review first, which usually takes a day or more, so the App Store version can trail the Mac, Linux and host releases. Your computer accounts for that: an update that needs a newer iPhone app waits until that version is in the App Store, then installs, and the iPhone app shows a reminder when a newer version is available.-**Linux** — the host, plus the native GTK 4 / libadwaita app:+**Linux** — the host, plus the desktop app:```bashcurl -fsSL https://raw.githubusercontent.com/leepokai/Codync/main/packaging/install.sh | sh@@ -105,9 +106,9 @@ codync-host install # systemd --user servicecodync-host pair # QR code in the terminal, or Settings in the app```-The script also installs the desktop app (`codync`, with its `.desktop` file and icon) when you're in a graphical session; it needs GTK 4 and libadwaita. By hand: unpack `codync-linux-<arch>.tar.gz` from [Releases](https://github.com/leepokai/Codync/releases/latest) and run `bin/codync`.+The script also installs the desktop app (`codync`, an AppImage, with its `.desktop` file) when you're in a graphical session. By hand: `codync-linux-<arch>.AppImage`, `.deb` or `.tar.gz` from [Releases](https://github.com/leepokai/Codync/releases/latest).-Building the Linux app yourself needs `libgtk-4-dev libadwaita-1-dev`: `cargo install --path apps/linux`.+Building the desktop app yourself: `cd apps/desktop && npm ci && npm run dev`.**Linux server / cloud VM** — the host runs headless on any distro (static binary, x86_64 + arm64). Setup, remote access and limitations: [docs/guides/linux-servers.md](docs/guides/linux-servers.md).@@ -139,11 +140,10 @@ Data lives in `~/.codync`. The local bearer token authorizes loopback helpers an| Path | ||---|---|| `host/` | `codync-host` — Rust daemon: ACP client, SQLite transcript, HTTP/SSE API, push, usage |-| `kit/` | Swift package: `CodyncKit` (wire models, host client, theme, avatars) and `CodyncUI` (store + chat screens shared by iPhone and Mac) || `apps/ios/` | iOS app: pairing, roster, push, Live Activity glue |+| `apps/ios/Kit/` | The iPhone app's Swift package: `CodyncKit` (wire models, host client, theme, avatars; shared with the widgets) and `CodyncUI` (store + screens) || `apps/ios/Widgets/` | Bots, usage and per-provider usage widgets + bot Live Activity |-| `apps/macos/` | Menu bar + native chat window; installs/monitors the host |-| `apps/linux/` | Native Linux app (GTK 4 + libadwaita, Rust) |+| `apps/desktop/` | Desktop app for macOS and Linux (Electron, React, TypeScript): menu bar/tray + chat window; installs/monitors the host || `cloud/` | Cloudflare accounts, D1, encrypted channel relay and offline mailbox || `apps/shared/` | Shared Apple account integration and environment configuration || `apps/screen-macos/`, `apps/screen-linux/` | Platform screen capture/input helpers |@@ -158,12 +158,33 @@ The Xcode project is generated: `xcodegen generate --spec apps/project.yml`.```bashcd host && cargo test # host-cd kit && swift test # shared Swift-cd apps/linux && cargo test # Linux app (needs GTK dev packages)+cd apps/desktop && npm test # desktop app (also: npm run typecheck)+# iPhone package: xcodebuild test -scheme CodyncKit-Package (apps/ios/Kit, iOS Simulator)cd cloud && npm test # cloud API / channel relaycd relay && npm test # relay tickets```+## Changelog++### 2.7.0 — one desktop app for Mac and Linux++The SwiftUI Mac app and the GTK 4 Linux app are replaced by a single desktop app in+`apps/desktop/` (Electron). It looks and works like the Mac app it replaces: the same roster,+chat, inspector, marketplace, settings, menu bar, pairing, SSH computers, voice calls and+remote screen helper. Why: the native chat had become too slow to scroll and stream long+transcripts, and keeping two desktop apps in step took more than one person can maintain.+The iPhone app stays native SwiftUI; its shared package moved into `apps/ios/Kit/`.+Details: [desktop app](docs/architecture/desktop-app.md).++**Looking for the SwiftUI Mac app?** It's still in the Git history. The last version is the+parent of the commit that removed `apps/macos/`:++```bash+git log --oneline -1 -- apps/macos # the commit that removed it+git show <commit>^:apps/macos/Views/ChatWindow.swift+git worktree add ../codync-swiftui <commit>^ # a checkout of the whole SwiftUI-era repo+```+## VersioningThe major version is the phone ↔ host protocol: apps work with hosts of the same major version.diff --git a/apps/Codync.xcodeproj/project.pbxproj b/apps/Codync.xcodeproj/project.pbxprojindex c41c5b2f..bea6dfb3 100644--- a/apps/Codync.xcodeproj/project.pbxproj+++ b/apps/Codync.xcodeproj/project.pbxproj@@ -12,23 +12,17 @@0631979397E0D6822747E03A /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6E13F8EA6C7B0DA4D899FEE /* RootView.swift */; };0CFB5009A2A90DAA9DAF3293 /* ComputerStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = 772D2E6B5C5157077E504B35 /* ComputerStatus.swift */; };17DD96A91B1EC2AE699F4A2F /* ViewingBadge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C0E04490F5C56FD070539E6 /* ViewingBadge.swift */; };- 2244021EF712DF568374AB04 /* HostController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14B7967A8F027FF28EAEA893 /* HostController.swift */; };- 2299EC1A2CE18A03C8AF9A0A /* ComputerStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = 772D2E6B5C5157077E504B35 /* ComputerStatus.swift */; };- 24DF3CB466CC877FCB8BAED6 /* ClerkKit in Frameworks */ = {isa = PBXBuildFile; productRef = 7D524C19E9D41C0CF635A619 /* ClerkKit */; };25667EBFCCC64B96FDCE95A9 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 59F5D19A417A7A50596902FA /* CodyncKit */; };2CC074683AE086D6C77CC1E8 /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B274A0195CB3B2409EA4C194 /* WidgetKit.framework */; };2CDF3DF16A13DAF83CA42168 /* CodyncWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = FAB9BDB52C3A9F7B2568A750 /* CodyncWidgets.swift */; };3BCC04815E5CA8953E0DDCAD /* WidgetPreviews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 305DDCC18BB8AA6CD9D19CEF /* WidgetPreviews.swift */; };- 3C37D6D7D9C89E6AD3F5E04F /* AppIcon.icon in Resources */ = {isa = PBXBuildFile; fileRef = 7549E88A01FD7650C5746C54 /* AppIcon.icon */; };48DAAA1384E5B8D0BA27C895 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1E47C60032C326157E0386B8 /* SwiftUI.framework */; };4DDC38E58D673047B332FDD5 /* AccessRequestView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B97102DEC6029268332DF901 /* AccessRequestView.swift */; };501377099B6CF42761B230CB /* WelcomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D57A7C09154869DD84BACE19 /* WelcomeView.swift */; };52CF04B855C6AAEC47B75B8F /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1285DDFA0390A76ECDAAD6C0 /* CodyncKit */; };54CEEA0734C2940E2D9FAC7D /* AXTree.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4D13418ABB5FD7CFC087677 /* AXTree.swift */; };- 56D1B234EB2E4DE200BCA764 /* ChatWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = B71D3227DAFDD03155870401 /* ChatWindow.swift */; };674BCFBAC7022359FB673FDB /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = AD18A04CD014230F1B7B0535 /* PrivacyInfo.xcprivacy */; };684F7F77EECBA0BD95BDD658 /* UsageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFEBE2E6A9D0AF0A0D89FFE7 /* UsageView.swift */; };- 68C9357B769268E8FA5BC746 /* AccountSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DF2F130F22D2672B7747474 /* AccountSession.swift */; };719EABCBBAC0A973D729363A /* PairingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECD0B4EA4BBA2BB2826C4362 /* PairingView.swift */; };72A907055F1AAEF8F10EAD72 /* NotificationService.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 7B7E845BA1B8696B266CF578 /* NotificationService.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };75C4B7F344DF1E52A1EADEFC /* Capture.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE63C84233B14A2D63640EAA /* Capture.swift */; };@@ -38,41 +32,23 @@8517F8FC5AFAFF1527369829 /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6932F782C1B87C9608359A6 /* NotificationService.swift */; };89CA3972915769DBA315876F /* Push.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3BF4D3B82FE8274F610C703 /* Push.swift */; };8BB3FC79EB798CE4347E6FD3 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 50F314172CC2AD1C5CDC916A /* CodyncKit */; };- 8D83C54A832018932F7261DE /* ComputersView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F70117FA3097C5A6F28C89B /* ComputersView.swift */; };921ED46A1643AB90BB3D4CF7 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = F99C11684BFBEB49006600A9 /* Session.swift */; };- 92AA18FF5A35A96864AE1184 /* com.pokai.Codync.screen.plist in CopyFiles */ = {isa = PBXBuildFile; fileRef = 08D070CB1CE05D4848C09C52 /* com.pokai.Codync.screen.plist */; };9638BAA981354C4CE72884A0 /* HostLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CC3E47D480A5F15CA95C504 /* HostLink.swift */; };974A5D8D89758A61E7D8D1B6 /* Input.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BA06CEE98A7CDED62678522 /* Input.swift */; };9BBB2FAEDBD35A83EAB02981 /* AccountSwitcherView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EB282B31FBC94EE70D07638 /* AccountSwitcherView.swift */; };A81CCD9288B1F54D9BB145EC /* AccountSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DF2F130F22D2672B7747474 /* AccountSession.swift */; };AA601649E43A5AF73DCF5B5E /* WebRTC in Frameworks */ = {isa = PBXBuildFile; productRef = 2D9748E611692583AFC5A152 /* WebRTC */; };- ADA06AC9F6CD98F58F77D364 /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = BEE30A9D5C73E5A151F34180 /* CodyncUI */; };- AF21AAA6549D150D18C8927F /* UpdatesManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = B08914B44558AFBF93C2E671 /* UpdatesManager.swift */; };B3554D38F39916698E961A37 /* WidgetGalleryView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B22589689593E0089118FDB /* WidgetGalleryView.swift */; };- B4373612F918A3158E69A8E3 /* SSHTunnel.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0DEB8851CB0D546BF93F830 /* SSHTunnel.swift */; };- B7306D54C75E4A20E61142D0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 5A6F0E1B9F75DA969F30E790 /* Assets.xcassets */; };- B8B86B2B7F8D9EE8639A9E09 /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 80868F96B9905FF52DCDFAE2 /* CodyncKit */; };BA978F06CB1E58511FFB541B /* WidgetSetupDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D8961FADA8810B6CC479705 /* WidgetSetupDemo.swift */; };BF77DD7946621D8818EDAB9B /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A87B0091DAF0E4807D62017 /* SettingsView.swift */; };- C263D5693212EB0812A232D9 /* CodyncMacApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AB018B7D7F8E8137E0A1012 /* CodyncMacApp.swift */; };C7ED489193AC0934515D2E85 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = D0DE72EEAEC947C1D3CA237F /* PrivacyInfo.xcprivacy */; };- D51C32451FB38C337707E3A5 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 124AB371AB16E5E232DE0A07 /* SettingsView.swift */; };EBB0417A5FB2CE6D514D21BE /* ClerkKit in Frameworks */ = {isa = PBXBuildFile; productRef = D9AB2F442A5F243653EAE936 /* ClerkKit */; };- EC14C7513A8D2999D97D5ABA /* Screen.app in Embed Dependencies */ = {isa = PBXBuildFile; fileRef = 741B706007BA1B91CB853699 /* Screen.app */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };F171F16563D1FF6308697173 /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = 06C9F37C6502131CAF0F145E /* CodyncUI */; };F842AE1C5ED96AF9A7F5D16C /* Widgets.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 6D734BEE7CD3F84677B0218B /* Widgets.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };- F93D9960F7C20B2E629C1736 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = AF460014351882D22C34DAA7 /* Sparkle */; };F97C489DDB806224CEFCEB57 /* ScreenHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28B2CB561A43ED9F2F1A4391 /* ScreenHelper.swift */; };/* End PBXBuildFile section *//* Begin PBXContainerItemProxy section */- 2E0B0CAFDFEF730B8269AE49 /* PBXContainerItemProxy */ = {- isa = PBXContainerItemProxy;- containerPortal = 5B6351DD20AF4506794D6460 /* Project object */;- proxyType = 1;- remoteGlobalIDString = 907F1F4A709111FC7178EAE9;- remoteInfo = Screen;- };D40A213F2C1B900F886F95EB /* PBXContainerItemProxy */ = {isa = PBXContainerItemProxy;containerPortal = 5B6351DD20AF4506794D6460 /* Project object */;@@ -102,71 +78,37 @@name = "Embed Foundation Extensions";runOnlyForDeploymentPostprocessing = 0;};- A39B341E188CE8DB0A29ACC0 /* Embed Dependencies */ = {- isa = PBXCopyFilesBuildPhase;- buildActionMask = 2147483647;- dstPath = Contents/Library/LoginItems;- dstSubfolderSpec = 1;- files = (- EC14C7513A8D2999D97D5ABA /* Screen.app in Embed Dependencies */,- );- name = "Embed Dependencies";- runOnlyForDeploymentPostprocessing = 0;- };- F03A20C030394F9A65472B30 /* CopyFiles */ = {- isa = PBXCopyFilesBuildPhase;- buildActionMask = 2147483647;- dstPath = Contents/Library/LaunchAgents;- dstSubfolderSpec = 1;- files = (- 92AA18FF5A35A96864AE1184 /* com.pokai.Codync.screen.plist in CopyFiles */,- );- runOnlyForDeploymentPostprocessing = 0;- };/* End PBXCopyFilesBuildPhase section *//* Begin PBXFileReference section */0582B6169BFC36E4BCD51C0D /* BotListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotListView.swift; sourceTree = "<group>"; };0829A4FCADAC108E8C2DB2F1 /* Widgets.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Widgets.entitlements; sourceTree = "<group>"; };- 08D070CB1CE05D4848C09C52 /* com.pokai.Codync.screen.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = com.pokai.Codync.screen.plist; sourceTree = "<group>"; };0A87B0091DAF0E4807D62017 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };- 124AB371AB16E5E232DE0A07 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };1318104275E5BEC47B7088AD /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };- 14B7967A8F027FF28EAEA893 /* HostController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostController.swift; sourceTree = "<group>"; };1E47C60032C326157E0386B8 /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; };28B2CB561A43ED9F2F1A4391 /* ScreenHelper.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScreenHelper.swift; sourceTree = "<group>"; };2C0E04490F5C56FD070539E6 /* ViewingBadge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewingBadge.swift; sourceTree = "<group>"; };2DF2F130F22D2672B7747474 /* AccountSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountSession.swift; sourceTree = "<group>"; };305DDCC18BB8AA6CD9D19CEF /* WidgetPreviews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetPreviews.swift; sourceTree = "<group>"; };+ 3F4C4D3B64C608AEF2F85F91 /* Kit */ = {isa = PBXFileReference; lastKnownFileType = folder; name = Kit; path = ios/Kit; sourceTree = SOURCE_ROOT; };4815867922559696EDCA47FD /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };4EB282B31FBC94EE70D07638 /* AccountSwitcherView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountSwitcherView.swift; sourceTree = "<group>"; };52A96030D47F1B9678095909 /* iOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = iOS.entitlements; sourceTree = "<group>"; };- 5A6F0E1B9F75DA969F30E790 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };5B22589689593E0089118FDB /* WidgetGalleryView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetGalleryView.swift; sourceTree = "<group>"; };- 5D8E24CB8B64ED897CAEC580 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };60422D3CA8FEBCDC5AC465E0 /* iOS.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = iOS.app; sourceTree = BUILT_PRODUCTS_DIR; };64888B10E98F19723500FBCA /* NotificationService.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = NotificationService.entitlements; sourceTree = "<group>"; };6D734BEE7CD3F84677B0218B /* Widgets.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = Widgets.appex; sourceTree = BUILT_PRODUCTS_DIR; };741B706007BA1B91CB853699 /* Screen.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Screen.app; sourceTree = BUILT_PRODUCTS_DIR; };- 7549E88A01FD7650C5746C54 /* AppIcon.icon */ = {isa = PBXFileReference; path = AppIcon.icon; sourceTree = "<group>"; };772D2E6B5C5157077E504B35 /* ComputerStatus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComputerStatus.swift; sourceTree = "<group>"; };- 7A2F5A7F5A648909D8CC5C19 /* kit */ = {isa = PBXFileReference; lastKnownFileType = folder; name = kit; path = ../kit; sourceTree = SOURCE_ROOT; };- 7AB018B7D7F8E8137E0A1012 /* CodyncMacApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncMacApp.swift; sourceTree = "<group>"; };7B7E845BA1B8696B266CF578 /* NotificationService.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = NotificationService.appex; sourceTree = BUILT_PRODUCTS_DIR; };7D8961FADA8810B6CC479705 /* WidgetSetupDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetSetupDemo.swift; sourceTree = "<group>"; };8BA06CEE98A7CDED62678522 /* Input.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Input.swift; sourceTree = "<group>"; };8CC3E47D480A5F15CA95C504 /* HostLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostLink.swift; sourceTree = "<group>"; };- 991A0FD3EAAD4B446F3BF14E /* macOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = macOS.app; sourceTree = BUILT_PRODUCTS_DIR; };9AD0BD16672E128A4F26272B /* SignInButtons.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SignInButtons.swift; sourceTree = "<group>"; };- 9F70117FA3097C5A6F28C89B /* ComputersView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComputersView.swift; sourceTree = "<group>"; };A65FE0504B741D0B44DB2516 /* CodyncApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncApp.swift; sourceTree = "<group>"; };AD18A04CD014230F1B7B0535 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };- B08914B44558AFBF93C2E671 /* UpdatesManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdatesManager.swift; sourceTree = "<group>"; };- B0DEB8851CB0D546BF93F830 /* SSHTunnel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHTunnel.swift; sourceTree = "<group>"; };- B19BCCF4FC316502CA90AF3F /* macOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = macOS.entitlements; sourceTree = "<group>"; };B274A0195CB3B2409EA4C194 /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; };B6E13F8EA6C7B0DA4D899FEE /* RootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = "<group>"; };- B71D3227DAFDD03155870401 /* ChatWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatWindow.swift; sourceTree = "<group>"; };B97102DEC6029268332DF901 /* AccessRequestView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccessRequestView.swift; sourceTree = "<group>"; };CE63C84233B14A2D63640EAA /* Capture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Capture.swift; sourceTree = "<group>"; };CFEBE2E6A9D0AF0A0D89FFE7 /* UsageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageView.swift; sourceTree = "<group>"; };@@ -184,17 +126,6 @@/* End PBXFileReference section *//* Begin PBXFrameworksBuildPhase section */- 1AC8A5FB72DF4C3DAEDBA56F /* Frameworks */ = {- isa = PBXFrameworksBuildPhase;- buildActionMask = 2147483647;- files = (- F93D9960F7C20B2E629C1736 /* Sparkle in Frameworks */,- 24DF3CB466CC877FCB8BAED6 /* ClerkKit in Frameworks */,- B8B86B2B7F8D9EE8639A9E09 /* CodyncKit in Frameworks */,- ADA06AC9F6CD98F58F77D364 /* CodyncUI in Frameworks */,- );- runOnlyForDeploymentPostprocessing = 0;- };9BF4C7DD5C26BAD44BD453BF /* Frameworks */ = {isa = PBXFrameworksBuildPhase;buildActionMask = 2147483647;@@ -234,28 +165,6 @@/* End PBXFrameworksBuildPhase section *//* Begin PBXGroup section */- 0C9ED805690F5F321E1C2C97 /* Resources */ = {- isa = PBXGroup;- children = (- 7549E88A01FD7650C5746C54 /* AppIcon.icon */,- 5A6F0E1B9F75DA969F30E790 /* Assets.xcassets */,- 5D8E24CB8B64ED897CAEC580 /* Info.plist */,- B19BCCF4FC316502CA90AF3F /* macOS.entitlements */,- );- path = Resources;- sourceTree = "<group>";- };- 1783562DCB0F9E8E2186F4A0 /* App */ = {- isa = PBXGroup;- children = (- 7AB018B7D7F8E8137E0A1012 /* CodyncMacApp.swift */,- 14B7967A8F027FF28EAEA893 /* HostController.swift */,- B0DEB8851CB0D546BF93F830 /* SSHTunnel.swift */,- B08914B44558AFBF93C2E671 /* UpdatesManager.swift */,- );- path = App;- sourceTree = "<group>";- };39BD6D06FC3DE74E5AA24856 /* Resources */ = {isa = PBXGroup;children = (@@ -279,7 +188,6 @@isa = PBXGroup;children = (60422D3CA8FEBCDC5AC465E0 /* iOS.app */,- 991A0FD3EAAD4B446F3BF14E /* macOS.app */,7B7E845BA1B8696B266CF578 /* NotificationService.appex */,741B706007BA1B91CB853699 /* Screen.app */,6D734BEE7CD3F84677B0218B /* Widgets.appex */,@@ -306,14 +214,6 @@path = Widgets;sourceTree = "<group>";};- 618253CDFCE9BBB7DF5C4C3E /* LaunchAgents */ = {- isa = PBXGroup;- children = (- 08D070CB1CE05D4848C09C52 /* com.pokai.Codync.screen.plist */,- );- path = LaunchAgents;- sourceTree = "<group>";- };64D176A915A00A2E5FB10F5B /* Views */ = {isa = PBXGroup;children = (@@ -333,17 +233,6 @@path = Views;sourceTree = "<group>";};- 655004E37EA6A354229431F0 /* macos */ = {- isa = PBXGroup;- children = (- 1783562DCB0F9E8E2186F4A0 /* App */,- 618253CDFCE9BBB7DF5C4C3E /* LaunchAgents */,- 0C9ED805690F5F321E1C2C97 /* Resources */,- EAAB62E0536250B727076FAD /* Views */,- );- path = macos;- sourceTree = "<group>";- };75D64C75DA194CAF10294493 /* ios */ = {isa = PBXGroup;children = (@@ -383,7 +272,7 @@AD54741A2330C502CD3BB628 /* Packages */ = {isa = PBXGroup;children = (- 7A2F5A7F5A648909D8CC5C19 /* kit */,+ 3F4C4D3B64C608AEF2F85F91 /* Kit */,);name = Packages;sourceTree = "<group>";@@ -403,7 +292,6 @@isa = PBXGroup;children = (75D64C75DA194CAF10294493 /* ios */,- 655004E37EA6A354229431F0 /* macos */,AD54741A2330C502CD3BB628 /* Packages */,95C8CE71ADF48ACFE026A1AF /* screen-macos */,53A9086E104FF26B9CE6C08F /* shared */,@@ -412,16 +300,6 @@);sourceTree = "<group>";};- EAAB62E0536250B727076FAD /* Views */ = {- isa = PBXGroup;- children = (- B71D3227DAFDD03155870401 /* ChatWindow.swift */,- 9F70117FA3097C5A6F28C89B /* ComputersView.swift */,- 124AB371AB16E5E232DE0A07 /* SettingsView.swift */,- );- path = Views;- sourceTree = "<group>";- };F25D9D57F88C5EFD30A30920 /* App */ = {isa = PBXGroup;children = (@@ -434,34 +312,6 @@/* End PBXGroup section *//* Begin PBXNativeTarget section */- 72F29E7EBE9A88B16B4E608A /* macOS */ = {- isa = PBXNativeTarget;- buildConfigurationList = 7C0003BA8C173EC41757B9B4 /* Build configuration list for PBXNativeTarget "macOS" */;- buildPhases = (- FD97D0661DD7AA54EB7DE077 /* Sources */,- 14FEC4FC6C72AC9A2596C04C /* Resources */,- F03A20C030394F9A65472B30 /* CopyFiles */,- 1AC8A5FB72DF4C3DAEDBA56F /* Frameworks */,- A39B341E188CE8DB0A29ACC0 /* Embed Dependencies */,- 7471650ADCC84E2BBDF4E47C /* Codync environment */,- C0A14ED49FC6A533FEABD5B2 /* Embed codync-host */,- );- buildRules = (- );- dependencies = (- 403D98EE1C95EF3BA01D41CB /* PBXTargetDependency */,- );- name = macOS;- packageProductDependencies = (- AF460014351882D22C34DAA7 /* Sparkle */,- 7D524C19E9D41C0CF635A619 /* ClerkKit */,- 80868F96B9905FF52DCDFAE2 /* CodyncKit */,- BEE30A9D5C73E5A151F34180 /* CodyncUI */,- );- productName = macOS;- productReference = 991A0FD3EAAD4B446F3BF14E /* macOS.app */;- productType = "com.apple.product-type.application";- };907F1F4A709111FC7178EAE9 /* Screen */ = {isa = PBXNativeTarget;buildConfigurationList = EC3A304F5821443C1DD50876 /* Build configuration list for PBXNativeTarget "Screen" */;@@ -555,10 +405,6 @@BuildIndependentTargetsInParallel = YES;LastUpgradeCheck = 1430;TargetAttributes = {- 72F29E7EBE9A88B16B4E608A = {- DevelopmentTeam = 7FUM8A8H72;- ProvisioningStyle = Automatic;- };907F1F4A709111FC7178EAE9 = {DevelopmentTeam = 7FUM8A8H72;ProvisioningStyle = Automatic;@@ -589,9 +435,8 @@minimizedProjectReferenceProxies = 1;packageReferences = (2C830647014432C6F20C557C /* XCRemoteSwiftPackageReference "clerk-ios" */,- 3A835D8D18E836C121D811E0 /* XCRemoteSwiftPackageReference "Sparkle" */,979123F21565A4068586B502 /* XCRemoteSwiftPackageReference "WebRTC" */,- 4821371032224740E592D19C /* XCLocalSwiftPackageReference "../kit" */,+ 1971A679A8497DA8D0C8B77A /* XCLocalSwiftPackageReference "ios/Kit" */,);preferredProjectObjectVersion = 77;projectDirPath = "";@@ -601,21 +446,11 @@907F1F4A709111FC7178EAE9 /* Screen */,A27E4E88D6A5B9850734B594 /* Widgets */,913BDA9F79CE8C35A9E35830 /* iOS */,- 72F29E7EBE9A88B16B4E608A /* macOS */,);};/* End PBXProject section *//* Begin PBXResourcesBuildPhase section */- 14FEC4FC6C72AC9A2596C04C /* Resources */ = {- isa = PBXResourcesBuildPhase;- buildActionMask = 2147483647;- files = (- 3C37D6D7D9C89E6AD3F5E04F /* AppIcon.icon in Resources */,- B7306D54C75E4A20E61142D0 /* Assets.xcassets in Resources */,- );- runOnlyForDeploymentPostprocessing = 0;- };8C91DA62A73BD91999C1FD70 /* Resources */ = {isa = PBXResourcesBuildPhase;buildActionMask = 2147483647;@@ -636,26 +471,6 @@/* End PBXResourcesBuildPhase section *//* Begin PBXShellScriptBuildPhase section */- 7471650ADCC84E2BBDF4E47C /* Codync environment */ = {- isa = PBXShellScriptBuildPhase;- alwaysOutOfDate = 1;- buildActionMask = 2147483647;- files = (- );- inputFileListPaths = (- );- inputPaths = (- );- name = "Codync environment";- outputFileListPaths = (- );- outputPaths = (- );- runOnlyForDeploymentPostprocessing = 0;- shellPath = /bin/sh;- shellScript = "# Debug builds use dev (dev-api.codync.dev), Release builds use main (api.codync.dev).\ncp \"$SRCROOT/shared/Config/$CODYNC_ENV.plist\" \"$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/AccountConfig.plist\"\n";- showEnvVarsInLog = 0;- };9900BE8858E71975C4052787 /* Codync environment */ = {isa = PBXShellScriptBuildPhase;alwaysOutOfDate = 1;@@ -676,26 +491,6 @@shellScript = "# Debug builds use dev (dev-api.codync.dev), Release builds use main (api.codync.dev).\ncp \"$SRCROOT/shared/Config/$CODYNC_ENV.plist\" \"$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/AccountConfig.plist\"\n";showEnvVarsInLog = 0;};- C0A14ED49FC6A533FEABD5B2 /* Embed codync-host */ = {- isa = PBXShellScriptBuildPhase;- alwaysOutOfDate = 1;- buildActionMask = 2147483647;- files = (- );- inputFileListPaths = (- );- inputPaths = (- );- name = "Embed codync-host";- outputFileListPaths = (- );- outputPaths = (- );- runOnlyForDeploymentPostprocessing = 0;- shellPath = /bin/sh;- shellScript = "# Builds the Rust host and ships it inside Codync.app/Contents/MacOS.\nexport PATH=\"$HOME/.cargo/bin:/opt/homebrew/bin:/usr/local/bin:$PATH\"\nif ! command -v cargo >/dev/null; then\n echo \"warning: cargo not found; Codync.app will look for codync-host on PATH instead\"\n exit 0\nfi\nPROFILE=release\n[ \"$CONFIGURATION\" = \"Debug\" ] && PROFILE=debug\nFLAGS=\"\"\n[ \"$PROFILE\" = \"release\" ] && FLAGS=\"--release\"\nif [ \"$PROFILE\" = \"release\" ]; then\n rustup target add aarch64-apple-darwin x86_64-apple-darwin >/dev/null 2>&1 || true\n cargo build --release --manifest-path \"$SRCROOT/../host/Cargo.toml\" --target aarch64-apple-darwin &&\n cargo build --release --manifest-path \"$SRCROOT/../host/Cargo.toml\" --target x86_64-apple-darwin &&\n lipo -create -output \"$SRCROOT/../host/target/codync-host-universal\" \\\n \"$SRCROOT/../host/target/aarch64-apple-darwin/release/codync-host\" \\\n \"$SRCROOT/../host/target/x86_64-apple-darwin/release/codync-host\" &&\n BIN=\"$SRCROOT/../host/target/codync-host-universal\" ||\n { cargo build --release --manifest-path \"$SRCROOT/../host/Cargo.toml\" && BIN=\"$SRCROOT/../host/target/release/codync-host\"; }\nelse\n cargo build --manifest-path \"$SRCROOT/../host/Cargo.toml\" && BIN=\"$SRCROOT/../host/target/debug/codync-host\"\nfi\n[ -n \"$BIN\" ] || { echo \"error: building codync-host failed\"; exit 1; }\nDEST=\"$TARGET_BUILD_DIR/$EXECUTABLE_FOLDER_PATH/codync-host\"\ncp \"$BIN\" \"$DEST\"\nif [ -n \"$EXPANDED_CODE_SIGN_IDENTITY\" ] && [ \"$CODE_SIGNING_ALLOWED\" != \"NO\" ]; then\n codesign --force --options runtime --timestamp=none --sign \"$EXPANDED_CODE_SIGN_IDENTITY\" \"$DEST\"\nfi\n";- showEnvVarsInLog = 0;- };/* End PBXShellScriptBuildPhase section *//* Begin PBXSourcesBuildPhase section */@@ -753,22 +548,6 @@);runOnlyForDeploymentPostprocessing = 0;};- FD97D0661DD7AA54EB7DE077 /* Sources */ = {- isa = PBXSourcesBuildPhase;- buildActionMask = 2147483647;- files = (- 68C9357B769268E8FA5BC746 /* AccountSession.swift in Sources */,- 56D1B234EB2E4DE200BCA764 /* ChatWindow.swift in Sources */,- C263D5693212EB0812A232D9 /* CodyncMacApp.swift in Sources */,- 2299EC1A2CE18A03C8AF9A0A /* ComputerStatus.swift in Sources */,- 8D83C54A832018932F7261DE /* ComputersView.swift in Sources */,- 2244021EF712DF568374AB04 /* HostController.swift in Sources */,- B4373612F918A3158E69A8E3 /* SSHTunnel.swift in Sources */,- D51C32451FB38C337707E3A5 /* SettingsView.swift in Sources */,- AF21AAA6549D150D18C8927F /* UpdatesManager.swift in Sources */,- );- runOnlyForDeploymentPostprocessing = 0;- };/* End PBXSourcesBuildPhase section *//* Begin PBXTargetDependency section */@@ -777,11 +556,6 @@target = C42E5E078332C6C2B35AF5FA /* NotificationService */;targetProxy = DA04088A6786CD5F92C67AED /* PBXContainerItemProxy */;};- 403D98EE1C95EF3BA01D41CB /* PBXTargetDependency */ = {- isa = PBXTargetDependency;- target = 907F1F4A709111FC7178EAE9 /* Screen */;- targetProxy = 2E0B0CAFDFEF730B8269AE49 /* PBXContainerItemProxy */;- };40DF4BEA40A82C095F51AB76 /* PBXTargetDependency */ = {isa = PBXTargetDependency;target = A27E4E88D6A5B9850734B594 /* Widgets */;@@ -854,33 +628,6 @@};name = Release;};- 57C9A2C8FA6B1E9F990016F9 /* Debug */ = {- isa = XCBuildConfiguration;- buildSettings = {- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;- ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;- CODE_SIGN_ENTITLEMENTS = macos/Resources/macOS.entitlements;- COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = "$(MARKETING_VERSION)";- ENABLE_APP_SANDBOX = NO;- ENABLE_HARDENED_RUNTIME = YES;- GENERATE_INFOPLIST_FILE = YES;- INFOPLIST_FILE = macos/Resources/Info.plist;- INFOPLIST_KEY_CFBundleDisplayName = Codync;- INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";- INFOPLIST_KEY_NSHumanReadableCopyright = "";- INFOPLIST_KEY_NSMicrophoneUsageDescription = "Talk to your bots in a voice call.";- INFOPLIST_KEY_NSSpeechRecognitionUsageDescription = "Your words are transcribed on this Mac and sent to your bot as a message.";- LD_RUNPATH_SEARCH_PATHS = (- "$(inherited)",- "@executable_path/../Frameworks",- );- PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync;- PRODUCT_NAME = Codync;- SDKROOT = macosx;- };- name = Debug;- };6377E0B7DC2015DD92AB6550 /* Debug */ = {isa = XCBuildConfiguration;buildSettings = {@@ -1142,33 +889,6 @@};name = Release;};- F1C857613730023CBDC70E38 /* Release */ = {- isa = XCBuildConfiguration;- buildSettings = {- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;- ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;- CODE_SIGN_ENTITLEMENTS = macos/Resources/macOS.entitlements;- COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = "$(MARKETING_VERSION)";- ENABLE_APP_SANDBOX = NO;- ENABLE_HARDENED_RUNTIME = YES;- GENERATE_INFOPLIST_FILE = YES;- INFOPLIST_FILE = macos/Resources/Info.plist;- INFOPLIST_KEY_CFBundleDisplayName = Codync;- INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";- INFOPLIST_KEY_NSHumanReadableCopyright = "";- INFOPLIST_KEY_NSMicrophoneUsageDescription = "Talk to your bots in a voice call.";- INFOPLIST_KEY_NSSpeechRecognitionUsageDescription = "Your words are transcribed on this Mac and sent to your bot as a message.";- LD_RUNPATH_SEARCH_PATHS = (- "$(inherited)",- "@executable_path/../Frameworks",- );- PRODUCT_BUNDLE_IDENTIFIER = com.pokai.Codync;- PRODUCT_NAME = Codync;- SDKROOT = macosx;- };- name = Release;- };/* End XCBuildConfiguration section *//* Begin XCConfigurationList section */@@ -1181,15 +901,6 @@defaultConfigurationIsVisible = 0;defaultConfigurationName = Debug;};- 7C0003BA8C173EC41757B9B4 /* Build configuration list for PBXNativeTarget "macOS" */ = {- isa = XCConfigurationList;- buildConfigurations = (- 57C9A2C8FA6B1E9F990016F9 /* Debug */,- F1C857613730023CBDC70E38 /* Release */,- );- defaultConfigurationIsVisible = 0;- defaultConfigurationName = Debug;- };95CAB203C65D7CF3F8C9B90E /* Build configuration list for PBXNativeTarget "Widgets" */ = {isa = XCConfigurationList;buildConfigurations = (@@ -1229,9 +940,9 @@/* End XCConfigurationList section *//* Begin XCLocalSwiftPackageReference section */- 4821371032224740E592D19C /* XCLocalSwiftPackageReference "../kit" */ = {+ 1971A679A8497DA8D0C8B77A /* XCLocalSwiftPackageReference "ios/Kit" */ = {isa = XCLocalSwiftPackageReference;- relativePath = ../kit;+ relativePath = ios/Kit;};/* End XCLocalSwiftPackageReference section */@@ -1244,14 +955,6 @@version = 1.5.6;};};- 3A835D8D18E836C121D811E0 /* XCRemoteSwiftPackageReference "Sparkle" */ = {- isa = XCRemoteSwiftPackageReference;- repositoryURL = "https://github.com/sparkle-project/Sparkle";- requirement = {- kind = exactVersion;- version = 2.10.0;- };- };979123F21565A4068586B502 /* XCRemoteSwiftPackageReference "WebRTC" */ = {isa = XCRemoteSwiftPackageReference;repositoryURL = "https://github.com/stasel/WebRTC";@@ -1284,24 +987,6 @@isa = XCSwiftPackageProductDependency;productName = CodyncKit;};- 7D524C19E9D41C0CF635A619 /* ClerkKit */ = {- isa = XCSwiftPackageProductDependency;- package = 2C830647014432C6F20C557C /* XCRemoteSwiftPackageReference "clerk-ios" */;- productName = ClerkKit;- };- 80868F96B9905FF52DCDFAE2 /* CodyncKit */ = {- isa = XCSwiftPackageProductDependency;- productName = CodyncKit;- };- AF460014351882D22C34DAA7 /* Sparkle */ = {- isa = XCSwiftPackageProductDependency;- package = 3A835D8D18E836C121D811E0 /* XCRemoteSwiftPackageReference "Sparkle" */;- productName = Sparkle;- };- BEE30A9D5C73E5A151F34180 /* CodyncUI */ = {- isa = XCSwiftPackageProductDependency;- productName = CodyncUI;- };D9AB2F442A5F243653EAE936 /* ClerkKit */ = {isa = XCSwiftPackageProductDependency;package = 2C830647014432C6F20C557C /* XCRemoteSwiftPackageReference "clerk-ios" */;diff --git a/apps/Codync.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/apps/Codync.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex 46157b3d..6d5e60c6 100644--- a/apps/Codync.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/apps/Codync.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -1,5 +1,5 @@{- "originHash" : "eeae096a19644f764cb7e1451017412c7bb2c310ea1686dc71ef0b7959688a0d",+ "originHash" : "6b5dcf803e39947a013de836e5cdccdbb68820d48c2749e9ce1d635db0b2af67","pins" : [{"identity" : "clerk-ios",@@ -28,15 +28,6 @@"version" : "5.0.11"}},- {- "identity" : "sparkle",- "kind" : "remoteSourceControl",- "location" : "https://github.com/sparkle-project/Sparkle",- "state" : {- "revision" : "eef1a539a373c1f1a320624b1130fc5de7b2e100",- "version" : "2.10.0"- }- },{"identity" : "swift-argument-parser","kind" : "remoteSourceControl",diff --git a/kit/Package.swift b/apps/ios/Kit/Package.swiftsimilarity index 96%rename from kit/Package.swiftrename to apps/ios/Kit/Package.swiftindex aabbdb66..2ec356dc 100644--- a/kit/Package.swift+++ b/apps/ios/Kit/Package.swift@@ -3,7 +3,7 @@ import PackageDescriptionlet package = Package(name: "CodyncKit",- platforms: [.macOS(.v14), .iOS(.v17)],+ platforms: [.iOS(.v17)],products: [.library(name: "CodyncKit", targets: ["CodyncKit"]),.library(name: "CodyncUI", targets: ["CodyncUI"]),diff --git a/kit/Sources/CodyncKit/Client/ChannelTransport.swift b/apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Client/ChannelTransport.swiftrename to apps/ios/Kit/Sources/CodyncKit/Client/ChannelTransport.swiftdiff --git a/kit/Sources/CodyncKit/Client/CloudClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Client/CloudClient.swiftrename to apps/ios/Kit/Sources/CodyncKit/Client/CloudClient.swiftdiff --git a/kit/Sources/CodyncKit/Client/DeviceIdentity.swift b/apps/ios/Kit/Sources/CodyncKit/Client/DeviceIdentity.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Client/DeviceIdentity.swiftrename to apps/ios/Kit/Sources/CodyncKit/Client/DeviceIdentity.swiftdiff --git a/kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Client/HostClient.swiftrename to apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swiftdiff --git a/kit/Sources/CodyncKit/Client/HostConnector.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Client/HostConnector.swiftrename to apps/ios/Kit/Sources/CodyncKit/Client/HostConnector.swiftdiff --git a/kit/Sources/CodyncKit/Client/HostTransport.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostTransport.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Client/HostTransport.swiftrename to apps/ios/Kit/Sources/CodyncKit/Client/HostTransport.swiftdiff --git a/kit/Sources/CodyncKit/Client/Pairing.swift b/apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Client/Pairing.swiftrename to apps/ios/Kit/Sources/CodyncKit/Client/Pairing.swiftdiff --git a/kit/Sources/CodyncKit/Client/RelayCrypto.swift b/apps/ios/Kit/Sources/CodyncKit/Client/RelayCrypto.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Client/RelayCrypto.swiftrename to apps/ios/Kit/Sources/CodyncKit/Client/RelayCrypto.swiftdiff --git a/kit/Sources/CodyncKit/Client/SharedStore.swift b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Client/SharedStore.swiftrename to apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swiftdiff --git a/kit/Sources/CodyncKit/Client/Tailscale.swift b/apps/ios/Kit/Sources/CodyncKit/Client/Tailscale.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Client/Tailscale.swiftrename to apps/ios/Kit/Sources/CodyncKit/Client/Tailscale.swiftdiff --git a/kit/Sources/CodyncKit/Design/AccessoryWidgetCard.swift b/apps/ios/Kit/Sources/CodyncKit/Design/AccessoryWidgetCard.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Design/AccessoryWidgetCard.swiftrename to apps/ios/Kit/Sources/CodyncKit/Design/AccessoryWidgetCard.swiftdiff --git a/kit/Sources/CodyncKit/Design/ActivityCards.swift b/apps/ios/Kit/Sources/CodyncKit/Design/ActivityCards.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Design/ActivityCards.swiftrename to apps/ios/Kit/Sources/CodyncKit/Design/ActivityCards.swiftdiff --git a/kit/Sources/CodyncKit/Design/AppFont.swift b/apps/ios/Kit/Sources/CodyncKit/Design/AppFont.swiftsimilarity index 76%rename from kit/Sources/CodyncKit/Design/AppFont.swiftrename to apps/ios/Kit/Sources/CodyncKit/Design/AppFont.swiftindex f389dc14..3910a300 100644--- a/kit/Sources/CodyncKit/Design/AppFont.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Design/AppFont.swift@@ -1,7 +1,4 @@import SwiftUI-#if os(macOS)-import AppKit-#endif/// Keeps each font's hierarchy and styling while applying the Mac text preference.public struct AppFont: Sendable {@@ -33,19 +30,11 @@ public struct AppFont: Sendable {/// Codync's existing compact desktop fonts; phones retain their semantic fonts.public static var compactBody: Self {- #if os(macOS)- system(size: 12)- #elsebody- #endif}public static var compactSecondary: Self {- #if os(macOS)- system(size: 11)- #elsesubheadline- #endif}public static func system(size: CGFloat, weight: Font.Weight? = nil, design: Font.Design? = nil) -> Self {@@ -88,17 +77,7 @@ public struct AppFont: Sendable {}func scaled(by scale: CGFloat) -> Font {- #if os(macOS)- guard scale != 1 else { return original }- if #available(macOS 26, *) {- // Semantic scaling rounds to quarter points; the preference also- // scales explicit point fonts, so retain their exact relative size.- return original.scaled(by: scale).pointSize(pointSize * scale)- }- return fallbackScaled(by: scale)- #elsereturn original- #endif}/// macOS 14–15 lack Font.scaled(by:); recreate the native font with its traits.@@ -108,25 +87,7 @@ public struct AppFont: Sendable {}private static func semantic(_ style: Font.TextStyle) -> Self {- #if os(macOS)- let nativeStyle: NSFont.TextStyle- switch style {- case .largeTitle: nativeStyle = .largeTitle- case .title: nativeStyle = .title1- case .title2: nativeStyle = .title2- case .title3: nativeStyle = .title3- case .headline: nativeStyle = .headline- case .subheadline: nativeStyle = .subheadline- case .callout: nativeStyle = .callout- case .footnote: nativeStyle = .footnote- case .caption: nativeStyle = .caption1- case .caption2: nativeStyle = .caption2- default: nativeStyle = .body- }- let size = NSFont.preferredFont(forTextStyle: nativeStyle, options: [:]).pointSize- #elselet size: CGFloat = 0 // Only used by the Mac fallback.- #endifvar font = Self(.system(style), size: size, weight: style == .headline ? .bold : .regular)// Native .bold() uses semibold for small semantic text and bold for// titles/headlines. An explicit .weight(.bold) remains explicit bold.diff --git a/kit/Sources/CodyncKit/Design/CharacterAvatar.swift b/apps/ios/Kit/Sources/CodyncKit/Design/CharacterAvatar.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Design/CharacterAvatar.swiftrename to apps/ios/Kit/Sources/CodyncKit/Design/CharacterAvatar.swiftdiff --git a/kit/Sources/CodyncKit/Design/Motion.swift b/apps/ios/Kit/Sources/CodyncKit/Design/Motion.swiftsimilarity index 91%rename from kit/Sources/CodyncKit/Design/Motion.swiftrename to apps/ios/Kit/Sources/CodyncKit/Design/Motion.swiftindex d54d8855..07d02b1e 100644--- a/kit/Sources/CodyncKit/Design/Motion.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Design/Motion.swift@@ -1,9 +1,5 @@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.@@ -35,13 +31,7 @@ public enum Motion {/// 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- #endifwithAnimation(reduced(layout, reduce), change)}}diff --git a/kit/Sources/CodyncKit/Design/Theme.swift b/apps/ios/Kit/Sources/CodyncKit/Design/Theme.swiftsimilarity index 94%rename from kit/Sources/CodyncKit/Design/Theme.swiftrename to apps/ios/Kit/Sources/CodyncKit/Design/Theme.swiftindex 78c92741..3cfe813d 100644--- a/kit/Sources/CodyncKit/Design/Theme.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Design/Theme.swift@@ -1,12 +1,7 @@import SwiftUI-#if canImport(UIKit)import UIKitprivate typealias PlatformColor = UIColor-#else-import AppKit-private typealias PlatformColor = NSColor-#endifprivate extension PlatformColor {convenience init(hex: UInt32, alpha: CGFloat = 1) {@@ -26,13 +21,7 @@ public extension Color {/// Light/dark pair resolved by the system appearance.init(light: UInt32, dark: UInt32) {- #if canImport(UIKit)self.init(uiColor: UIColor { $0.userInterfaceStyle == .dark ? UIColor(hex: dark) : UIColor(hex: light) })- #else- self.init(nsColor: NSColor(name: nil) { appearance in- appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? NSColor(hex: dark) : NSColor(hex: light)- })- #endif}}diff --git a/kit/Sources/CodyncKit/Design/ThinkingOrb.swift b/apps/ios/Kit/Sources/CodyncKit/Design/ThinkingOrb.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Design/ThinkingOrb.swiftrename to apps/ios/Kit/Sources/CodyncKit/Design/ThinkingOrb.swiftdiff --git a/kit/Sources/CodyncKit/Design/ThinkingOrbGeometry.swift b/apps/ios/Kit/Sources/CodyncKit/Design/ThinkingOrbGeometry.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Design/ThinkingOrbGeometry.swiftrename to apps/ios/Kit/Sources/CodyncKit/Design/ThinkingOrbGeometry.swiftdiff --git a/kit/Sources/CodyncKit/Design/UsageBar.swift b/apps/ios/Kit/Sources/CodyncKit/Design/UsageBar.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Design/UsageBar.swiftrename to apps/ios/Kit/Sources/CodyncKit/Design/UsageBar.swiftdiff --git a/kit/Sources/CodyncKit/Design/WidgetCards.swift b/apps/ios/Kit/Sources/CodyncKit/Design/WidgetCards.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Design/WidgetCards.swiftrename to apps/ios/Kit/Sources/CodyncKit/Design/WidgetCards.swiftdiff --git a/kit/Sources/CodyncKit/Models/AgentModels.swift b/apps/ios/Kit/Sources/CodyncKit/Models/AgentModels.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/AgentModels.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/AgentModels.swiftdiff --git a/kit/Sources/CodyncKit/Models/BotActivity.swift b/apps/ios/Kit/Sources/CodyncKit/Models/BotActivity.swiftsimilarity index 98%rename from kit/Sources/CodyncKit/Models/BotActivity.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/BotActivity.swiftindex e25fff6b..eac64e91 100644--- a/kit/Sources/CodyncKit/Models/BotActivity.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/BotActivity.swift@@ -1,4 +1,3 @@-#if os(iOS)import ActivityKitimport Foundation@@ -35,4 +34,3 @@ public struct BotActivityAttributes: ActivityAttributes {avatarColor = bot.avatarColor}}-#endifdiff --git a/kit/Sources/CodyncKit/Models/BotActivityPresentation.swift b/apps/ios/Kit/Sources/CodyncKit/Models/BotActivityPresentation.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/BotActivityPresentation.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/BotActivityPresentation.swiftdiff --git a/kit/Sources/CodyncKit/Models/Cloud.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Cloud.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/Cloud.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/Cloud.swiftdiff --git a/kit/Sources/CodyncKit/Models/Compatibility.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Compatibility.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/Compatibility.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/Compatibility.swiftdiff --git a/kit/Sources/CodyncKit/Models/Computer.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Computer.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/Computer.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/Computer.swiftdiff --git a/kit/Sources/CodyncKit/Models/Market.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Market.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/Market.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/Market.swiftdiff --git a/kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/Models.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/Models.swiftdiff --git a/kit/Sources/CodyncKit/Models/PushAlert.swift b/apps/ios/Kit/Sources/CodyncKit/Models/PushAlert.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/PushAlert.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/PushAlert.swiftdiff --git a/kit/Sources/CodyncKit/Models/Routine.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Routine.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/Routine.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/Routine.swiftdiff --git a/kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swift b/apps/ios/Kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swiftdiff --git a/kit/Sources/CodyncKit/Models/ScreenConnection.swift b/apps/ios/Kit/Sources/CodyncKit/Models/ScreenConnection.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/ScreenConnection.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/ScreenConnection.swiftdiff --git a/kit/Sources/CodyncKit/Models/ScreenViewport.swift b/apps/ios/Kit/Sources/CodyncKit/Models/ScreenViewport.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/ScreenViewport.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/ScreenViewport.swiftdiff --git a/kit/Sources/CodyncKit/Models/Voice.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Voice.swiftsimilarity index 100%rename from kit/Sources/CodyncKit/Models/Voice.swiftrename to apps/ios/Kit/Sources/CodyncKit/Models/Voice.swiftdiff --git a/apps/macos/Resources/Assets.xcassets/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/Contents.jsonsimilarity index 100%rename from apps/macos/Resources/Assets.xcassets/Contents.jsonrename to apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/Contents.jsondiff --git a/kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-claude-acp.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-claude-acp.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-claude-acp.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-claude-acp.imageset/Contents.jsondiff --git a/kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-claude-acp.imageset/claude-acp.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-claude-acp.imageset/claude-acp.svgsimilarity index 100%rename from kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-claude-acp.imageset/claude-acp.svgrename to apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-claude-acp.imageset/claude-acp.svgdiff --git a/kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-codex-acp.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-codex-acp.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-codex-acp.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-codex-acp.imageset/Contents.jsondiff --git a/kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-codex-acp.imageset/codex-acp.svg b/apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-codex-acp.imageset/codex-acp.svgsimilarity index 100%rename from kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-codex-acp.imageset/codex-acp.svgrename to apps/ios/Kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/agent-codex-acp.imageset/codex-acp.svgdiff --git a/kit/Sources/CodyncKit/Resources/ThirdPartyNotices/thinking-orbs-LICENSE.txt b/apps/ios/Kit/Sources/CodyncKit/Resources/ThirdPartyNotices/thinking-orbs-LICENSE.txtsimilarity index 100%rename from kit/Sources/CodyncKit/Resources/ThirdPartyNotices/thinking-orbs-LICENSE.txtrename to apps/ios/Kit/Sources/CodyncKit/Resources/ThirdPartyNotices/thinking-orbs-LICENSE.txtdiff --git a/kit/Sources/CodyncUI/Bots/AgentModelPicker.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/AgentModelPicker.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Bots/AgentModelPicker.swiftrename to apps/ios/Kit/Sources/CodyncUI/Bots/AgentModelPicker.swiftdiff --git a/kit/Sources/CodyncUI/Bots/BotEditorView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swiftsimilarity index 94%rename from kit/Sources/CodyncUI/Bots/BotEditorView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swiftindex 5e1d1003..73394349 100644--- a/kit/Sources/CodyncUI/Bots/BotEditorView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift@@ -119,29 +119,10 @@ struct BotSettingsForm: View {ScrollView {VStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 24, mobile: 30)) {VStack(spacing: InterfaceMetrics.value(mac: 12, mobile: 16)) {- #if os(macOS)- Button { pickingAvatar.toggle() } label: {- CharacterAvatar(shape: draft.avatarShape, color: draft.avatarColor, size: 56)- .padding(12)- .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 20))- }- .buttonStyle(.plain)- .accessibilityLabel("Edit Bot avatar")- .help("Edit Bot avatar")- .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { avatarFrame = $0 }- .codyncOverlay(isPresented: $pickingAvatar) { close in- AnchoredPanel(anchor: avatarFrame, close: close) {- AvatarPicker(shape: $draft.avatarShape, color: $draft.avatarColor)- .padding(14)- .frame(width: 300)- }- }- #elseCharacterAvatar(shape: draft.avatarShape, color: draft.avatarColor, size: 96).padding(18).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 24, style: .continuous))AvatarPicker(shape: $draft.avatarShape, color: $draft.avatarColor)- #endif}.frame(maxWidth: .infinity)@@ -254,9 +235,6 @@ struct BotSettingsForm: View {.padding(InterfaceMetrics.value(mac: 14, mobile: 20))}.appFont(AppFont.compactBody)- #if os(macOS)- .controlSize(.small)- #endif.scrollDismissesKeyboard(.interactively).background(Palette.background).task { await model.refreshPlugins() }@@ -265,9 +243,6 @@ struct BotSettingsForm: View {draft.cwd = $0pickingFolder = false}- #if os(macOS)- .frame(width: 460, height: 520)- #endif}}}diff --git a/kit/Sources/CodyncUI/Bots/BotRow.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotRow.swiftsimilarity index 94%rename from kit/Sources/CodyncUI/Bots/BotRow.swiftrename to apps/ios/Kit/Sources/CodyncUI/Bots/BotRow.swiftindex 1dc3fbaf..31c4c81d 100644--- a/kit/Sources/CodyncUI/Bots/BotRow.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/BotRow.swift@@ -12,15 +12,9 @@ public struct BotRow: View {}// A Mac sidebar row is denser than a phone row (Grok Bot's desktop sidebar).- #if os(macOS)- private let avatar: CGFloat = 30- private let rowPadding: CGFloat = 6- private let lineSpacing: CGFloat = 1- #elseprivate let avatar: CGFloat = 46private let rowPadding: CGFloat = 10private let lineSpacing: CGFloat = 4- #endifpublic var body: some View {HStack(spacing: compact ? 0 : InterfaceMetrics.value(mac: 8, mobile: 12)) {@@ -41,11 +35,9 @@ public struct BotRow: View {.accessibilityLabel("Using the computer")}Spacer(minLength: 8)- #if os(iOS)Text(RelativeTime.day(Date(milliseconds: bot.lastAt))).appFont(AppFont.compactSecondary).foregroundStyle(bot.unread > 0 ? Palette.text : Palette.tertiary)- #endif}HStack(alignment: .firstTextBaseline, spacing: 6) {previewdiff --git a/kit/Sources/CodyncUI/Bots/BotTemplateView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotTemplateView.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Bots/BotTemplateView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Bots/BotTemplateView.swiftdiff --git a/kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swiftsimilarity index 76%rename from kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swiftrename to apps/ios/Kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swiftindex c9b19e05..d4ea1f11 100644--- a/kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swift@@ -24,7 +24,6 @@ public struct ComputerFilterHeader: View {private var summary: String { ConnectionSummary(connections: stores.map(\.shownConnection)).text }public var body: some View {- #if os(iOS)Menu {Button("All computers", systemImage: selection.shown.count == accounts.computers.count ? "checkmark" : "desktopcomputer") { update("") }ForEach(accounts.computers) { computer in@@ -48,27 +47,6 @@ public struct ComputerFilterHeader: View {Button("Manage computers", systemImage: "desktopcomputer", action: manage)} label: { label }.accessibilityLabel("Computers, \(summary). Filter conversations")- #else- DropdownMenu {- var items = [MenuItem("All computers", selected: selection.shown.count == accounts.computers.count) { update("") }]- items += accounts.computers.map { computer in- MenuItem(computerTitle(computer), selected: selection.shown.contains(computer.id)) {- update(selection.toggling(computer.id))- }- }- if accounts.computers.count > 1 {- items += accounts.computers.enumerated().map { index, computer in- MenuItem("Only \(computer.name)", divider: index == 0) { update(selection.only(computer.id)) }- }- }- if !stores.isEmpty {- items.append(MenuItem("Reconnect", icon: "arrow.clockwise", divider: true, action: reconnect))- }- items.append(MenuItem("Manage computers", icon: "desktopcomputer", action: manage))- return items- } label: { label }- .accessibilityLabel("Computers, \(summary). Filter conversations")- #endif}private var label: some View {diff --git a/kit/Sources/CodyncUI/Bots/Dialogs.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/Dialogs.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Bots/Dialogs.swiftrename to apps/ios/Kit/Sources/CodyncUI/Bots/Dialogs.swiftdiff --git a/kit/Sources/CodyncUI/Bots/GroupEditorView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/GroupEditorView.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Bots/GroupEditorView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Bots/GroupEditorView.swiftdiff --git a/kit/Sources/CodyncUI/Bots/MemoryView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/MemoryView.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Bots/MemoryView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Bots/MemoryView.swiftdiff --git a/kit/Sources/CodyncUI/Bots/NewChatView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/NewChatView.swiftsimilarity index 98%rename from kit/Sources/CodyncUI/Bots/NewChatView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Bots/NewChatView.swiftindex 3d630542..829e48c1 100644--- a/kit/Sources/CodyncUI/Bots/NewChatView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/NewChatView.swift@@ -10,9 +10,6 @@ public struct NewChatView: View {let group: Boollet close: () -> Void@Environment(BotStore.self) private var model- #if os(macOS)- @Environment(\.conversationTypography) private var typography- #endif@State private var query = ""@State private var draft = ""@State private var recipients: [String] = []@@ -110,9 +107,6 @@ public struct NewChatView: View {HStack(alignment: .bottom, spacing: 8) {TextField(placeholder, text: $draft, axis: .vertical).lineLimit(1...6)- #if os(macOS)- .font(typography.body)- #endif.textFieldStyle(.plain).padding(.vertical, 11).sendOnReturn(start)diff --git a/kit/Sources/CodyncUI/Call/CallOperator.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallOperator.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Call/CallOperator.swiftrename to apps/ios/Kit/Sources/CodyncUI/Call/CallOperator.swiftdiff --git a/kit/Sources/CodyncUI/Call/CallView.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swiftsimilarity index 96%rename from kit/Sources/CodyncUI/Call/CallView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Call/CallView.swiftindex 6c31c3c6..1402a631 100644--- a/kit/Sources/CodyncUI/Call/CallView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swift@@ -160,14 +160,8 @@ struct CallView: View {.padding(.leading, InterfaceMetrics.value(mac: 18, mobile: 14)).padding(.trailing, InterfaceMetrics.value(mac: 10, mobile: 7)).padding(.vertical, InterfaceMetrics.value(mac: 10, mobile: 7))- #if os(macOS)- // Floats over the chat like the title pill: frosted, raised, sized to its content.- .frosted(in: Capsule())- .shadow(color: .black.opacity(0.25), radius: 20, y: 8)- #else.glass(in: Capsule()).shadow(color: .black.opacity(0.08), radius: 16, y: 6)- #endif}/// The bot; tapping it while it talks cuts the reply short.@@ -204,13 +198,8 @@ struct CallView: View {private static let dotsHeight = InterfaceMetrics.value(mac: 16, mobile: 20)private static let dotsWidth = InterfaceMetrics.value(mac: 120, mobile: 0)private static let dotsMaxWidth: CGFloat = InterfaceMetrics.value(mac: 120, mobile: .infinity)- #if os(macOS)- private static let buttonFill = Palette.bubbleUser- private static let buttonInk = Palette.secondary- #elseprivate static let buttonFill = Palette.backgroundprivate static let buttonInk = Palette.text- #endifprivate var statusText: String {switch session?.phase {diff --git a/kit/Sources/CodyncUI/Call/CloudSpeechEngine.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CloudSpeechEngine.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Call/CloudSpeechEngine.swiftrename to apps/ios/Kit/Sources/CodyncUI/Call/CloudSpeechEngine.swiftindex da461aaa..62be4600 100644--- a/kit/Sources/CodyncUI/Call/CloudSpeechEngine.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CloudSpeechEngine.swift@@ -81,11 +81,9 @@ final class CloudSpeechEngine: VoiceEngine {}guard !ended else { return }do {- #if os(iOS)let session = AVAudioSession.sharedInstance()try session.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .allowBluetoothHFP])try session.setActive(true)- #endiflet input = engine.inputNodelet format = input.outputFormat(forBus: 0)input.installTap(onBus: 0, bufferSize: 2048, format: format, block: MicTap.pcm16k(from: format) { [weak self] pcm, level in@@ -110,9 +108,7 @@ final class CloudSpeechEngine: VoiceEngine {engine.stop()audioRunning = false}- #if os(iOS)try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)- #endif}func interrupt() {diff --git a/kit/Sources/CodyncUI/Call/GeminiLiveEngine.swift b/apps/ios/Kit/Sources/CodyncUI/Call/GeminiLiveEngine.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Call/GeminiLiveEngine.swiftrename to apps/ios/Kit/Sources/CodyncUI/Call/GeminiLiveEngine.swiftindex 954a1fb7..cd2c95b4 100644--- a/kit/Sources/CodyncUI/Call/GeminiLiveEngine.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/GeminiLiveEngine.swift@@ -119,9 +119,7 @@ final class GeminiLiveEngine: VoiceEngine {engine.stop()audioRunning = false}- #if os(iOS)try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)- #endif}func interrupt() {@@ -252,11 +250,9 @@ final class GeminiLiveEngine: VoiceEngine {// MARK: audioprivate func startAudio() throws {- #if os(iOS)let session = AVAudioSession.sharedInstance()try session.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .allowBluetoothHFP])try session.setActive(true)- #endiflet input = engine.inputNodetry input.setVoiceProcessingEnabled(true)engine.attach(player)diff --git a/kit/Sources/CodyncUI/Call/OnDeviceEngine.swift b/apps/ios/Kit/Sources/CodyncUI/Call/OnDeviceEngine.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Call/OnDeviceEngine.swiftrename to apps/ios/Kit/Sources/CodyncUI/Call/OnDeviceEngine.swiftindex 1470c1ab..a23c10ae 100644--- a/kit/Sources/CodyncUI/Call/OnDeviceEngine.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/OnDeviceEngine.swift@@ -71,7 +71,6 @@ final class OnDeviceEngine: VoiceEngine {return fail("Speech recognition isn't available for this language right now.")}guard !ended else { return }- #if os(iOS)do {let audio = AVAudioSession.sharedInstance()try audio.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .allowBluetoothHFP])@@ -79,7 +78,6 @@ final class OnDeviceEngine: VoiceEngine {} catch {return fail("Couldn't start audio: \(error.localizedDescription)")}- #endiflisten()}@@ -88,9 +86,7 @@ final class OnDeviceEngine: VoiceEngine {onActivityChanged?(false)stopListening()synthesizer.stopSpeaking(at: .immediate)- #if os(iOS)try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)- #endif}/// Reads a reply aloud (the bot's final message), pausing the microphone meanwhile.diff --git a/kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swift b/apps/ios/Kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swiftrename to apps/ios/Kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swiftindex a6bc12ac..096e19dc 100644--- a/kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swift@@ -59,11 +59,9 @@ final class OpenAIRealtimeEngine: VoiceEngine {}private func connect(secret: String) async throws {- #if os(iOS)let audio = RTCAudioSessionConfiguration.webRTC()audio.categoryOptions = [.defaultToSpeaker, .allowBluetoothHFP]RTCAudioSessionConfiguration.setWebRTC(audio)- #endiflet config = RTCConfiguration()config.sdpSemantics = .unifiedPlandiff --git a/kit/Sources/CodyncUI/Call/SpokenText.swift b/apps/ios/Kit/Sources/CodyncUI/Call/SpokenText.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Call/SpokenText.swiftrename to apps/ios/Kit/Sources/CodyncUI/Call/SpokenText.swiftdiff --git a/kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swift b/apps/ios/Kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swiftsimilarity index 98%rename from kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swiftindex 774a69df..b5fa7efd 100644--- a/kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swift@@ -40,9 +40,6 @@ public struct VoiceChatSettingsView: View {}}.background(Palette.background)- #if os(macOS)- .frame(width: showsHeader ? 440 : nil, height: showsHeader ? 600 : nil)- #endif}private var engineFooter: String {@@ -177,11 +174,7 @@ private struct ProviderVoiceSettings: View {}/// Keys are entered on the computer itself (the host takes `setVoiceKey` from loopback only).- #if os(macOS)- private static let canEditKey = true- #elseprivate static let canEditKey = false- #endif/// On the phone: where to add the key.private var missingKeyRow: some View {diff --git a/kit/Sources/CodyncUI/Call/VoiceEngine.swift b/apps/ios/Kit/Sources/CodyncUI/Call/VoiceEngine.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Call/VoiceEngine.swiftrename to apps/ios/Kit/Sources/CodyncUI/Call/VoiceEngine.swiftdiff --git a/kit/Sources/CodyncUI/Chrome.swift b/apps/ios/Kit/Sources/CodyncUI/Chrome.swiftsimilarity index 69%rename from kit/Sources/CodyncUI/Chrome.swiftrename to apps/ios/Kit/Sources/CodyncUI/Chrome.swiftindex d8ee7c8d..f2cbb17a 100644--- a/kit/Sources/CodyncUI/Chrome.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Chrome.swift@@ -1,8 +1,6 @@import CodyncKitimport SwiftUI-#if os(iOS)import UIKit-#endif// Codync's own screen chrome: modals, headers, icon buttons and the iPhone tab bar.// Present with `.codyncSheet`, title with `ModalHeader` / `ScreenHeader`.@@ -180,11 +178,7 @@ public extension View {/// Mac: the window root that hosts every `.codyncSheet` below it, so modals cover the/// whole window rather than the column that opened them.@ViewBuilder func modalHost() -> some View {- #if os(macOS)- modifier(ModalHostModifier())- #elseself- #endif}}@@ -202,7 +196,6 @@ private struct CodyncItemSheet<Item: Identifiable, Sheet: View>: ViewModifier {}}-#if os(iOS)/// The system sheet: its own slide, grabber and swipe down, nothing hand-built.private struct CodyncSheet<Sheet: View>: ViewModifier {@Binding var isPresented: Bool@@ -282,153 +275,6 @@ public extension View {.background(SwipeBackEnabler().frame(width: 0, height: 0))}}-#else-@MainActor @Observable-final class ModalHost {- enum Chrome { case card, bare }-- struct Entry: Identifiable {- let id: UUID- var chrome: Chrome- var content: AnyView- var shown = false- }-- var entries: [Entry] = []-- func present(_ id: UUID, chrome: Chrome, _ content: AnyView) {- if let index = entries.firstIndex(where: { $0.id == id }) {- entries[index].content = content- if !entries[index].shown { withAnimation(Motion.layout) { entries[index].shown = true } }- return- }- entries.append(Entry(id: id, chrome: chrome, content: content))- withAnimation(Motion.layout) {- if let index = entries.firstIndex(where: { $0.id == id }) { entries[index].shown = true }- }- }-- func close(_ id: UUID) {- guard let index = entries.firstIndex(where: { $0.id == id }), entries[index].shown else { return }- withAnimation(Motion.layout) {- entries[index].shown = false- } completion: {- self.entries.removeAll { $0.id == id && !$0.shown }- }- }-}--extension EnvironmentValues {- @Entry var modalHost: ModalHost?-}--private struct ModalHostModifier: ViewModifier {- @State private var host = ModalHost()-- func body(content: Content) -> some View {- content- .environment(\.modalHost, host)- .overlay {- ZStack {- ForEach(host.entries) { entry in- Group {- switch entry.chrome {- case .card: ModalCard(shown: entry.shown) { entry.content }- case .bare: entry.content.opacity(entry.shown ? 1 : 0).scaleEffect(entry.shown ? 1 : 0.98)- }- }- // A menu above a sheet becomes the active accessibility surface.- .accessibilityHidden(entry.id != host.entries.last?.id)- .disabled(entry.id != host.entries.last?.id)- }- }- }- }-}--/// The Mac modal: a centered card over a dim; the content sizes it.-private struct ModalCard<Content: View>: View {- let shown: Bool- @ViewBuilder let content: () -> Content-- var body: some View {- ZStack {- Color.black.opacity(shown ? 0.4 : 0)- .ignoresSafeArea()- .contentShape(Rectangle())- .onTapGesture {}- .accessibilityHidden(true)- content()- .background(Palette.background)- .clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))- .shadow(color: .black.opacity(0.3), radius: 30, y: 12)- .scaleEffect(shown ? 1 : 0.96)- .opacity(shown ? 1 : 0)- .padding(24)- }- .accessibilityAddTraits(.isModal)- }-}--/// Hands a presentation to the window's `ModalHost`, carrying the stores the content reads.-private struct HostedPresentation<Layer: View>: ViewModifier {- @Binding var isPresented: Bool- let chrome: ModalHost.Chrome- let layer: (_ close: @escaping () -> Void) -> Layer- @Environment(\.modalHost) private var host- @Environment(BotStore.self) private var store: BotStore?- @Environment(AccountStore.self) private var accounts: AccountStore?- @State private var id = UUID()-- func body(content: Content) -> some View {- content- .onChange(of: isPresented, initial: true) { _, _ in sync() }- .onDisappear { host?.close(id) }- }-- private func sync() {- guard let host else { return }- guard isPresented else { return host.close(id) }- let binding = $isPresented- let close = { binding.wrappedValue = false }- // ponytail: the content is captured when it opens; state it reads through- // stores and bindings stays live, plain values passed in don't refresh.- host.present(id, chrome: chrome, AnyView(- layer(close)- .environment(store)- .environment(accounts)- .environment(\.modalHost, host)- .environment(\.dismissModal, DismissModalAction { binding.wrappedValue = false })- ))- }-}--private struct CodyncSheet<Sheet: View>: ViewModifier {- @Binding var isPresented: Bool- let sheet: () -> Sheet-- func body(content: Content) -> some View {- content.modifier(HostedPresentation(isPresented: $isPresented, chrome: .card) { _ in sheet() })- }-}--private struct CodyncOverlay<Layer: View>: ViewModifier {- @Binding var isPresented: Bool- let layer: (_ close: @escaping () -> Void) -> Layer-- func body(content: Content) -> some View {- content.modifier(HostedPresentation(isPresented: $isPresented, chrome: .bare) { close in- layer(close)- .accessibilityAddTraits(.isModal)- .onExitCommand(perform: close)- })- }-}--public extension View {- func hidesSystemNavigationBar() -> some View { self }-}-#endif// MARK: - Tab bardiff --git a/kit/Sources/CodyncUI/ComputerBadge.swift b/apps/ios/Kit/Sources/CodyncUI/ComputerBadge.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/ComputerBadge.swiftrename to apps/ios/Kit/Sources/CodyncUI/ComputerBadge.swiftdiff --git a/kit/Sources/CodyncUI/Controls.swift b/apps/ios/Kit/Sources/CodyncUI/Controls.swiftsimilarity index 92%rename from kit/Sources/CodyncUI/Controls.swiftrename to apps/ios/Kit/Sources/CodyncUI/Controls.swiftindex 00217bbd..0645726f 100644--- a/kit/Sources/CodyncUI/Controls.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Controls.swift@@ -1,10 +1,6 @@import CodyncKitimport SwiftUI-#if os(macOS)-import AppKit-#elseif os(iOS)import UIKit-#endif// Codync's own controls. Never use the stock ones (Picker, .switch toggles,// Form/List styling, confirmationDialog/alert, ProgressView, DisclosureGroup,@@ -337,13 +333,8 @@ public extension View {private struct ContextActions: ViewModifier {let items: () -> [MenuItem]let reactions: ReactionPick?- #if os(macOS)- @State private var open = false- @State private var point: CGPoint?- #endiffunc body(content: Content) -> some View {- #if os(iOS)content.contextMenu {if let reactions {ControlGroup {@@ -359,25 +350,9 @@ private struct ContextActions: ViewModifier {systemMenuRow(item)}}- #else- content- .overlay { SecondaryClickCapture { point = $0; open = true } }- .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) }- }- }- }- #endif}}-#if os(iOS)/// A `MenuItem` inside a system `Menu` or `contextMenu`: choices as checkmarked toggles.@ViewBuilder private func systemMenuRow(_ item: MenuItem) -> some View {let role: ButtonRole? = item.destructive ? .destructive : nil@@ -391,7 +366,6 @@ private struct ContextActions: ViewModifier {Button(item.title, role: role, action: item.action)}}-#endif/// Presents `MenuPanel` next to the view (or at `point` inside it, for right-clicks).private struct AnchoredMenu: ViewModifier {@@ -419,9 +393,6 @@ struct AnchoredPanel<Panel: View>: View {let anchor: CGRectlet close: () -> Void@ViewBuilder let panel: () -> Panel- #if os(macOS)- @FocusState private var keyboardFocused: Bool- #endifvar body: some View {GeometryReader { geo in@@ -446,12 +417,6 @@ struct AnchoredPanel<Panel: View>: View {}}.ignoresSafeArea()- #if os(macOS)- .focusable()- .focusEffectDisabled()- .focused($keyboardFocused)- .onAppear { keyboardFocused = true }- #endif}}@@ -467,7 +432,6 @@ public struct DropdownMenu<Label: View>: View {}public var body: some View {- #if os(iOS)// The system menu: it anchors correctly inside sheets and scroll views, where an overlay can't.Menu {ForEach(items()) { item in@@ -477,11 +441,6 @@ public struct DropdownMenu<Label: View>: View {} label: { label }.buttonStyle(.plain).menuIndicator(.hidden)- #else- Button { open.toggle() } label: { label }- .buttonStyle(.plain)- .codyncMenu(isPresented: $open, items: items)- #endif}}@@ -847,12 +806,10 @@ private struct CodyncDialog: ViewModifier {isPresented = false}.transition(.opacity)- #if os(iOS).onAppear {UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder),to: nil, from: nil, for: nil)}- #endif}}.animation(Motion.reduced(Motion.fade, reduceMotion), value: isPresented)@@ -944,34 +901,3 @@ extension View {}}-#if os(macOS)-/// Intercepts only secondary clicks; primary clicks, scrolling and dragging pass through.-public struct SecondaryClickCapture: NSViewRepresentable {- let onClick: (CGPoint) -> Void-- public init(onClick: @escaping (CGPoint) -> Void) { self.onClick = onClick }-- public func makeNSView(context: Context) -> CaptureView { CaptureView(onClick: onClick) }- public func updateNSView(_ view: CaptureView, context: Context) { view.onClick = onClick }-- public final class CaptureView: NSView {- var onClick: (CGPoint) -> Void- override public var isFlipped: Bool { true }-- init(onClick: @escaping (CGPoint) -> Void) {- self.onClick = onClick- super.init(frame: .zero)- }- required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }-- override public func hitTest(_ point: NSPoint) -> NSView? {- guard let event = NSApp.currentEvent,- event.type == .rightMouseDown || (event.type == .leftMouseDown && event.modifierFlags.contains(.control))- else { return nil }- return super.hitTest(point)- }- override public func rightMouseDown(with event: NSEvent) { onClick(convert(event.locationInWindow, from: nil)) }- override public func mouseDown(with event: NSEvent) { onClick(convert(event.locationInWindow, from: nil)) }- }-}-#endifdiff --git a/kit/Sources/CodyncUI/Marketplace/ComposioViews.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/ComposioViews.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Marketplace/ComposioViews.swiftrename to apps/ios/Kit/Sources/CodyncUI/Marketplace/ComposioViews.swiftdiff --git a/kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swiftrename to apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swiftdiff --git a/kit/Sources/CodyncUI/Marketplace/ConnectorSignInFlow.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectorSignInFlow.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Marketplace/ConnectorSignInFlow.swiftrename to apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectorSignInFlow.swiftdiff --git a/kit/Sources/CodyncUI/Marketplace/MarketplacePage.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplacePage.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Marketplace/MarketplacePage.swiftrename to apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplacePage.swiftdiff --git a/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplaceView.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Marketplace/MarketplaceView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplaceView.swiftindex dad8c529..de39424b 100644--- a/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift@@ -1,10 +1,6 @@import CodyncKitimport SwiftUI-#if canImport(UIKit)import UIKit-#else-import AppKit-#endif/// The Marketplace (Grok Bot's layout): one page of agents, connectors and/// skills for the bots on one computer (the store in the environment). Installing happens on that/// computer; each bot turns connectors and skills on in its settings.@@ -93,7 +89,6 @@ public struct MarketplaceView: View {searchFieldif !agents.isEmpty {MarketSection(title: query.isEmpty ? "Agents" : "Agents matching “\(query)”") {- #if os(iOS)// A swipeable row on the phone, a grid on the Mac.ScrollView(.horizontal, showsIndicators: false) {LazyHStack(spacing: 10) {@@ -102,11 +97,6 @@ public struct MarketplaceView: View {.padding(.horizontal, 24)}.padding(.horizontal, -24)- #else- LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 12)], spacing: 12) {- ForEach(agents.prefix(agentLimit)) { agentCard($0) }- }- #endifif agents.count > agentLimit {Button("Load more agents") {withAnimation(Motion.fade) { agentLimit += 10 }@@ -1372,11 +1362,7 @@ public struct AgentIcon: View {}private static func exists(_ name: String) -> Bool {- #if canImport(UIKit)UIImage(named: name, in: .module, with: nil) != nil- #else- Bundle.module.image(forResource: name) != nil- #endif}}diff --git a/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/SetupTerminal.swiftsimilarity index 86%rename from kit/Sources/CodyncUI/Marketplace/SetupTerminal.swiftrename to apps/ios/Kit/Sources/CodyncUI/Marketplace/SetupTerminal.swiftindex 207350ee..7e5540a2 100644--- a/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/SetupTerminal.swift@@ -1,11 +1,7 @@import CodyncKitimport SwiftTermimport SwiftUI-#if canImport(UIKit)import UIKit-#else-import AppKit-#endif/// Installing or signing in to an agent, live: the command runs in a terminal/// on the computer and this screen is that terminal (links open here).@@ -175,26 +171,16 @@ private final class TerminalBridge: NSObject, @preconcurrency TerminalViewDelega@MainActor func make() -> TerminalView {let view = TerminalView(frame: CGRect(x: 0, y: 0, width: 400, height: 300))view.terminalDelegate = self- #if canImport(UIKit)view.font = .monospacedSystemFont(ofSize: 12, weight: .regular)view.nativeBackgroundColor = UIColor(Palette.background)view.nativeForegroundColor = UIColor(Palette.text)view.keyboardDismissMode = .interactive- #else- view.font = .monospacedSystemFont(ofSize: 12, weight: .regular)- view.nativeBackgroundColor = NSColor(Palette.background)- view.nativeForegroundColor = NSColor(Palette.text)- #endifsession.view = viewreturn view}@MainActor func focus(_ view: TerminalView) {- #if canImport(UIKit)_ = view.becomeFirstResponder()- #else- view.window?.makeFirstResponder(view)- #endif}@MainActor func send(source: TerminalView, data: ArraySlice<UInt8>) { session.type(data) }@@ -213,7 +199,6 @@ private final class TerminalBridge: NSObject, @preconcurrency TerminalViewDelega}}-#if canImport(UIKit)private struct TerminalSurface: UIViewRepresentable {let session: TermSessionlet open: (URL) -> Void@@ -228,25 +213,3 @@ private struct TerminalSurface: UIViewRepresentable {func updateUIView(_ view: TerminalView, context: Context) {}}-#else-private struct TerminalSurface: NSViewRepresentable {- let session: TermSession- let open: (URL) -> Void- @Environment(\.appFontScale) private var fontScale-- func makeCoordinator() -> TerminalBridge { TerminalBridge(session: session, open: open) }-- func makeNSView(context: Context) -> TerminalView {- let view = context.coordinator.make()- view.font = .monospacedSystemFont(ofSize: 12 * fontScale, weight: .regular)- Task { @MainActor in context.coordinator.focus(view) }- return view- }-- func updateNSView(_ view: TerminalView, context: Context) {- let size = 12 * fontScale- guard view.font.pointSize != size else { return }- view.font = .monospacedSystemFont(ofSize: size, weight: .regular)- }-}-#endifdiff --git a/kit/Sources/CodyncUI/Platform.swift b/apps/ios/Kit/Sources/CodyncUI/Platform.swiftsimilarity index 60%rename from kit/Sources/CodyncUI/Platform.swiftrename to apps/ios/Kit/Sources/CodyncUI/Platform.swiftindex 913fa14e..84424503 100644--- a/kit/Sources/CodyncUI/Platform.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Platform.swift@@ -1,30 +1,17 @@import CodyncKitimport SwiftUI-#if canImport(UIKit)import UIKit-#else-import AppKit-#endifenum Pasteboard {static func copy(_ text: String?) {guard let text else { return }- #if canImport(UIKit)UIPasteboard.general.string = text- #else- NSPasteboard.general.clearContents()- NSPasteboard.general.setString(text, forType: .string)- #endif}}extension View {func plainTextInput() -> some View {- #if os(iOS)textInputAutocapitalization(.never).autocorrectionDisabled()- #else- autocorrectionDisabled()- #endif}}@@ -52,61 +39,27 @@ extension View {/// The message box: Liquid Glass on iPhone; on the Mac a filled box with a/// soft shadow (as in Grok Bot's desktop app).@ViewBuilder func composerSurface(in shape: some Shape) -> some View {- #if os(macOS)- background(Palette.bubbleUser, in: shape)- .shadow(color: .black.opacity(0.06), radius: 10, y: 2)- #elseglass(in: shape)- #endif}/// Mac: Return sends, Shift-Return adds a new line. iPhone keeps Return as a new line./// While an input method (Zhuyin, Pinyin, Japanese…) is composing, Return picks the candidate instead.@ViewBuilder func sendOnReturn(_ send: @escaping () -> Void) -> some View {- #if os(macOS)- onKeyPress(.return, phases: .down) { press in- let editor = NSApp.keyWindow?.firstResponder as? NSTextView- if editor?.hasMarkedText() == true {- return .ignored- }- if press.modifiers.contains(.shift) {- guard let editor else { return .ignored }- // The multiline TextField treats Return as submission, even with Shift.- editor.insertNewlineIgnoringFieldEditor(nil)- return .handled- }- send()- return .handled- }- #elseself- #endif}}/// Compact desktop metrics while preserving the phone's touch layout and Dynamic Type.enum InterfaceMetrics {static func value(mac: CGFloat, mobile: CGFloat) -> CGFloat {- #if os(macOS)- mac- #elsemobile- #endif}static var body: Font {- #if os(macOS)- .system(size: 12)- #else.body- #endif}static var secondary: Font {- #if os(macOS)- .system(size: 11)- #else.subheadline- #endif}}diff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-agoragentic-acp.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-agoragentic-acp.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-agoragentic-acp.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-agoragentic-acp.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-agoragentic-acp.imageset/agoragentic-acp.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-agoragentic-acp.imageset/agoragentic-acp.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-agoragentic-acp.imageset/agoragentic-acp.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-agoragentic-acp.imageset/agoragentic-acp.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-amp-acp.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-amp-acp.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-amp-acp.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-amp-acp.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-amp-acp.imageset/amp-acp.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-amp-acp.imageset/amp-acp.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-amp-acp.imageset/amp-acp.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-amp-acp.imageset/amp-acp.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-antigravity-acp.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-antigravity-acp.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-antigravity-acp.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-antigravity-acp.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-antigravity-acp.imageset/antigravity-acp.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-antigravity-acp.imageset/antigravity-acp.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-antigravity-acp.imageset/antigravity-acp.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-antigravity-acp.imageset/antigravity-acp.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-auggie.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-auggie.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-auggie.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-auggie.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-auggie.imageset/auggie.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-auggie.imageset/auggie.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-auggie.imageset/auggie.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-auggie.imageset/auggie.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-autohand.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-autohand.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-autohand.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-autohand.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-autohand.imageset/autohand.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-autohand.imageset/autohand.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-autohand.imageset/autohand.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-autohand.imageset/autohand.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-claude-acp.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-claude-acp.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-claude-acp.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-claude-acp.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-claude-acp.imageset/claude-acp.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-claude-acp.imageset/claude-acp.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-claude-acp.imageset/claude-acp.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-claude-acp.imageset/claude-acp.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cline.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cline.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cline.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cline.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cline.imageset/cline.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cline.imageset/cline.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cline.imageset/cline.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cline.imageset/cline.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codebuddy-code.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codebuddy-code.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codebuddy-code.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codebuddy-code.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codebuddy-code.imageset/codebuddy-code.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codebuddy-code.imageset/codebuddy-code.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codebuddy-code.imageset/codebuddy-code.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codebuddy-code.imageset/codebuddy-code.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codex-acp.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codex-acp.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codex-acp.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codex-acp.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codex-acp.imageset/codex-acp.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codex-acp.imageset/codex-acp.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codex-acp.imageset/codex-acp.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-codex-acp.imageset/codex-acp.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cortex-code.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cortex-code.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cortex-code.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cortex-code.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cortex-code.imageset/cortex-code.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cortex-code.imageset/cortex-code.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cortex-code.imageset/cortex-code.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cortex-code.imageset/cortex-code.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-corust-agent.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-corust-agent.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-corust-agent.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-corust-agent.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-corust-agent.imageset/corust-agent.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-corust-agent.imageset/corust-agent.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-corust-agent.imageset/corust-agent.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-corust-agent.imageset/corust-agent.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-crow-cli.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-crow-cli.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-crow-cli.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-crow-cli.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-crow-cli.imageset/crow-cli.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-crow-cli.imageset/crow-cli.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-crow-cli.imageset/crow-cli.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-crow-cli.imageset/crow-cli.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cursor.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cursor.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cursor.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cursor.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cursor.imageset/cursor.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cursor.imageset/cursor.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cursor.imageset/cursor.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-cursor.imageset/cursor.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-deepagents.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-deepagents.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-deepagents.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-deepagents.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-deepagents.imageset/deepagents.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-deepagents.imageset/deepagents.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-deepagents.imageset/deepagents.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-deepagents.imageset/deepagents.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-devin.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-devin.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-devin.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-devin.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-devin.imageset/devin.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-devin.imageset/devin.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-devin.imageset/devin.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-devin.imageset/devin.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dimcode.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dimcode.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dimcode.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dimcode.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dimcode.imageset/dimcode.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dimcode.imageset/dimcode.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dimcode.imageset/dimcode.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dimcode.imageset/dimcode.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dirac.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dirac.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dirac.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dirac.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dirac.imageset/dirac.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dirac.imageset/dirac.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dirac.imageset/dirac.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-dirac.imageset/dirac.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-factory-droid.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-factory-droid.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-factory-droid.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-factory-droid.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-factory-droid.imageset/factory-droid.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-factory-droid.imageset/factory-droid.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-factory-droid.imageset/factory-droid.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-factory-droid.imageset/factory-droid.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-fast-agent.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-fast-agent.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-fast-agent.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-fast-agent.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-fast-agent.imageset/fast-agent.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-fast-agent.imageset/fast-agent.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-fast-agent.imageset/fast-agent.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-fast-agent.imageset/fast-agent.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-gemini.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-gemini.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-gemini.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-gemini.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-gemini.imageset/gemini.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-gemini.imageset/gemini.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-gemini.imageset/gemini.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-gemini.imageset/gemini.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-github-copilot-cli.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-github-copilot-cli.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-github-copilot-cli.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-github-copilot-cli.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-github-copilot-cli.imageset/github-copilot-cli.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-github-copilot-cli.imageset/github-copilot-cli.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-github-copilot-cli.imageset/github-copilot-cli.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-github-copilot-cli.imageset/github-copilot-cli.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-glm-acp-agent.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-glm-acp-agent.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-glm-acp-agent.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-glm-acp-agent.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-glm-acp-agent.imageset/glm-acp-agent.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-glm-acp-agent.imageset/glm-acp-agent.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-glm-acp-agent.imageset/glm-acp-agent.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-glm-acp-agent.imageset/glm-acp-agent.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-goose.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-goose.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-goose.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-goose.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-goose.imageset/goose.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-goose.imageset/goose.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-goose.imageset/goose.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-goose.imageset/goose.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-grok-build.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-grok-build.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-grok-build.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-grok-build.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-grok-build.imageset/grok-build.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-grok-build.imageset/grok-build.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-grok-build.imageset/grok-build.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-grok-build.imageset/grok-build.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-harn.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-harn.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-harn.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-harn.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-harn.imageset/harn.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-harn.imageset/harn.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-harn.imageset/harn.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-harn.imageset/harn.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-junie.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-junie.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-junie.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-junie.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-junie.imageset/junie.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-junie.imageset/junie.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-junie.imageset/junie.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-junie.imageset/junie.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kilo.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kilo.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kilo.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kilo.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kilo.imageset/kilo.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kilo.imageset/kilo.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kilo.imageset/kilo.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kilo.imageset/kilo.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimchi.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimchi.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimchi.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimchi.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimchi.imageset/kimchi.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimchi.imageset/kimchi.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimchi.imageset/kimchi.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimchi.imageset/kimchi.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimi.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimi.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimi.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimi.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimi.imageset/kimi.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimi.imageset/kimi.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimi.imageset/kimi.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kimi.imageset/kimi.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kiro.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kiro.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kiro.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kiro.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kiro.imageset/kiro.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kiro.imageset/kiro.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kiro.imageset/kiro.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-kiro.imageset/kiro.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minimax-code.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minimax-code.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minimax-code.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minimax-code.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minimax-code.imageset/minimax-code.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minimax-code.imageset/minimax-code.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minimax-code.imageset/minimax-code.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minimax-code.imageset/minimax-code.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minion-code.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minion-code.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minion-code.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minion-code.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minion-code.imageset/minion-code.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minion-code.imageset/minion-code.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minion-code.imageset/minion-code.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-minion-code.imageset/minion-code.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-mistral-vibe.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-mistral-vibe.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-mistral-vibe.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-mistral-vibe.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-mistral-vibe.imageset/mistral-vibe.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-mistral-vibe.imageset/mistral-vibe.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-mistral-vibe.imageset/mistral-vibe.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-mistral-vibe.imageset/mistral-vibe.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-nova.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-nova.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-nova.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-nova.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-nova.imageset/nova.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-nova.imageset/nova.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-nova.imageset/nova.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-nova.imageset/nova.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-opencode.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-opencode.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-opencode.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-opencode.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-opencode.imageset/opencode.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-opencode.imageset/opencode.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-opencode.imageset/opencode.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-opencode.imageset/opencode.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-pi-acp.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-pi-acp.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-pi-acp.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-pi-acp.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-pi-acp.imageset/pi-acp.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-pi-acp.imageset/pi-acp.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-pi-acp.imageset/pi-acp.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-pi-acp.imageset/pi-acp.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-poolside.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-poolside.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-poolside.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-poolside.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-poolside.imageset/poolside.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-poolside.imageset/poolside.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-poolside.imageset/poolside.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-poolside.imageset/poolside.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qoder.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qoder.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qoder.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qoder.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qoder.imageset/qoder.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qoder.imageset/qoder.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qoder.imageset/qoder.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qoder.imageset/qoder.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qwen-code.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qwen-code.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qwen-code.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qwen-code.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qwen-code.imageset/qwen-code.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qwen-code.imageset/qwen-code.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qwen-code.imageset/qwen-code.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-qwen-code.imageset/qwen-code.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-sigit.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-sigit.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-sigit.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-sigit.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-sigit.imageset/sigit.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-sigit.imageset/sigit.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-sigit.imageset/sigit.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-sigit.imageset/sigit.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-stakpak.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-stakpak.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-stakpak.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-stakpak.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-stakpak.imageset/stakpak.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-stakpak.imageset/stakpak.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-stakpak.imageset/stakpak.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-stakpak.imageset/stakpak.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-vtcode.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-vtcode.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-vtcode.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-vtcode.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-vtcode.imageset/vtcode.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-vtcode.imageset/vtcode.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-vtcode.imageset/vtcode.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/agent-vtcode.imageset/vtcode.svgdiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/computer-linux.imageset/Contents.json b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/computer-linux.imageset/Contents.jsonsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/computer-linux.imageset/Contents.jsonrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/computer-linux.imageset/Contents.jsondiff --git a/kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/computer-linux.imageset/linux.svg b/apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/computer-linux.imageset/linux.svgsimilarity index 100%rename from kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/computer-linux.imageset/linux.svgrename to apps/ios/Kit/Sources/CodyncUI/Resources/AgentIcons.xcassets/computer-linux.imageset/linux.svgdiff --git a/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift b/apps/ios/Kit/Sources/CodyncUI/Routines/RoutineEditorView.swiftsimilarity index 96%rename from kit/Sources/CodyncUI/Routines/RoutineEditorView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Routines/RoutineEditorView.swiftindex c819650d..c8f07299 100644--- a/kit/Sources/CodyncUI/Routines/RoutineEditorView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Routines/RoutineEditorView.swift@@ -49,12 +49,7 @@ struct RoutineEditorView: View {VStack(spacing: 0) {ModalHeader(routine == nil ? "Set up a routine" : "Edit routine")Group {- #if os(macOS)- // The card fits the form; it scrolls only when taller than the window allows.- ViewThatFits(in: .vertical) { form; ScrollView { form } }- #elseScrollView { form }.scrollDismissesKeyboard(.interactively)- #endif}.disabled(busy || !loaded)footer@@ -254,7 +249,6 @@ struct RoutineEditorView: View {Label("Connect to this computer to save your routine.", systemImage: "wifi.slash").appFont(.caption).foregroundStyle(Palette.danger)}- #if os(iOS)if loaded, !model.isOffline,name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||instruction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {@@ -262,16 +256,11 @@ struct RoutineEditorView: View {.appFont(.caption).foregroundStyle(Palette.secondary)}HStack(spacing: 16) { routineActions; saveButton }- #else- HStack(spacing: 16) { routineActions; Spacer(minLength: 0); saveButton }- #endif}.padding(20).frame(maxWidth: .infinity, alignment: .leading)- #if os(iOS).padding(.bottom, 16).background(Palette.background)- #endif}/// An existing routine's own actions: delete and run it now.@@ -297,9 +286,7 @@ struct RoutineEditorView: View {Text(busy ? "Saving…" : routine == nil ? "Create routine" : "Save changes").fixedSize(horizontal: false, vertical: true)}- #if os(iOS).frame(maxWidth: .infinity, minHeight: 26)- #endif}.buttonStyle(.primary).disabled(!canSave)diff --git a/kit/Sources/CodyncUI/Routines/RoutineWebhookPanel.swift b/apps/ios/Kit/Sources/CodyncUI/Routines/RoutineWebhookPanel.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Routines/RoutineWebhookPanel.swiftrename to apps/ios/Kit/Sources/CodyncUI/Routines/RoutineWebhookPanel.swiftdiff --git a/kit/Sources/CodyncUI/Routines/RoutinesView.swift b/apps/ios/Kit/Sources/CodyncUI/Routines/RoutinesView.swiftsimilarity index 98%rename from kit/Sources/CodyncUI/Routines/RoutinesView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Routines/RoutinesView.swiftindex 0d764de6..d64fcfc2 100644--- a/kit/Sources/CodyncUI/Routines/RoutinesView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Routines/RoutinesView.swift@@ -59,9 +59,6 @@ struct RoutinesView: View {}Task { await load() }}- #if os(macOS)- .frame(width: 540).frame(maxHeight: 700)- #endif}}diff --git a/kit/Sources/CodyncUI/Screen/ScreenCanvas.swift b/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenCanvas.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Screen/ScreenCanvas.swiftrename to apps/ios/Kit/Sources/CodyncUI/Screen/ScreenCanvas.swiftindex 782ec768..fbd3a18c 100644--- a/kit/Sources/CodyncUI/Screen/ScreenCanvas.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenCanvas.swift@@ -1,4 +1,3 @@-#if os(iOS)import CodyncKitimport SwiftUIimport UIKit@@ -438,4 +437,3 @@ struct ScreenCanvasView: UIViewRepresentable {canvas.attach(nil)}}-#endifdiff --git a/kit/Sources/CodyncUI/Screen/ScreenSession.swift b/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenSession.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Screen/ScreenSession.swiftrename to apps/ios/Kit/Sources/CodyncUI/Screen/ScreenSession.swiftindex eacdd4e6..80096b8a 100644--- a/kit/Sources/CodyncUI/Screen/ScreenSession.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenSession.swift@@ -1,4 +1,3 @@-#if os(iOS)import CodyncKitimport Foundationimport Observation@@ -332,4 +331,3 @@ private final class WeakBox: Sendable {@MainActor weak var value: ScreenSession?@MainActor init(_ value: ScreenSession) { self.value = value }}-#endifdiff --git a/kit/Sources/CodyncUI/Screen/ScreenView.swift b/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenView.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Screen/ScreenView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Screen/ScreenView.swiftindex a64f88d6..4d9ac83e 100644--- a/kit/Sources/CodyncUI/Screen/ScreenView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Screen/ScreenView.swift@@ -1,4 +1,3 @@-#if os(iOS)import CodyncKitimport SwiftUIimport UIKit@@ -371,4 +370,3 @@ public enum OrientationLock {}}}-#endifdiff --git a/kit/Sources/CodyncUI/Store/AccountStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Store/AccountStore.swiftrename to apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swiftdiff --git a/kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Store/BotStore.swiftrename to apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftdiff --git a/kit/Sources/CodyncUI/Store/ComputerSelection.swift b/apps/ios/Kit/Sources/CodyncUI/Store/ComputerSelection.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Store/ComputerSelection.swiftrename to apps/ios/Kit/Sources/CodyncUI/Store/ComputerSelection.swiftdiff --git a/kit/Sources/CodyncUI/Thread/Attachments.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Attachments.swiftsimilarity index 98%rename from kit/Sources/CodyncUI/Thread/Attachments.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/Attachments.swiftindex 576a1d56..39dac13e 100644--- a/kit/Sources/CodyncUI/Thread/Attachments.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Attachments.swift@@ -120,9 +120,6 @@ struct AttachmentList: View {.padding(12)}.background(Palette.background)- #if os(macOS)- .frame(width: 720, height: 560)- #endif}}diff --git a/kit/Sources/CodyncUI/Thread/ChatRows+iOS.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows+iOS.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Thread/ChatRows+iOS.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows+iOS.swiftindex de720474..3cb16728 100644--- a/kit/Sources/CodyncUI/Thread/ChatRows+iOS.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows+iOS.swift@@ -1,4 +1,3 @@-#if os(iOS)import CodyncKitimport SwiftUI@@ -69,4 +68,3 @@ extension EnvironmentValues {/// The reader is scrolling the conversation: streamed text holds still until they stop.@Entry var conversationScrolling = false}-#endifdiff --git a/kit/Sources/CodyncUI/Thread/ChatRows.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swiftsimilarity index 91%rename from kit/Sources/CodyncUI/Thread/ChatRows.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swiftindex 4d97538f..13a845ab 100644--- a/kit/Sources/CodyncUI/Thread/ChatRows.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift@@ -137,17 +137,7 @@ struct UserBubble: View {AttachmentList(attachments: attachments, botId: entry.botId)}if !(entry.data.text ?? "").isEmpty { text }- #if os(macOS)- HStack(spacing: 6) {- if hovering, entry.data.status == nil || entry.data.status == "sent" {- MessageActions(reactions: model.reactionPick(entry), reply: reply) { Pasteboard.copy(entry.data.text) }- }- status- }- .frame(minHeight: MessageActions.height)- #elsestatus- #endif}.hoverTracking($hovering).frame(maxWidth: .infinity, alignment: .trailing)@@ -200,11 +190,7 @@ struct UserBubble: View {case "delivering":Text("Delivered to the computer").appFont(.caption2).foregroundStyle(Palette.tertiary)default:- #if os(macOS)- Text(entry.date, style: .time).appFont(.system(size: 10)).foregroundStyle(Palette.tertiary)- #elseEmptyView()- #endif}}}@@ -215,20 +201,14 @@ struct AgentBubble: View {var reply: (() -> Void)?@Environment(BotStore.self) private var model@State private var hovering = false- #if os(iOS)@Environment(\.accessibilityReduceMotion) private var reduceMotion- #endif/// The reply's text. iPhone: revealed steadily as it's written; the turn's next text/// segment takes the bubble over with a cross-fade instead of retyping.@ViewBuilder private var text: some View {- #if os(iOS)StreamingMarkdown(text: entry.data.text ?? "", live: entry.data.final == false).id(entry.id).transition(.opacity)- #else- MarkdownText(entry.data.text ?? "", streaming: entry.data.final == false)- #endif}var body: some View {@@ -245,28 +225,10 @@ struct AgentBubble: View {if let reply { items.insert(MenuItem("Reply in thread", icon: "arrowshape.turn.up.left", action: reply), at: 1) }return items}- #if os(macOS)- HStack(spacing: 6) {- Text(entry.date, style: .time)- .appFont(.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)- #if os(macOS)- .padding(.trailing, 64)- #else.animation(Motion.reduced(Motion.layout, reduceMotion), value: entry.id).padding(.trailing, 40)- #endif}}@@ -436,13 +398,7 @@ private struct HoverTracking: ViewModifier {@Environment(\.accessibilityReduceMotion) private var reduceMotionfunc body(content: Content) -> some View {- #if os(macOS)- content- .contentShape(Rectangle())- .onHover { h in withAnimation(Motion.reduced(Motion.hover, reduceMotion)) { hovering = h } }- #elsecontent- #endif}}diff --git a/kit/Sources/CodyncUI/Thread/Composer.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swiftsimilarity index 86%rename from kit/Sources/CodyncUI/Thread/Composer.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swiftindex 33f6e14a..a6d4d45d 100644--- a/kit/Sources/CodyncUI/Thread/Composer.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift@@ -22,13 +22,9 @@ struct Composer: View {@State private var pickingFiles = false@State private var pickingPhotos = false@State private var photoItems: [PhotosPickerItem] = []- #if os(iOS)/// The clipboard's `changeCount` last pasted (or passed on), so one copy is offered once.@State private var pasteCount = -1@State private var clipboardTick = 0- #else- @State private var pasteMonitor: Any?- #endif@FocusState private var focused: Bool/// One line of the field's text, following Dynamic Type: the send button centers on the last line.@ScaledMetric(relativeTo: .body) private var lineHeight = InterfaceMetrics.value(mac: 15, mobile: 22)@@ -101,21 +97,15 @@ struct Composer: View {/// The one-line field's height; the + circle matches it.private var fieldHeight: CGFloat { max(textLineHeight + 2 * fieldPadding, buttonSize) + 2 * boxPadding }private var textLineHeight: CGFloat {- #if os(macOS)- ceil(typography.pointSize * 1.25)- #elselineHeight- #endif}private var field: some View {HStack(alignment: .bottom, spacing: 8) {if canAttach { addButton }VStack(alignment: .leading, spacing: 0) {- #if os(iOS)let _ = clipboardTickif clipboardOffer { pasteOffer.transition(.move(edge: .bottom).combined(with: .opacity)) }- #endifif !files.isEmpty {fileChips.transition(.move(edge: .bottom).combined(with: .opacity))}@@ -125,18 +115,10 @@ struct Composer: View {.animation(Motion.layout, value: draft)}.animation(Motion.layout, value: files.map(\.id))- #if os(iOS)// The clipboard isn't observable: look again when typing starts or the app comes back..onChange(of: focused) { _, _ in clipboardTick += 1 }.onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in clipboardTick += 1 }.onReceive(NotificationCenter.default.publisher(for: UIPasteboard.changedNotification)) { _ in clipboardTick += 1 }- #else- .onAppear(perform: installPasteMonitor)- .onDisappear {- if let pasteMonitor { NSEvent.removeMonitor(pasteMonitor) }- pasteMonitor = nil- }- #endif.dropDestination(for: PickedFile.self) { picked, _ inguard canAttach else { return false }append(picked.map(\.file))@@ -145,21 +127,15 @@ struct Composer: View {.fileImporter(isPresented: $pickingFiles, allowedContentTypes: [.item], allowsMultipleSelection: true) { result inif case .success(let urls) = result { add(urls) }}- #if os(iOS).photosPicker(isPresented: $pickingPhotos, selection: $photoItems, maxSelectionCount: 10, matching: .images).onChange(of: photoItems) { _, items inguard !items.isEmpty else { return }photoItems = []Task { await addPhotos(items) }}- #endif.padding(.horizontal, 16).padding(.top, 6).padding(.bottom, 16)- #if os(macOS)- .frame(maxWidth: 820)- .frame(maxWidth: .infinity)- #endif}private enum Trailing: Equatable {@@ -244,7 +220,6 @@ struct Composer: View {/// Photos or files (iPhone, a system menu), files (Mac); dropping files on the box works too.@ViewBuilder private var addButton: some View {- #if os(iOS)DropdownMenu {var items = [MenuItem("Photos", icon: "photo.on.rectangle") { pickingPhotos = true },MenuItem("Files", icon: "folder") { pickingFiles = true }]@@ -254,12 +229,6 @@ struct Composer: View {return items} label: { addLabel }.accessibilityLabel("Add files")- #else- Button { pickingFiles = true } label: { addLabel }- .buttonStyle(PressScale())- .accessibilityLabel("Add files")- .help("Add files")- #endif}private var addLabel: some View {@@ -271,7 +240,6 @@ struct Composer: View {.contentShape(Circle())}- #if os(iOS)private var pasteOffer: some View {HStack(spacing: 6) {Button(action: pasteFiles) {@@ -292,7 +260,6 @@ struct Composer: View {.padding(.horizontal, 10).padding(.top, 8)}- #endifprivate var fileChips: some View {ScrollView(.horizontal, showsIndicators: false) {@@ -347,24 +314,11 @@ struct Composer: View {/// Images (or files) on the clipboard become attachments.private func pasteFiles() {- #if os(iOS)let providers = UIPasteboard.general.itemProviderspasteCount = UIPasteboard.general.changeCount- #else- let providers = (NSPasteboard.general.pasteboardItems ?? []).compactMap { item -> NSItemProvider? in- if let url = item.string(forType: .fileURL).flatMap(URL.init(string:)) { return NSItemProvider(contentsOf: url) }- for type in [NSPasteboard.PasteboardType.png, .tiff] {- if let data = item.data(forType: type) {- return NSItemProvider(item: data as NSData, typeIdentifier: type == .png ? UTType.png.identifier : UTType.tiff.identifier)- }- }- return nil- }- #endifTask { append(await PickedFile.load(providers)) }}- #if os(iOS)/// Photos go out as JPEG: HEIC isn't something every agent can read.private func addPhotos(_ items: [PhotosPickerItem]) async {let stamp = Int(Date.now.timeIntervalSince1970)@@ -381,24 +335,6 @@ struct Composer: View {private var clipboardOffer: Bool {canAttach && focused && UIPasteboard.general.hasImages && UIPasteboard.general.changeCount != pasteCount}- #else- /// ⌘V with a copied image or file (the text field alone would paste nothing, or just- /// the file's name).- private func installPasteMonitor() {- guard pasteMonitor == nil else { return }- pasteMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in- let consumed = MainActor.assumeIsolated {- guard focused, canAttach, event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command,- event.charactersIgnoringModifiers == "v" else { return false }- let types = NSPasteboard.general.types ?? []- guard types.contains(.fileURL) || (!types.contains(.string) && (types.contains(.png) || types.contains(.tiff))) else { return false }- pasteFiles()- return true- }- return consumed ? nil : event- }- }- #endifprivate func mention(_ member: Bot) {guard let at = draft.lastIndex(of: "@") else { return }diff --git a/kit/Sources/CodyncUI/Thread/ConversationFollow+iOS.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ConversationFollow+iOS.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Thread/ConversationFollow+iOS.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/ConversationFollow+iOS.swiftindex 753cf324..b3abfde1 100644--- a/kit/Sources/CodyncUI/Thread/ConversationFollow+iOS.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ConversationFollow+iOS.swift@@ -1,4 +1,3 @@-#if os(iOS)import CodyncKitimport SwiftUI@@ -157,4 +156,3 @@ struct JumpToLatest: View {.animation(Motion.reduced(Motion.layout, reduceMotion), value: visible)}}-#endifdiff --git a/kit/Sources/CodyncUI/Thread/ConversationTypography.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ConversationTypography.swiftsimilarity index 75%rename from kit/Sources/CodyncUI/Thread/ConversationTypography.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/ConversationTypography.swiftindex 002c88bd..e8059f0d 100644--- a/kit/Sources/CodyncUI/Thread/ConversationTypography.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ConversationTypography.swift@@ -18,36 +18,19 @@ public struct ConversationTypography: Sendable {}public var scale: CGFloat {- #if os(macOS)- pointSize / Self.defaultSize- #else1- #endif}var body: Font {- #if os(macOS)- .system(size: pointSize)- #else.body- #endif}func heading(level: Int) -> Font {- #if os(macOS)- .system(size: (level == 1 ? 15 : level == 2 ? 13 : 11) * scale,- weight: level == 2 ? .semibold : .bold)- #elselevel == 1 ? .title3.bold() : level == 2 ? .headline : .subheadline.bold()- #endif}var code: Font {- #if os(macOS)- .system(size: 10 * scale, design: .monospaced)- #else.system(.footnote, design: .monospaced)- #endif}}diff --git a/kit/Sources/CodyncUI/Thread/MarkdownBlocks.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/MarkdownBlocks.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Thread/MarkdownBlocks.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/MarkdownBlocks.swiftdiff --git a/kit/Sources/CodyncUI/Thread/MarkdownText+iOS.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/MarkdownText+iOS.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Thread/MarkdownText+iOS.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/MarkdownText+iOS.swiftindex 29cdfc72..52477452 100644--- a/kit/Sources/CodyncUI/Thread/MarkdownText+iOS.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/MarkdownText+iOS.swift@@ -1,4 +1,3 @@-#if os(iOS)import CodyncKitimport SwiftUI@@ -176,4 +175,3 @@ private struct TrailingFade: TextRenderer {}}}-#endifdiff --git a/kit/Sources/CodyncUI/Thread/PermissionCard.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/PermissionCard.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Thread/PermissionCard.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/PermissionCard.swiftdiff --git a/kit/Sources/CodyncUI/Thread/ReadingConversation.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ReadingConversation.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Thread/ReadingConversation.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/ReadingConversation.swiftdiff --git a/kit/Sources/CodyncUI/Thread/RepliesView+iOS.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/RepliesView+iOS.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Thread/RepliesView+iOS.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/RepliesView+iOS.swiftindex 6a47ac5f..c43e2f35 100644--- a/kit/Sources/CodyncUI/Thread/RepliesView+iOS.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/RepliesView+iOS.swift@@ -1,4 +1,3 @@-#if os(iOS)import CodyncKitimport SwiftUI@@ -55,4 +54,3 @@ extension RepliesView {}}}-#endifdiff --git a/kit/Sources/CodyncUI/Thread/RepliesView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/RepliesView.swiftsimilarity index 95%rename from kit/Sources/CodyncUI/Thread/RepliesView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/RepliesView.swiftindex 34f56f83..81e57591 100644--- a/kit/Sources/CodyncUI/Thread/RepliesView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/RepliesView.swift@@ -11,10 +11,8 @@ struct RepliesView: View {let close: () -> Void@Environment(BotStore.self) var model@State var showTrace = false- #if os(iOS)@State var following = true@Environment(\.accessibilityReduceMotion) var reduceMotion- #endifvar chat: Bot? { model.bots[botId] }var root: Entry? { model.allEntries(botId).first { $0.id == rootId } }@@ -53,9 +51,6 @@ struct RepliesView: View {.readingConversation(botId, thread: rootId).codyncSheet(isPresented: $showTrace) {TraceView(botId: botId, thread: rootId)- #if os(macOS)- .frame(width: 620, height: 560)- #endif}}}diff --git a/kit/Sources/CodyncUI/Thread/ThreadView+iOS.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView+iOS.swiftsimilarity index 99%rename from kit/Sources/CodyncUI/Thread/ThreadView+iOS.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView+iOS.swiftindex a4d2cb28..1cc720b9 100644--- a/kit/Sources/CodyncUI/Thread/ThreadView+iOS.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView+iOS.swift@@ -1,4 +1,3 @@-#if os(iOS)import CodyncKitimport SwiftUIimport UIKit@@ -174,4 +173,3 @@ extension ThreadView {editing = EditorRequest(BotDraft(bot))}}-#endifdiff --git a/kit/Sources/CodyncUI/Thread/ThreadView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swiftsimilarity index 96%rename from kit/Sources/CodyncUI/Thread/ThreadView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swiftindex dc24e1db..3b3b006f 100644--- a/kit/Sources/CodyncUI/Thread/ThreadView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift@@ -28,9 +28,6 @@ public struct ThreadView: View {@State var showRoutines = false@State var routineId: String?@State var routineRequest = UUID()- #if os(macOS)- @State var isAtBottom = true- #else/// iPhone: the chat stays on the newest message until the reader scrolls away.@State var following = true/// The oldest message rendered (nil: the latest page).@@ -40,11 +37,7 @@ public struct ThreadView: View {@State var keepingPlace: String?/// The top of the rendered messages is within reach.@State var topVisible = false- #endif@Environment(\.accessibilityReduceMotion) var reduceMotion- #if os(macOS)- @Environment(\.conversationTypography) var typography- #endifvar bot: Bot? { model.bots[botId] }@@ -93,9 +86,6 @@ public struct ThreadView: View {.readingConversation(botId).codyncSheet(isPresented: $showTrace) {TraceView(botId: botId)- #if os(macOS)- .frame(width: 620, height: 560)- #endif}.codyncSheet(item: $templateRequest) { request inBotTemplateView(draft: request.draft)@@ -105,9 +95,6 @@ public struct ThreadView: View {}.codyncSheet(isPresented: $editingGroup) {GroupEditorView(group: bot)- #if os(macOS)- .frame(width: 420, height: 560)- #endif}.codyncDialog("Start a new session?", isPresented: $confirmNewSession,message: "The conversation stays here, but the agent starts with a fresh context.") {@@ -119,9 +106,6 @@ public struct ThreadView: View {withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { showRoutines = false }}.padding(20)}- #if os(macOS)- .frame(width: 440, height: 580)- #endif}.deleteBotConfirmation($confirmDelete) { dismiss() }}@@ -151,9 +135,7 @@ public struct ThreadView: View {} openThread: { root inwithAnimation(Motion.reduced(Motion.layout, reduceMotion)) { openThread = ThreadTarget(id: root.id) }}- #if os(iOS).equatable()- #endif}}}diff --git a/kit/Sources/CodyncUI/Thread/TraceView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/TraceView.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Thread/TraceView.swiftrename to apps/ios/Kit/Sources/CodyncUI/Thread/TraceView.swiftdiff --git a/kit/Sources/CodyncUI/UpdateNeededCard.swift b/apps/ios/Kit/Sources/CodyncUI/UpdateNeededCard.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/UpdateNeededCard.swiftrename to apps/ios/Kit/Sources/CodyncUI/UpdateNeededCard.swiftdiff --git a/kit/Sources/CodyncUI/Usage/UsageViews.swift b/apps/ios/Kit/Sources/CodyncUI/Usage/UsageViews.swiftsimilarity index 100%rename from kit/Sources/CodyncUI/Usage/UsageViews.swiftrename to apps/ios/Kit/Sources/CodyncUI/Usage/UsageViews.swiftdiff --git a/kit/Tests/CodyncKitTests/ActivityPresentationTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ActivityPresentationTests.swiftsimilarity index 100%rename from kit/Tests/CodyncKitTests/ActivityPresentationTests.swiftrename to apps/ios/Kit/Tests/CodyncKitTests/ActivityPresentationTests.swiftdiff --git a/kit/Tests/CodyncKitTests/AgentModelsTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/AgentModelsTests.swiftsimilarity index 100%rename from kit/Tests/CodyncKitTests/AgentModelsTests.swiftrename to apps/ios/Kit/Tests/CodyncKitTests/AgentModelsTests.swiftdiff --git a/apps/ios/Kit/Tests/CodyncKitTests/AppFontTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/AppFontTests.swiftnew file mode 100644index 00000000..167b2c53--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncKitTests/AppFontTests.swift@@ -0,0 +1,4 @@+import SwiftUI+import Testing+@testable import CodyncKit+diff --git a/kit/Tests/CodyncKitTests/ChannelTransportTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swiftsimilarity index 100%rename from kit/Tests/CodyncKitTests/ChannelTransportTests.swiftrename to apps/ios/Kit/Tests/CodyncKitTests/ChannelTransportTests.swiftdiff --git a/kit/Tests/CodyncKitTests/CodyncKitTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/CodyncKitTests.swiftsimilarity index 100%rename from kit/Tests/CodyncKitTests/CodyncKitTests.swiftrename to apps/ios/Kit/Tests/CodyncKitTests/CodyncKitTests.swiftdiff --git a/kit/Tests/CodyncKitTests/ConnectionRequestTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ConnectionRequestTests.swiftsimilarity index 100%rename from kit/Tests/CodyncKitTests/ConnectionRequestTests.swiftrename to apps/ios/Kit/Tests/CodyncKitTests/ConnectionRequestTests.swiftdiff --git a/kit/Tests/CodyncKitTests/Fixtures/events.txt b/apps/ios/Kit/Tests/CodyncKitTests/Fixtures/events.txtsimilarity index 100%rename from kit/Tests/CodyncKitTests/Fixtures/events.txtrename to apps/ios/Kit/Tests/CodyncKitTests/Fixtures/events.txtdiff --git a/kit/Tests/CodyncKitTests/Fixtures/thinking-orbs-golden.json b/apps/ios/Kit/Tests/CodyncKitTests/Fixtures/thinking-orbs-golden.jsonsimilarity index 100%rename from kit/Tests/CodyncKitTests/Fixtures/thinking-orbs-golden.jsonrename to apps/ios/Kit/Tests/CodyncKitTests/Fixtures/thinking-orbs-golden.jsondiff --git a/kit/Tests/CodyncKitTests/PairingStorageTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/PairingStorageTests.swiftsimilarity index 100%rename from kit/Tests/CodyncKitTests/PairingStorageTests.swiftrename to apps/ios/Kit/Tests/CodyncKitTests/PairingStorageTests.swiftdiff --git a/kit/Tests/CodyncKitTests/PushAlertTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/PushAlertTests.swiftsimilarity index 100%rename from kit/Tests/CodyncKitTests/PushAlertTests.swiftrename to apps/ios/Kit/Tests/CodyncKitTests/PushAlertTests.swiftdiff --git a/kit/Tests/CodyncKitTests/RelayVectorsTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/RelayVectorsTests.swiftsimilarity index 99%rename from kit/Tests/CodyncKitTests/RelayVectorsTests.swiftrename to apps/ios/Kit/Tests/CodyncKitTests/RelayVectorsTests.swiftindex 4c40226b..72cd45cf 100644--- a/kit/Tests/CodyncKitTests/RelayVectorsTests.swift+++ b/apps/ios/Kit/Tests/CodyncKitTests/RelayVectorsTests.swift@@ -9,7 +9,7 @@ struct Vectors: Sendable {var json: [String: Any] { (try? JSONSerialization.jsonObject(with: data) as? [String: Any]) ?? [:] }static let shared = Vectors(data: (try? Data(contentsOf: URL(filePath: #filePath).deletingLastPathComponent()- .appending(path: "../../../docs/reference/fixtures/remote-relay-vectors.json").standardized)) ?? Data())+ .appending(path: "../../../../../docs/reference/fixtures/remote-relay-vectors.json").standardized)) ?? Data())subscript(_ section: String) -> [String: Any] { json[section] as? [String: Any] ?? [:] }diff --git a/kit/Tests/CodyncKitTests/RoutineTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/RoutineTests.swiftsimilarity index 100%rename from kit/Tests/CodyncKitTests/RoutineTests.swiftrename to apps/ios/Kit/Tests/CodyncKitTests/RoutineTests.swiftdiff --git a/kit/Tests/CodyncKitTests/ThinkingOrbGeometryTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ThinkingOrbGeometryTests.swiftsimilarity index 100%rename from kit/Tests/CodyncKitTests/ThinkingOrbGeometryTests.swiftrename to apps/ios/Kit/Tests/CodyncKitTests/ThinkingOrbGeometryTests.swiftdiff --git a/kit/Tests/CodyncKitTests/WorkspaceTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/WorkspaceTests.swiftsimilarity index 100%rename from kit/Tests/CodyncKitTests/WorkspaceTests.swiftrename to apps/ios/Kit/Tests/CodyncKitTests/WorkspaceTests.swiftdiff --git a/kit/Tests/CodyncUITests/ChatItemTests.swift b/apps/ios/Kit/Tests/CodyncUITests/ChatItemTests.swiftsimilarity index 100%rename from kit/Tests/CodyncUITests/ChatItemTests.swiftrename to apps/ios/Kit/Tests/CodyncUITests/ChatItemTests.swiftdiff --git a/kit/Tests/CodyncUITests/ComputerSelectionTests.swift b/apps/ios/Kit/Tests/CodyncUITests/ComputerSelectionTests.swiftsimilarity index 100%rename from kit/Tests/CodyncUITests/ComputerSelectionTests.swiftrename to apps/ios/Kit/Tests/CodyncUITests/ComputerSelectionTests.swiftdiff --git a/kit/Tests/CodyncUITests/ConversationTypographyTests.swift b/apps/ios/Kit/Tests/CodyncUITests/ConversationTypographyTests.swiftsimilarity index 50%rename from kit/Tests/CodyncUITests/ConversationTypographyTests.swiftrename to apps/ios/Kit/Tests/CodyncUITests/ConversationTypographyTests.swiftindex 0c2a1311..f83def72 100644--- a/kit/Tests/CodyncUITests/ConversationTypographyTests.swift+++ b/apps/ios/Kit/Tests/CodyncUITests/ConversationTypographyTests.swift@@ -20,20 +20,3 @@ import Testing#expect(ConversationTypography.step(11, up: false) == 11)}-#if os(macOS)-@Test func conversationTypographyPreservesTextHierarchyWhenResized() throws {- guard #available(macOS 26, *) else { return }- let context = EnvironmentValues().fontResolutionContext- let original = ConversationTypography()- let resized = ConversationTypography(pointSize: 18)- let originalFonts = [original.body, original.code, original.heading(level: 1), original.heading(level: 2), original.heading(level: 3)]- let resizedFonts = [resized.body, resized.code, resized.heading(level: 1), resized.heading(level: 2), resized.heading(level: 3)]- for (originalFont, resizedFont) in zip(originalFonts, resizedFonts) {- let base = originalFont.resolve(in: context)- let changed = resizedFont.resolve(in: context)- #expect(abs(changed.pointSize / base.pointSize - resized.scale) < 0.001)- #expect(base.weight == changed.weight)- #expect(base.isMonospaced == changed.isMonospaced)- }-}-#endifdiff --git a/kit/Tests/CodyncUITests/MarketplacePageTests.swift b/apps/ios/Kit/Tests/CodyncUITests/MarketplacePageTests.swiftsimilarity index 100%rename from kit/Tests/CodyncUITests/MarketplacePageTests.swiftrename to apps/ios/Kit/Tests/CodyncUITests/MarketplacePageTests.swiftdiff --git a/kit/Tests/CodyncUITests/SpeechClipTests.swift b/apps/ios/Kit/Tests/CodyncUITests/SpeechClipTests.swiftsimilarity index 100%rename from kit/Tests/CodyncUITests/SpeechClipTests.swiftrename to apps/ios/Kit/Tests/CodyncUITests/SpeechClipTests.swiftdiff --git a/kit/Tests/CodyncUITests/SpokenTextTests.swift b/apps/ios/Kit/Tests/CodyncUITests/SpokenTextTests.swiftsimilarity index 100%rename from kit/Tests/CodyncUITests/SpokenTextTests.swiftrename to apps/ios/Kit/Tests/CodyncUITests/SpokenTextTests.swiftdiff --git a/kit/Tests/CodyncUITests/StoreTests.swift b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swiftsimilarity index 100%rename from kit/Tests/CodyncUITests/StoreTests.swiftrename to apps/ios/Kit/Tests/CodyncUITests/StoreTests.swiftdiff --git a/kit/Tests/CodyncUITests/VoiceSettingsTests.swift b/apps/ios/Kit/Tests/CodyncUITests/VoiceSettingsTests.swiftsimilarity index 100%rename from kit/Tests/CodyncUITests/VoiceSettingsTests.swiftrename to apps/ios/Kit/Tests/CodyncUITests/VoiceSettingsTests.swiftdiff --git a/apps/linux/.gitignore b/apps/linux/.gitignoredeleted file mode 100644index 2f7896d1..00000000--- a/apps/linux/.gitignore+++ /dev/null@@ -1 +0,0 @@-target/diff --git a/apps/linux/Cargo.lock b/apps/linux/Cargo.lockdeleted file mode 100644index 057c409a..00000000--- a/apps/linux/Cargo.lock+++ /dev/null@@ -1,2277 +0,0 @@-# This file is automatically @generated by Cargo.-# It is not intended for manual editing.-version = 4--[[package]]-name = "async-channel"-version = "2.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"-dependencies = [- "concurrent-queue",- "event-listener-strategy",- "futures-core",- "pin-project-lite",-]--[[package]]-name = "atomic-waker"-version = "1.1.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"--[[package]]-name = "autocfg"-version = "1.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"--[[package]]-name = "aws-lc-rs"-version = "1.18.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e"-dependencies = [- "aws-lc-sys",- "zeroize",-]--[[package]]-name = "aws-lc-sys"-version = "0.45.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27"-dependencies = [- "cc",- "cmake",- "dunce",- "fs_extra",- "pkg-config",-]--[[package]]-name = "base64"-version = "0.23.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"--[[package]]-name = "bitflags"-version = "2.13.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"--[[package]]-name = "bumpalo"-version = "3.20.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"--[[package]]-name = "bytes"-version = "1.12.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"--[[package]]-name = "cairo-rs"-version = "0.22.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "df683f1d30b457964673a5541a4603208ef95ab6873d2a55871895cf310f3b56"-dependencies = [- "bitflags",- "cairo-sys-rs",- "glib",- "libc",-]--[[package]]-name = "cairo-sys-rs"-version = "0.22.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ee548131103ad8f698c6725669647b9c757b3b66992dd6a026037596417bee21"-dependencies = [- "glib-sys",- "libc",- "system-deps 9.0.0",-]--[[package]]-name = "cc"-version = "1.4.7"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313"-dependencies = [- "find-msvc-tools",- "jobserver",- "libc",- "shlex",-]--[[package]]-name = "cfg-expr"-version = "0.20.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fe4ece8474b5f766c63426647e7b4b316b67431ade1036a8313cee24a03ae917"-dependencies = [- "smallvec",- "target-lexicon",-]--[[package]]-name = "cfg-if"-version = "1.0.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"--[[package]]-name = "cfg_aliases"-version = "0.2.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"--[[package]]-name = "chacha20"-version = "0.10.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"-dependencies = [- "cfg-if",- "cpufeatures",- "rand_core",-]--[[package]]-name = "cmake"-version = "0.1.58"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"-dependencies = [- "cc",-]--[[package]]-name = "codync-gtk"-version = "2.6.3"-dependencies = [- "async-channel",- "dirs",- "futures",- "gtk4",- "libadwaita",- "qrcode",- "reqwest",- "serde_json",- "tokio",- "uuid",- "vte4",-]--[[package]]-name = "combine"-version = "4.6.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"-dependencies = [- "bytes",- "memchr",-]--[[package]]-name = "concurrent-queue"-version = "2.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"-dependencies = [- "crossbeam-utils",-]--[[package]]-name = "core-foundation"-version = "0.10.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"-dependencies = [- "core-foundation-sys",- "libc",-]--[[package]]-name = "core-foundation-sys"-version = "0.8.7"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"--[[package]]-name = "cpufeatures"-version = "0.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"-dependencies = [- "libc",-]--[[package]]-name = "crossbeam-utils"-version = "0.8.23"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"--[[package]]-name = "dirs"-version = "7.0.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f"-dependencies = [- "dirs-sys",-]--[[package]]-name = "dirs-sys"-version = "0.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"-dependencies = [- "libc",- "option-ext",- "redox_users",- "windows-sys 0.61.2",-]--[[package]]-name = "displaydoc"-version = "0.2.7"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"-dependencies = [- "proc-macro2",- "quote",- "syn 3.0.6",-]--[[package]]-name = "dunce"-version = "1.0.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"--[[package]]-name = "equivalent"-version = "1.0.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"--[[package]]-name = "errno"-version = "0.3.14"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"-dependencies = [- "libc",- "windows-sys 0.61.2",-]--[[package]]-name = "event-listener"-version = "5.4.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"-dependencies = [- "parking",- "pin-project-lite",-]--[[package]]-name = "event-listener-strategy"-version = "0.5.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"-dependencies = [- "event-listener",- "pin-project-lite",-]--[[package]]-name = "field-offset"-version = "0.3.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f"-dependencies = [- "memoffset",- "rustc_version",-]--[[package]]-name = "find-msvc-tools"-version = "0.1.13"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b"--[[package]]-name = "form_urlencoded"-version = "1.2.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"-dependencies = [- "percent-encoding",-]--[[package]]-name = "fs_extra"-version = "1.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"--[[package]]-name = "futures"-version = "0.3.34"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"-dependencies = [- "futures-channel",- "futures-core",- "futures-executor",- "futures-io",- "futures-sink",- "futures-task",- "futures-util",-]--[[package]]-name = "futures-channel"-version = "0.3.34"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"-dependencies = [- "futures-core",- "futures-sink",-]--[[package]]-name = "futures-core"-version = "0.3.34"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"--[[package]]-name = "futures-executor"-version = "0.3.34"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"-dependencies = [- "futures-core",- "futures-task",- "futures-util",-]--[[package]]-name = "futures-io"-version = "0.3.34"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"--[[package]]-name = "futures-macro"-version = "0.3.34"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"-dependencies = [- "proc-macro2",- "quote",- "syn 3.0.6",-]--[[package]]-name = "futures-sink"-version = "0.3.34"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"--[[package]]-name = "futures-task"-version = "0.3.34"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"--[[package]]-name = "futures-util"-version = "0.3.34"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"-dependencies = [- "futures-channel",- "futures-core",- "futures-io",- "futures-macro",- "futures-sink",- "futures-task",- "memchr",- "pin-project-lite",- "slab",-]--[[package]]-name = "gdk-pixbuf"-version = "0.22.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "25f420376dbee041b2db374ce4573892a36222bb3f6c0c43e24f0d67eae9b646"-dependencies = [- "gdk-pixbuf-sys",- "gio",- "glib",- "libc",-]--[[package]]-name = "gdk-pixbuf-sys"-version = "0.22.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9d5209294ba3775f9b650bf78bfadeba4332089f2329b3e2f6ce0a4957a45bff"-dependencies = [- "gio-sys",- "glib-sys",- "gobject-sys",- "libc",- "system-deps 9.0.0",-]--[[package]]-name = "gdk4"-version = "0.11.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e77c579bac9eff8b84c0625d5f533da6d69988c063062fe92c2e955ede8f28eb"-dependencies = [- "cairo-rs",- "gdk-pixbuf",- "gdk4-sys",- "gio",- "glib",- "libc",- "pango",-]--[[package]]-name = "gdk4-sys"-version = "0.11.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3eff6238a30c1f198fb3c8d3d445fa7faf211d11d9075af0772e6e0ca32ae001"-dependencies = [- "cairo-sys-rs",- "gdk-pixbuf-sys",- "gio-sys",- "glib-sys",- "gobject-sys",- "libc",- "pango-sys",- "pkg-config",- "system-deps 9.0.0",-]--[[package]]-name = "getrandom"-version = "0.2.17"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"-dependencies = [- "cfg-if",- "js-sys",- "libc",- "wasi",- "wasm-bindgen",-]--[[package]]-name = "getrandom"-version = "0.4.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"-dependencies = [- "cfg-if",- "js-sys",- "libc",- "r-efi",- "rand_core",- "wasm-bindgen",-]--[[package]]-name = "gio"-version = "0.22.10"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4620fbafdf19dba814473e19f18e75290cb3338662f6ae35f0402affd3b2b699"-dependencies = [- "futures-channel",- "futures-core",- "futures-io",- "futures-util",- "gio-sys",- "glib",- "libc",- "pin-project-lite",- "smallvec",-]--[[package]]-name = "gio-sys"-version = "0.22.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5"-dependencies = [- "glib-sys",- "gobject-sys",- "libc",- "system-deps 9.0.0",- "windows-sys 0.61.2",-]--[[package]]-name = "glib"-version = "0.22.10"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694"-dependencies = [- "bitflags",- "futures-channel",- "futures-core",- "futures-executor",- "futures-task",- "futures-util",- "gio-sys",- "glib-macros",- "glib-sys",- "gobject-sys",- "libc",- "memchr",- "smallvec",-]--[[package]]-name = "glib-macros"-version = "0.22.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9"-dependencies = [- "heck",- "proc-macro2",- "quote",- "syn 3.0.6",-]--[[package]]-name = "glib-sys"-version = "0.22.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295"-dependencies = [- "libc",- "system-deps 9.0.0",-]--[[package]]-name = "gobject-sys"-version = "0.22.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834"-dependencies = [- "glib-sys",- "libc",- "system-deps 9.0.0",-]--[[package]]-name = "graphene-rs"-version = "0.22.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eb856b9c558971c3f13ab692358926da710b046932a4e087aedcc35b040d7dff"-dependencies = [- "glib",- "graphene-sys",-]--[[package]]-name = "graphene-sys"-version = "0.22.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "97842c7543828f98aa5583aa54fcda28aa84fa2b0f8c556142177f7bbb638057"-dependencies = [- "glib-sys",- "libc",- "system-deps 9.0.0",-]--[[package]]-name = "gsk4"-version = "0.11.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eee23d7425c5281ec5a2f40f7b69384aac66c15861d990d248e9d9c9368be464"-dependencies = [- "cairo-rs",- "gdk4",- "glib",- "graphene-rs",- "gsk4-sys",- "libc",- "pango",-]--[[package]]-name = "gsk4-sys"-version = "0.11.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "27900c92e47df410bbe43b51818104051e3409da43fb88547a41c0bafddfd39c"-dependencies = [- "cairo-sys-rs",- "gdk4-sys",- "glib-sys",- "gobject-sys",- "graphene-sys",- "libc",- "pango-sys",- "system-deps 9.0.0",-]--[[package]]-name = "gtk4"-version = "0.11.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e0f8226c94dd0b65ba2e8fcd8ff402d380e890f6e5a6488e652a0158e827b9bf"-dependencies = [- "cairo-rs",- "field-offset",- "futures-channel",- "gdk-pixbuf",- "gdk4",- "gio",- "glib",- "graphene-rs",- "gsk4",- "gtk4-macros",- "gtk4-sys",- "libc",- "pango",-]--[[package]]-name = "gtk4-macros"-version = "0.11.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eb906c98f0b4cc9002594e337e83f40492aa6dca22c97242f13be5b046c5f338"-dependencies = [- "proc-macro-crate",- "proc-macro2",- "quote",- "syn 3.0.6",-]--[[package]]-name = "gtk4-sys"-version = "0.11.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bd14af0137f269bdecee73404157d2a852f9651af7d68bd1023d3b8b914a14c3"-dependencies = [- "cairo-sys-rs",- "gdk-pixbuf-sys",- "gdk4-sys",- "gio-sys",- "glib-sys",- "gobject-sys",- "graphene-sys",- "gsk4-sys",- "libc",- "pango-sys",- "system-deps 9.0.0",-]--[[package]]-name = "hashbrown"-version = "0.17.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"--[[package]]-name = "heck"-version = "0.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"--[[package]]-name = "http"-version = "1.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"-dependencies = [- "bytes",- "itoa",-]--[[package]]-name = "http-body"-version = "1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"-dependencies = [- "bytes",- "http",-]--[[package]]-name = "http-body-util"-version = "0.1.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"-dependencies = [- "bytes",- "futures-core",- "http",- "http-body",- "pin-project-lite",-]--[[package]]-name = "httparse"-version = "1.10.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"--[[package]]-name = "hyper"-version = "1.11.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"-dependencies = [- "atomic-waker",- "bytes",- "futures-channel",- "futures-core",- "http",- "http-body",- "httparse",- "itoa",- "pin-project-lite",- "smallvec",- "tokio",- "want",-]--[[package]]-name = "hyper-rustls"-version = "0.27.10"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"-dependencies = [- "http",- "hyper",- "hyper-util",- "rustls",- "tokio",- "tokio-rustls",- "tower-service",-]--[[package]]-name = "hyper-util"-version = "0.1.21"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"-dependencies = [- "base64",- "bytes",- "futures-channel",- "futures-util",- "http",- "http-body",- "httparse",- "hyper",- "ipnet",- "libc",- "percent-encoding",- "pin-project-lite",- "socket2",- "tokio",- "tower-service",- "tracing",-]--[[package]]-name = "icu_collections"-version = "2.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"-dependencies = [- "displaydoc",- "potential_utf",- "utf8_iter",- "yoke",- "zerofrom",- "zerovec",-]--[[package]]-name = "icu_locale_core"-version = "2.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"-dependencies = [- "displaydoc",- "litemap",- "tinystr",- "writeable",- "zerovec",-]--[[package]]-name = "icu_normalizer"-version = "2.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"-dependencies = [- "icu_collections",- "icu_normalizer_data",- "icu_properties",- "icu_provider",- "smallvec",- "zerovec",-]--[[package]]-name = "icu_normalizer_data"-version = "2.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"--[[package]]-name = "icu_properties"-version = "2.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"-dependencies = [- "displaydoc",- "icu_collections",- "icu_locale_core",- "icu_properties_data",- "icu_provider",- "zerotrie",- "zerovec",-]--[[package]]-name = "icu_properties_data"-version = "2.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"--[[package]]-name = "icu_provider"-version = "2.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"-dependencies = [- "displaydoc",- "icu_locale_core",- "writeable",- "yoke",- "zerofrom",- "zerotrie",- "zerovec",-]--[[package]]-name = "idna"-version = "1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"-dependencies = [- "idna_adapter",- "smallvec",- "utf8_iter",-]--[[package]]-name = "idna_adapter"-version = "1.2.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"-dependencies = [- "icu_normalizer",- "icu_properties",-]--[[package]]-name = "indexmap"-version = "2.14.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"-dependencies = [- "equivalent",- "hashbrown",-]--[[package]]-name = "io-lifetimes"-version = "2.0.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"--[[package]]-name = "ipnet"-version = "2.12.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"--[[package]]-name = "itoa"-version = "1.0.18"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"--[[package]]-name = "jni"-version = "0.22.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"-dependencies = [- "cfg-if",- "combine",- "jni-macros",- "jni-sys",- "log",- "simd_cesu8",- "thiserror",- "walkdir",- "windows-link",-]--[[package]]-name = "jni-macros"-version = "0.22.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"-dependencies = [- "proc-macro2",- "quote",- "rustc_version",- "simd_cesu8",- "syn 2.0.119",-]--[[package]]-name = "jni-sys"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"-dependencies = [- "jni-sys-macros",-]--[[package]]-name = "jni-sys-macros"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"-dependencies = [- "quote",- "syn 2.0.119",-]--[[package]]-name = "jobserver"-version = "0.1.35"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"-dependencies = [- "getrandom 0.4.3",- "libc",-]--[[package]]-name = "js-sys"-version = "0.3.105"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e"-dependencies = [- "cfg-if",- "futures-util",- "wasm-bindgen",-]--[[package]]-name = "libadwaita"-version = "0.9.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "85b9900e67182a4b5b1f157b448d94f0715c8b9770cce21cf000801917f53bfa"-dependencies = [- "gdk4",- "gio",- "glib",- "gtk4",- "libadwaita-sys",- "pango",-]--[[package]]-name = "libadwaita-sys"-version = "0.9.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "28d3c27642b389852aa99341bd4a4c19ec6f8a2b63ebdd7f5ba1952198079ccd"-dependencies = [- "gdk4-sys",- "gio-sys",- "glib-sys",- "gobject-sys",- "gtk4-sys",- "libc",- "pango-sys",- "system-deps 7.0.8",-]--[[package]]-name = "libc"-version = "0.2.189"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"--[[package]]-name = "libredox"-version = "0.1.25"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"-dependencies = [- "libc",-]--[[package]]-name = "litemap"-version = "0.8.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"--[[package]]-name = "log"-version = "0.4.34"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"--[[package]]-name = "lru-slab"-version = "0.1.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"--[[package]]-name = "memchr"-version = "2.8.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"--[[package]]-name = "memoffset"-version = "0.9.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"-dependencies = [- "autocfg",-]--[[package]]-name = "mio"-version = "1.2.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"-dependencies = [- "libc",- "wasi",- "windows-sys 0.61.2",-]--[[package]]-name = "once_cell"-version = "1.21.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"--[[package]]-name = "openssl-probe"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"--[[package]]-name = "option-ext"-version = "0.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"--[[package]]-name = "pango"-version = "0.22.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0b2022dbbd82e1c42bd950a6f1df9b98c796e725dce5ec275e03cbf9772e4efa"-dependencies = [- "gio",- "glib",- "pango-sys",-]--[[package]]-name = "pango-sys"-version = "0.22.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ca02d64761b74d56cdd4b437db6d73dc95e6c0d40f27e1c707952c0f09052948"-dependencies = [- "glib-sys",- "gobject-sys",- "libc",- "system-deps 9.0.0",-]--[[package]]-name = "parking"-version = "2.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"--[[package]]-name = "percent-encoding"-version = "2.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"--[[package]]-name = "pin-project-lite"-version = "0.2.17"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"--[[package]]-name = "pkg-config"-version = "0.3.34"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"--[[package]]-name = "potential_utf"-version = "0.1.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"-dependencies = [- "zerovec",-]--[[package]]-name = "proc-macro-crate"-version = "3.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"-dependencies = [- "toml_edit",-]--[[package]]-name = "proc-macro2"-version = "1.0.107"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"-dependencies = [- "unicode-ident",-]--[[package]]-name = "qrcode"-version = "0.14.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"--[[package]]-name = "quinn"-version = "0.11.12"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"-dependencies = [- "bytes",- "cfg_aliases",- "pin-project-lite",- "quinn-proto",- "quinn-udp",- "rustc-hash",- "rustls",- "socket2",- "thiserror",- "tokio",- "tracing",- "web-time",-]--[[package]]-name = "quinn-proto"-version = "0.11.18"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a9746dbde176634f4f2f1faf2404e30a31b2bc1e9cafb5329c95d8177a18c9fc"-dependencies = [- "aws-lc-rs",- "bytes",- "getrandom 0.4.3",- "lru-slab",- "rand",- "rand_pcg",- "ring",- "rustc-hash",- "rustls",- "rustls-pki-types",- "slab",- "thiserror",- "tinyvec",- "tracing",- "web-time",-]--[[package]]-name = "quinn-udp"-version = "0.5.15"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"-dependencies = [- "cfg_aliases",- "libc",- "once_cell",- "socket2",- "tracing",- "windows-sys 0.61.2",-]--[[package]]-name = "quote"-version = "1.0.47"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"-dependencies = [- "proc-macro2",-]--[[package]]-name = "r-efi"-version = "6.0.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"--[[package]]-name = "rand"-version = "0.10.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"-dependencies = [- "chacha20",- "getrandom 0.4.3",- "rand_core",-]--[[package]]-name = "rand_core"-version = "0.10.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"--[[package]]-name = "rand_pcg"-version = "0.10.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"-dependencies = [- "rand_core",-]--[[package]]-name = "redox_users"-version = "0.5.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"-dependencies = [- "libredox",- "thiserror",-]--[[package]]-name = "reqwest"-version = "0.13.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"-dependencies = [- "base64",- "bytes",- "futures-core",- "futures-util",- "http",- "http-body",- "http-body-util",- "hyper",- "hyper-rustls",- "hyper-util",- "js-sys",- "log",- "percent-encoding",- "pin-project-lite",- "quinn",- "rustls",- "rustls-pki-types",- "rustls-platform-verifier",- "serde",- "serde_json",- "sync_wrapper",- "tokio",- "tokio-rustls",- "tokio-util",- "tower",- "tower-http",- "tower-service",- "url",- "wasm-bindgen",- "wasm-bindgen-futures",- "wasm-streams",- "web-sys",-]--[[package]]-name = "ring"-version = "0.17.14"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"-dependencies = [- "cc",- "cfg-if",- "getrandom 0.2.17",- "libc",- "untrusted",- "windows-sys 0.52.0",-]--[[package]]-name = "rustc-hash"-version = "2.1.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"--[[package]]-name = "rustc_version"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"-dependencies = [- "semver",-]--[[package]]-name = "rustls"-version = "0.23.45"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"-dependencies = [- "aws-lc-rs",- "once_cell",- "rustls-pki-types",- "rustls-webpki",- "subtle",- "zeroize",-]--[[package]]-name = "rustls-native-certs"-version = "0.8.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"-dependencies = [- "openssl-probe",- "rustls-pki-types",- "schannel",- "security-framework",-]--[[package]]-name = "rustls-pki-types"-version = "1.15.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"-dependencies = [- "web-time",- "zeroize",-]--[[package]]-name = "rustls-platform-verifier"-version = "0.7.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0"-dependencies = [- "core-foundation",- "core-foundation-sys",- "jni",- "log",- "once_cell",- "rustls",- "rustls-native-certs",- "rustls-platform-verifier-android",- "rustls-webpki",- "security-framework",- "security-framework-sys",- "webpki-root-certs",- "windows-sys 0.61.2",-]--[[package]]-name = "rustls-platform-verifier-android"-version = "0.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"--[[package]]-name = "rustls-webpki"-version = "0.103.15"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"-dependencies = [- "aws-lc-rs",- "ring",- "rustls-pki-types",- "untrusted",-]--[[package]]-name = "rustversion"-version = "1.0.23"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"--[[package]]-name = "same-file"-version = "1.0.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"-dependencies = [- "winapi-util",-]--[[package]]-name = "schannel"-version = "0.1.29"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"-dependencies = [- "windows-sys 0.61.2",-]--[[package]]-name = "security-framework"-version = "3.7.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"-dependencies = [- "bitflags",- "core-foundation",- "core-foundation-sys",- "libc",- "security-framework-sys",-]--[[package]]-name = "security-framework-sys"-version = "2.17.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"-dependencies = [- "core-foundation-sys",- "libc",-]--[[package]]-name = "semver"-version = "1.0.28"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"--[[package]]-name = "serde"-version = "1.0.229"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"-dependencies = [- "serde_core",-]--[[package]]-name = "serde_core"-version = "1.0.229"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"-dependencies = [- "serde_derive",-]--[[package]]-name = "serde_derive"-version = "1.0.229"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"-dependencies = [- "proc-macro2",- "quote",- "syn 3.0.6",-]--[[package]]-name = "serde_json"-version = "1.0.151"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"-dependencies = [- "itoa",- "memchr",- "serde",- "serde_core",- "zmij",-]--[[package]]-name = "serde_spanned"-version = "1.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"-dependencies = [- "serde_core",-]--[[package]]-name = "shlex"-version = "2.0.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"--[[package]]-name = "signal-hook-registry"-version = "1.4.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"-dependencies = [- "errno",- "libc",-]--[[package]]-name = "simd_cesu8"-version = "1.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"-dependencies = [- "rustc_version",- "simdutf8",-]--[[package]]-name = "simdutf8"-version = "0.1.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"--[[package]]-name = "slab"-version = "0.4.12"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"--[[package]]-name = "smallvec"-version = "1.16.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891"--[[package]]-name = "socket2"-version = "0.6.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"-dependencies = [- "libc",- "windows-sys 0.61.2",-]--[[package]]-name = "stable_deref_trait"-version = "1.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"--[[package]]-name = "subtle"-version = "2.6.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"--[[package]]-name = "syn"-version = "2.0.119"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"-dependencies = [- "proc-macro2",- "quote",- "unicode-ident",-]--[[package]]-name = "syn"-version = "3.0.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"-dependencies = [- "proc-macro2",- "quote",- "unicode-ident",-]--[[package]]-name = "sync_wrapper"-version = "1.0.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"-dependencies = [- "futures-core",-]--[[package]]-name = "synstructure"-version = "0.14.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"-dependencies = [- "proc-macro2",- "quote",- "syn 3.0.6",-]--[[package]]-name = "system-deps"-version = "7.0.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7"-dependencies = [- "cfg-expr",- "heck",- "pkg-config",- "toml",- "version-compare",-]--[[package]]-name = "system-deps"-version = "9.0.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8a0dae2cbca1f0ff93795713cfe0a4c02f760e3c0b8ae2ab4ec4045808ff429f"-dependencies = [- "cfg-expr",- "heck",- "pkg-config",- "toml",- "version-compare",-]--[[package]]-name = "target-lexicon"-version = "0.13.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"--[[package]]-name = "thiserror"-version = "2.0.21"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"-dependencies = [- "thiserror-impl",-]--[[package]]-name = "thiserror-impl"-version = "2.0.21"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"-dependencies = [- "proc-macro2",- "quote",- "syn 3.0.6",-]--[[package]]-name = "tinystr"-version = "0.8.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"-dependencies = [- "displaydoc",- "zerovec",-]--[[package]]-name = "tinyvec"-version = "1.13.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"--[[package]]-name = "tokio"-version = "1.53.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"-dependencies = [- "bytes",- "libc",- "mio",- "pin-project-lite",- "signal-hook-registry",- "socket2",- "windows-sys 0.61.2",-]--[[package]]-name = "tokio-rustls"-version = "0.26.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67"-dependencies = [- "rustls",- "tokio",-]--[[package]]-name = "tokio-util"-version = "0.7.19"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"-dependencies = [- "bytes",- "futures-core",- "futures-sink",- "pin-project-lite",- "tokio",-]--[[package]]-name = "toml"-version = "1.1.6+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"-dependencies = [- "indexmap",- "serde_core",- "serde_spanned",- "toml_datetime",- "toml_parser",- "toml_writer",- "winnow",-]--[[package]]-name = "toml_datetime"-version = "1.1.1+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"-dependencies = [- "serde_core",-]--[[package]]-name = "toml_edit"-version = "0.25.15+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614"-dependencies = [- "indexmap",- "toml_datetime",- "toml_parser",- "winnow",-]--[[package]]-name = "toml_parser"-version = "1.1.3+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"-dependencies = [- "winnow",-]--[[package]]-name = "toml_writer"-version = "1.1.2+spec-1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"--[[package]]-name = "tower"-version = "0.5.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"-dependencies = [- "futures-core",- "futures-util",- "pin-project-lite",- "sync_wrapper",- "tokio",- "tower-layer",- "tower-service",-]--[[package]]-name = "tower-http"-version = "0.6.11"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"-dependencies = [- "bitflags",- "bytes",- "futures-util",- "http",- "http-body",- "pin-project-lite",- "tower",- "tower-layer",- "tower-service",- "url",-]--[[package]]-name = "tower-layer"-version = "0.3.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"--[[package]]-name = "tower-service"-version = "0.3.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"--[[package]]-name = "tracing"-version = "0.1.44"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"-dependencies = [- "pin-project-lite",- "tracing-core",-]--[[package]]-name = "tracing-core"-version = "0.1.36"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"-dependencies = [- "once_cell",-]--[[package]]-name = "try-lock"-version = "0.2.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"--[[package]]-name = "unicode-ident"-version = "1.0.26"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"--[[package]]-name = "untrusted"-version = "0.9.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"--[[package]]-name = "url"-version = "2.5.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"-dependencies = [- "form_urlencoded",- "idna",- "percent-encoding",- "serde",-]--[[package]]-name = "utf8_iter"-version = "1.0.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"--[[package]]-name = "uuid"-version = "1.26.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"-dependencies = [- "getrandom 0.4.3",- "js-sys",- "wasm-bindgen",-]--[[package]]-name = "version-compare"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"--[[package]]-name = "vte4"-version = "0.10.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c61732974d4915c5112a82506cdc86e19a83d786497c2c8bcd80d065825c695d"-dependencies = [- "cairo-rs",- "gdk4",- "gio",- "glib",- "gtk4",- "io-lifetimes",- "libc",- "pango",- "vte4-sys",-]--[[package]]-name = "vte4-sys"-version = "0.10.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bd99766524f740945b1b3fc516dc2ee76311be2efa8d7a1238f35f04330b9afd"-dependencies = [- "cairo-sys-rs",- "gdk4-sys",- "gio-sys",- "glib-sys",- "gobject-sys",- "gtk4-sys",- "libc",- "pango-sys",- "system-deps 7.0.8",-]--[[package]]-name = "walkdir"-version = "2.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"-dependencies = [- "same-file",- "winapi-util",-]--[[package]]-name = "want"-version = "0.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"-dependencies = [- "try-lock",-]--[[package]]-name = "wasi"-version = "0.11.1+wasi-snapshot-preview1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"--[[package]]-name = "wasm-bindgen"-version = "0.2.128"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf"-dependencies = [- "cfg-if",- "once_cell",- "rustversion",- "wasm-bindgen-macro",- "wasm-bindgen-shared",-]--[[package]]-name = "wasm-bindgen-futures"-version = "0.4.78"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928"-dependencies = [- "js-sys",- "wasm-bindgen",-]--[[package]]-name = "wasm-bindgen-macro"-version = "0.2.128"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed"-dependencies = [- "quote",- "wasm-bindgen-macro-support",-]--[[package]]-name = "wasm-bindgen-macro-support"-version = "0.2.128"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a"-dependencies = [- "bumpalo",- "proc-macro2",- "quote",- "syn 3.0.6",- "wasm-bindgen-shared",-]--[[package]]-name = "wasm-bindgen-shared"-version = "0.2.128"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e"-dependencies = [- "unicode-ident",-]--[[package]]-name = "wasm-streams"-version = "0.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"-dependencies = [- "futures-util",- "js-sys",- "wasm-bindgen",- "wasm-bindgen-futures",- "web-sys",-]--[[package]]-name = "web-sys"-version = "0.3.105"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8"-dependencies = [- "js-sys",- "wasm-bindgen",-]--[[package]]-name = "web-time"-version = "1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"-dependencies = [- "js-sys",- "wasm-bindgen",-]--[[package]]-name = "webpki-root-certs"-version = "1.0.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"-dependencies = [- "rustls-pki-types",-]--[[package]]-name = "winapi-util"-version = "0.1.11"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"-dependencies = [- "windows-sys 0.61.2",-]--[[package]]-name = "windows-link"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"--[[package]]-name = "windows-sys"-version = "0.52.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"-dependencies = [- "windows-targets",-]--[[package]]-name = "windows-sys"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-targets"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"-dependencies = [- "windows_aarch64_gnullvm",- "windows_aarch64_msvc",- "windows_i686_gnu",- "windows_i686_gnullvm",- "windows_i686_msvc",- "windows_x86_64_gnu",- "windows_x86_64_gnullvm",- "windows_x86_64_msvc",-]--[[package]]-name = "windows_aarch64_gnullvm"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"--[[package]]-name = "windows_aarch64_msvc"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"--[[package]]-name = "windows_i686_gnu"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"--[[package]]-name = "windows_i686_gnullvm"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"--[[package]]-name = "windows_i686_msvc"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"--[[package]]-name = "windows_x86_64_gnu"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"--[[package]]-name = "windows_x86_64_gnullvm"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"--[[package]]-name = "windows_x86_64_msvc"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"--[[package]]-name = "winnow"-version = "1.0.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"-dependencies = [- "memchr",-]--[[package]]-name = "writeable"-version = "0.6.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"--[[package]]-name = "yoke"-version = "0.8.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"-dependencies = [- "stable_deref_trait",- "yoke-derive",- "zerofrom",-]--[[package]]-name = "yoke-derive"-version = "0.8.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"-dependencies = [- "proc-macro2",- "quote",- "syn 3.0.6",- "synstructure",-]--[[package]]-name = "zerofrom"-version = "0.1.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"-dependencies = [- "zerofrom-derive",-]--[[package]]-name = "zerofrom-derive"-version = "0.1.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"-dependencies = [- "proc-macro2",- "quote",- "syn 3.0.6",- "synstructure",-]--[[package]]-name = "zeroize"-version = "1.9.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"--[[package]]-name = "zerotrie"-version = "0.2.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"-dependencies = [- "displaydoc",- "yoke",- "zerofrom",-]--[[package]]-name = "zerovec"-version = "0.11.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"-dependencies = [- "yoke",- "zerofrom",- "zerovec-derive",-]--[[package]]-name = "zerovec-derive"-version = "0.11.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"-dependencies = [- "proc-macro2",- "quote",- "syn 3.0.6",-]--[[package]]-name = "zmij"-version = "1.0.23"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"diff --git a/apps/linux/Cargo.toml b/apps/linux/Cargo.tomldeleted file mode 100644index 817436fa..00000000--- a/apps/linux/Cargo.toml+++ /dev/null@@ -1,23 +0,0 @@-[package]-name = "codync-gtk"-version = "2.6.3"-edition = "2024"-description = "Codync for Linux: message your coding-agent bots (GTK 4 + libadwaita)"-license = "MIT"--[[bin]]-name = "codync"-path = "src/main.rs"--[dependencies]-adw = { package = "libadwaita", version = "0.9", features = ["v1_5"] }-gtk = { package = "gtk4", version = "0.11", features = ["v4_14"] }-async-channel = "2"-futures = "0.3"-qrcode = { version = "0.14", default-features = false }-reqwest = { version = "0.13", default-features = false, features = ["rustls", "json", "stream"] }-serde_json = "1"-tokio = { version = "1", features = ["rt-multi-thread", "time", "process"] }-uuid = { version = "1", features = ["v4"] }-dirs = "7"-vte = { package = "vte4", version = "0.10", features = ["v0_70"] }diff --git a/apps/linux/data/com.pokai.Codync.desktop b/apps/linux/data/com.pokai.Codync.desktopdeleted file mode 100644index 3c9f5ba4..00000000--- a/apps/linux/data/com.pokai.Codync.desktop+++ /dev/null@@ -1,9 +0,0 @@-[Desktop Entry]-Type=Application-Name=Codync-Comment=Message your coding-agent bots-Exec=codync-Icon=com.pokai.Codync-Terminal=false-Categories=Development;-StartupWMClass=com.pokai.Codyncdiff --git a/apps/linux/data/com.pokai.Codync.svg b/apps/linux/data/com.pokai.Codync.svgdeleted file mode 100644index b0bc6aa6..00000000--- a/apps/linux/data/com.pokai.Codync.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"><rect width="256" height="256" rx="57.6" fill="#000"/><g fill="#fff"><circle cx="68.27" cy="48.36" r="7.17"/><circle cx="88.18" cy="48.36" r="7.17"/><circle cx="108.09" cy="48.36" r="7.17"/><circle cx="128.00" cy="48.36" r="7.17"/><circle cx="147.91" cy="48.36" r="7.13"/><circle cx="167.82" cy="48.36" r="6.92"/><circle cx="187.73" cy="48.36" r="6.70"/><circle cx="48.36" cy="68.27" r="7.17"/><circle cx="68.27" cy="68.27" r="7.17"/><circle cx="88.18" cy="68.27" r="7.17"/><circle cx="108.09" cy="68.27" r="7.17"/><circle cx="128.00" cy="68.27" r="7.06"/><circle cx="147.91" cy="68.27" r="6.85"/><circle cx="167.82" cy="68.27" r="6.63"/><circle cx="187.73" cy="68.27" r="6.42"/><circle cx="207.64" cy="68.27" r="6.20"/><circle cx="48.36" cy="88.18" r="7.17"/><circle cx="68.27" cy="88.18" r="7.17"/><circle cx="88.18" cy="88.18" r="7.17"/><circle cx="108.09" cy="88.18" r="6.99"/><circle cx="128.00" cy="88.18" r="6.77"/><circle cx="147.91" cy="88.18" r="6.56"/><circle cx="167.82" cy="88.18" r="6.34"/><circle cx="187.73" cy="88.18" r="6.13"/><circle cx="207.64" cy="88.18" r="5.91"/><circle cx="48.36" cy="108.09" r="7.17"/><circle cx="68.27" cy="108.09" r="7.13"/><circle cx="88.18" cy="108.09" r="6.92"/><circle cx="128.00" cy="108.09" r="6.49"/><circle cx="167.82" cy="108.09" r="6.06"/><circle cx="187.73" cy="108.09" r="5.84"/><circle cx="207.64" cy="108.09" r="5.63"/><circle cx="48.36" cy="128.00" r="7.06"/><circle cx="68.27" cy="128.00" r="6.85"/><circle cx="88.18" cy="128.00" r="6.63"/><circle cx="128.00" cy="128.00" r="6.20"/><circle cx="167.82" cy="128.00" r="5.77"/><circle cx="187.73" cy="128.00" r="5.56"/><circle cx="207.64" cy="128.00" r="5.34"/><circle cx="48.36" cy="147.91" r="6.77"/><circle cx="68.27" cy="147.91" r="6.56"/><circle cx="88.18" cy="147.91" r="6.34"/><circle cx="108.09" cy="147.91" r="6.13"/><circle cx="128.00" cy="147.91" r="5.91"/><circle cx="147.91" cy="147.91" r="5.70"/><circle cx="167.82" cy="147.91" r="5.48"/><circle cx="187.73" cy="147.91" r="5.27"/><circle cx="207.64" cy="147.91" r="5.05"/><circle cx="48.36" cy="167.82" r="6.49"/><circle cx="68.27" cy="167.82" r="6.27"/><circle cx="88.18" cy="167.82" r="6.06"/><circle cx="108.09" cy="167.82" r="5.84"/><circle cx="128.00" cy="167.82" r="5.63"/><circle cx="147.91" cy="167.82" r="5.41"/><circle cx="167.82" cy="167.82" r="5.20"/><circle cx="187.73" cy="167.82" r="4.98"/><circle cx="207.64" cy="167.82" r="4.77"/><circle cx="48.36" cy="187.73" r="6.20"/><circle cx="68.27" cy="187.73" r="5.99"/><circle cx="88.18" cy="187.73" r="5.77"/><circle cx="108.09" cy="187.73" r="5.56"/><circle cx="128.00" cy="187.73" r="5.34"/><circle cx="147.91" cy="187.73" r="5.13"/><circle cx="167.82" cy="187.73" r="4.91"/><circle cx="187.73" cy="187.73" r="4.70"/><circle cx="207.64" cy="187.73" r="4.48"/><circle cx="68.27" cy="207.64" r="5.70"/><circle cx="88.18" cy="207.64" r="5.48"/><circle cx="108.09" cy="207.64" r="5.27"/><circle cx="128.00" cy="207.64" r="5.05"/><circle cx="147.91" cy="207.64" r="4.84"/><circle cx="167.82" cy="207.64" r="4.62"/><circle cx="187.73" cy="207.64" r="4.41"/></g></svg>\ No newline at end of filediff --git a/apps/linux/src/avatar.rs b/apps/linux/src/avatar.rsdeleted file mode 100644index 891e7eee..00000000--- a/apps/linux/src/avatar.rs+++ /dev/null@@ -1,398 +0,0 @@-//! Grok-Bot-style characters (same silhouettes and palette as the Apple apps), drawn with cairo.-//! Mirrors CodyncKit/Design/CharacterAvatar.swift: `CharacterAvatar`, `GroupAvatar`, `AvatarWithStatus`.--use gtk::cairo::Context;-use gtk::prelude::*;-use serde_json::Value;-use std::collections::HashMap;-use std::f64::consts::PI;--pub const SHAPES: &[&str] = &[- "blob", "pebble", "squircle", "tablet", "wedge", "hex", "cloud", "teardrop",-];-pub const COLORS: &[(&str, u32)] = &[- ("black", 0x2B2B2B),- ("brown", 0x936439),- ("red", 0xFF263C),- ("orange", 0xFF6700),- ("yellow", 0xFF9800),- ("green", 0x00C972),- ("cyan", 0x00BCA6),- ("blue", 0x1084FE),- ("violet", 0x9159FE),- ("magenta", 0xFF309B),- ("gray", 0x777777),-];--pub fn rgb(hex: u32) -> (f64, f64, f64) {- (- f64::from((hex >> 16) & 0xFF) / 255.0,- f64::from((hex >> 8) & 0xFF) / 255.0,- f64::from(hex & 0xFF) / 255.0,- )-}--pub fn color_of(name: &str) -> u32 {- COLORS- .iter()- .find(|(n, _)| *n == name)- .map_or(0x1084FE, |c| c.1)-}--fn rounded_rect(cr: &Context, x: f64, y: f64, w: f64, h: f64, r: f64) {- cr.new_sub_path();- cr.arc(x + w - r, y + r, r, -PI / 2.0, 0.0);- cr.arc(x + w - r, y + h - r, r, 0.0, PI / 2.0);- cr.arc(x + r, y + h - r, r, PI / 2.0, PI);- cr.arc(x + r, y + r, r, PI, 1.5 * PI);- cr.close_path();-}--fn ellipse(cr: &Context, x: f64, y: f64, w: f64, h: f64) {- cr.save().ok();- cr.translate(x + w / 2.0, y + h / 2.0);- cr.scale(w / 2.0, h / 2.0);- cr.new_sub_path();- cr.arc(0.0, 0.0, 1.0, 0.0, 2.0 * PI);- cr.restore().ok();-}--/// A quadratic curve as the cubic cairo draws.-fn quad_to(cr: &Context, (cx, cy): (f64, f64), (x, y): (f64, f64)) {- let (x0, y0) = cr.current_point().unwrap_or((x, y));- cr.curve_to(- x0 + 2.0 / 3.0 * (cx - x0),- y0 + 2.0 / 3.0 * (cy - y0),- x + 2.0 / 3.0 * (cx - x),- y + 2.0 / 3.0 * (cy - y),- x,- y,- );-}--/// Draws the silhouette into a 100×100 unit box (`CharacterShape`).-fn silhouette(cr: &Context, shape: &str) {- match shape {- "pebble" => ellipse(cr, 0.0, 10.0, 100.0, 80.0),- "squircle" => rounded_rect(cr, 4.0, 4.0, 92.0, 92.0, 30.0),- "tablet" => rounded_rect(cr, 14.0, 0.0, 72.0, 100.0, 22.0),- "wedge" => {- cr.move_to(50.0, 4.0);- quad_to(cr, (90.0, 40.0), (98.0, 86.0));- quad_to(cr, (50.0, 104.0), (2.0, 86.0));- quad_to(cr, (10.0, 40.0), (50.0, 4.0));- cr.close_path();- }- "hex" => {- for i in 0..6 {- let a = f64::from(i) * PI / 3.0 - PI / 2.0;- let (x, y) = (50.0 + a.cos() * 49.0, 50.0 + a.sin() * 49.0);- if i == 0 {- cr.move_to(x, y);- } else {- cr.line_to(x, y);- }- }- cr.close_path();- }- "cloud" => {- ellipse(cr, 0.0, 30.0, 55.0, 55.0);- ellipse(cr, 45.0, 30.0, 55.0, 55.0);- ellipse(cr, 18.0, 8.0, 64.0, 64.0);- rounded_rect(cr, 10.0, 50.0, 80.0, 35.0, 15.0);- }- "teardrop" => {- cr.move_to(50.0, 0.0);- cr.curve_to(62.0, 20.0, 94.0, 38.0, 94.0, 62.0);- cr.arc(50.0, 62.0, 44.0, 0.0, PI);- cr.curve_to(6.0, 38.0, 38.0, 20.0, 50.0, 0.0);- cr.close_path();- }- _ => {- for i in 0..=64 {- let a = f64::from(i) / 64.0 * 2.0 * PI;- let r = 46.0 + 3.5 * (a * 3.0 + 0.6).sin();- let (x, y) = (50.0 + a.cos() * r, 50.0 + a.sin() * r);- if i == 0 {- cr.move_to(x, y);- } else {- cr.line_to(x, y);- }- }- cr.close_path();- }- }-}--#[derive(Clone, Copy, PartialEq)]-pub enum Mood {- Idle,- Working,- Needs,-}--pub fn mood(b: &Value) -> Mood {- match b["status"].as_str() {- Some("needsInput") => Mood::Needs,- Some("working") => Mood::Working,- _ => Mood::Idle,- }-}--/// Small icons use fewer, larger dots so the gaps and hollow eyes survive.-fn grid(size: f64) -> (i32, &'static [i32], &'static [i32]) {- if size < 18.0 {- (7, &[2, 4], &[2, 3])- } else if size < 28.0 {- (9, &[3, 6], &[3, 4])- } else {- (13, &[4, 8], &[4, 5, 6])- }-}--/// A halftone of dots shaded as if the silhouette were a ball (grey ink, the bot's color-/// only on the brightest dots), eyes left hollow. Working swings the light and glances;-/// needing you sends a ripple out from the center.-pub fn draw(- cr: &Context,- size: f64,- shape: &str,- color: &str,- ink: (f64, f64, f64),- mood: Mood,- t: f64,-) {- cr.save().ok();- cr.scale(size / 100.0, size / 100.0);- let (r, g, b) = rgb(color_of(color));- let (cells, eye_cols, all_eye_rows) = grid(size);- let step = 100.0 / f64::from(cells);- let animated = mood != Mood::Idle;- let glance = if mood == Mood::Working {- ((t * 2.0 * PI / 3.2).sin() * 1.4).round() as i32- } else {- 0- };- let blinking = animated && (t / 4.7).fract() < 0.035;- let eye_rows = if blinking {- &all_eye_rows[all_eye_rows.len() - 1..]- } else {- all_eye_rows- };- silhouette(cr, shape);- let hex = shape == "hex";- if hex {- cr.set_line_width(8.0);- cr.set_line_join(gtk::cairo::LineJoin::Round);- }- let mut dots = Vec::new();- for row in 0..cells {- for col in 0..cells {- let (x, y) = ((f64::from(col) + 0.5) * step, (f64::from(row) + 0.5) * step);- let inside =- cr.in_fill(x, y).unwrap_or(false) || (hex && cr.in_stroke(x, y).unwrap_or(false));- let eye = eye_cols.iter().any(|c| c + glance == col) && eye_rows.contains(&row);- if inside && !eye {- dots.push((x, y));- }- }- }- cr.new_path();- let yaw = if mood == Mood::Working { t * 1.4 } else { -0.7 };- let (lx, ly, lz) = (yaw.sin() * 0.8, 0.55, yaw.cos() * 0.5 + 0.6); // never fully behind- let ll = (lx * lx + ly * ly + lz * lz).sqrt();- for (x, y) in dots {- let (u, v) = ((x - 50.0) / 50.0, (50.0 - y) / 50.0);- let z = (1.0 - u * u - v * v).max(0.2).sqrt();- let nl = (u * u + v * v + z * z).sqrt();- let mut shade = 0.3 + 0.7 * ((u * lx + v * ly + z * lz) / (nl * ll)).max(0.0);- if mood == Mood::Needs {- shade *= 0.6 + 0.4 * (0.5 + 0.5 * ((u * u + v * v).sqrt() * 9.0 - t * 5.0).sin());- }- cr.arc(x, y, step * 0.42 * (0.55 + 0.45 * shade), 0.0, 2.0 * PI);- let alpha = if cells < 13 {- 0.4 + 0.4 * shade- } else {- 0.2 + 0.4 * (shade / 0.7).min(1.0)- };- cr.set_source_rgba(ink.0, ink.1, ink.2, alpha);- cr.fill_preserve().ok();- if shade > 0.6 {- cr.set_source_rgba(r, g, b, (shade - 0.6) / 0.4);- cr.fill_preserve().ok();- }- cr.new_path();- }- cr.restore().ok();-}--type Part = (String, String, Mood);--fn part(b: &Value, animated: bool) -> Part {- (- b["avatarShape"].as_str().unwrap_or("blob").to_owned(),- b["avatarColor"].as_str().unwrap_or("blue").to_owned(),- if animated { mood(b) } else { Mood::Idle },- )-}--#[derive(Clone, Copy, PartialEq)]-enum Badge {- None,- Unread,- Needs,-}--/// One character in a fixed look.-pub fn shape(shape: &str, color: &str, size: i32, mood: Mood) -> gtk::DrawingArea {- area(- vec![(shape.to_owned(), color.to_owned(), mood)],- size,- Badge::None,- )-}--/// A bot's character, or for a group its first two members, one tucked behind the other.-pub fn of(bots: &HashMap<String, Value>, b: &Value, size: i32, animated: bool) -> gtk::DrawingArea {- build(bots, b, size, animated, Badge::None)-}--/// The roster avatar: a dot when unread, an amber "!" when it needs you.-pub fn with_status(bots: &HashMap<String, Value>, b: &Value, size: i32) -> gtk::DrawingArea {- let badge = if b["status"] == "needsInput" {- Badge::Needs- } else if b["unread"].as_i64().unwrap_or(0) > 0 {- Badge::Unread- } else {- Badge::None- };- build(bots, b, size, true, badge)-}--fn build(- bots: &HashMap<String, Value>,- b: &Value,- size: i32,- animated: bool,- badge: Badge,-) -> gtk::DrawingArea {- if b["kind"] == "group" {- let parts = b["members"]- .as_array()- .into_iter()- .flatten()- .filter_map(|m| bots.get(m.as_str()?))- .take(2)- .map(|m| part(m, animated))- .collect();- area(parts, size, badge)- } else {- area(vec![part(b, animated)], size, badge)- }-}--/// Several characters drawn side by side, overlapping by `overlap` px (the empty state's trio).-pub fn row(looks: &[(&str, &str, Mood)], size: i32, overlap: i32) -> gtk::DrawingArea {- let n = i32::try_from(looks.len()).unwrap_or(1);- let looks: Vec<Part> = looks- .iter()- .map(|(s, c, m)| ((*s).to_owned(), (*c).to_owned(), *m))- .collect();- let moving = looks.iter().any(|p| p.2 != Mood::Idle);- let area = gtk::DrawingArea::builder()- .content_width(size * n - overlap * (n - 1))- .content_height(size)- .halign(gtk::Align::Center)- .build();- let start = std::time::Instant::now();- area.set_draw_func(move |area, cr, _, _| {- let fg = area.color();- let ink = (- f64::from(fg.red()),- f64::from(fg.green()),- f64::from(fg.blue()),- );- let t = start.elapsed().as_secs_f64();- for (i, (s, c, m)) in looks.iter().enumerate() {- cr.save().ok();- cr.translate(f64::from(size - overlap) * i as f64, 0.0);- draw(cr, f64::from(size), s, c, ink, *m, t);- cr.restore().ok();- }- });- if moving {- area.add_tick_callback(|a, _| {- a.queue_draw();- gtk::glib::ControlFlow::Continue- });- }- area-}--fn area(parts: Vec<Part>, size: i32, badge: Badge) -> gtk::DrawingArea {- let area = gtk::DrawingArea::builder()- .content_width(size)- .content_height(size)- .valign(gtk::Align::Center)- .halign(gtk::Align::Center)- .build();- let moving = parts.iter().any(|p| p.2 != Mood::Idle);- let start = std::time::Instant::now();- area.set_draw_func(move |area, cr, w, _| {- let s = f64::from(w);- let fg = area.color();- let ink = (- f64::from(fg.red()),- f64::from(fg.green()),- f64::from(fg.blue()),- );- let t = start.elapsed().as_secs_f64();- match parts.as_slice() {- [] => draw(cr, s, "blob", "gray", ink, Mood::Idle, t),- [(shape, color, m)] => draw(cr, s, shape, color, ink, *m, t),- [first, second, ..] => {- let small = s * 0.66;- // Second member top-right, behind; first bottom-left.- for (p, (x, y)) in [(second, (s - small, 0.0)), (first, (0.0, s - small))] {- cr.save().ok();- cr.translate(x, y);- draw(cr, small, &p.0, &p.1, ink, p.2, t);- cr.restore().ok();- }- }- }- if badge != Badge::None {- let d = s * if badge == Badge::Needs { 0.36 } else { 0.28 };- let (cx, cy) = (s - d / 2.0, s - d / 2.0);- let dark = adw::StyleManager::default().is_dark();- let bg = if dark { 0.04 } else { 1.0 };- cr.arc(cx, cy, d / 2.0 + 2.0, 0.0, 2.0 * PI);- cr.set_source_rgb(bg, bg, bg);- cr.fill().ok();- cr.arc(cx, cy, d / 2.0, 0.0, 2.0 * PI);- if badge == Badge::Needs {- let (r, g, b) = rgb(0xF0A030);- cr.set_source_rgb(r, g, b);- cr.fill().ok();- cr.set_source_rgb(1.0, 1.0, 1.0);- cr.set_line_width(d * 0.16);- cr.set_line_cap(gtk::cairo::LineCap::Round);- cr.move_to(cx, cy - d * 0.22);- cr.line_to(cx, cy + d * 0.06);- cr.stroke().ok();- cr.arc(cx, cy + d * 0.24, d * 0.08, 0.0, 2.0 * PI);- cr.fill().ok();- } else {- cr.set_source_rgb(ink.0, ink.1, ink.2);- cr.fill().ok();- }- }- });- if moving {- area.add_tick_callback(|a, _| {- a.queue_draw();- gtk::glib::ControlFlow::Continue- });- }- area-}diff --git a/apps/linux/src/client.rs b/apps/linux/src/client.rsdeleted file mode 100644index 3123f6d9..00000000--- a/apps/linux/src/client.rs+++ /dev/null@@ -1,381 +0,0 @@-//! Talks to the local codync-host: JSON commands and the SSE event stream,-//! run on a tokio runtime and handed to the GTK main loop through channels.--use futures::StreamExt;-use serde_json::{Value, json};-use std::path::PathBuf;-use std::sync::OnceLock;-use std::sync::atomic::{AtomicI64, Ordering};-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()- })-}--pub fn data_dir() -> PathBuf {- std::env::var_os("CODYNC_HOME")- .map(PathBuf::from)- .unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join(".codync"))-}--pub fn port() -> u16 {- 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).-pub fn base() -> String {- std::env::var("CODYNC_URL").unwrap_or_else(|_| format!("http://127.0.0.1:{}", port()))-}--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())-}--fn http() -> &'static reqwest::Client {- static C: OnceLock<reqwest::Client> = OnceLock::new();- C.get_or_init(reqwest::Client::new)-}--/// How long a command keeps trying while the host can't be reached (it is restarting, say).-const PATIENCE: Duration = Duration::from_secs(20);--async fn call_async(method: String, body: Value) -> Result<Value, String> {- let token = token().ok_or("The Codync host isn't set up on this computer.")?;- let started = std::time::Instant::now();- let res = loop {- let sent = http()- .post(format!("{}/api/{method}", base()))- .bearer_auth(&token)- .json(&body)- .timeout(Duration::from_secs(- if matches!(- method.as_str(),- "agentAuth"- | "agentAuthenticate"- | "setAgentEnv"- | "installSkill"- | "installConnector"- ) {- 660- } else {- 120- },- ))- .send()- .await;- match sent {- Ok(res) => break res,- // Nothing was sent, so any command is safe to repeat while the host comes back.- // `hello` is the probe that says why it can't be reached, so it answers at once.- Err(e) if e.is_connect() && method != "hello" && started.elapsed() < PATIENCE => {- tokio::time::sleep(Duration::from_millis(500)).await;- }- Err(_) => return 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())- }-}--/// Runs a host command off the main thread and hands the result back on it.-pub fn call(method: &str, body: Value, done: impl FnOnce(Result<Value, String>) + 'static) {- let (tx, rx) = async_channel::bounded(1);- let method = method.to_owned();- runtime().spawn(async move {- let _ = tx.send(call_async(method, body).await).await;- });- gtk::glib::spawn_future_local(async move {- if let Ok(r) = rx.recv().await {- done(r);- }- });-}--/// Uploads `files` in 384 KiB chunks (under the channel's message limit, like the apps), then-/// sends `body` with them attached; the result comes back on the main thread.-pub fn send_files(- mut body: Value,- files: Vec<PathBuf>,- done: impl FnOnce(Result<Value, String>) + 'static,-) {- const CHUNK: usize = 384 * 1024;- const MAX: usize = 100 * 1024 * 1024;- let (tx, rx) = async_channel::bounded(1);- runtime().spawn(async move {- let r = async {- let mut ids = Vec::new();- for path in &files {- let name = path- .file_name()- .map(|n| n.to_string_lossy().into_owned())- .unwrap_or_default();- let data = tokio::fs::read(path)- .await- .map_err(|e| format!("Can't read {name}: {e}"))?;- if data.len() > MAX {- return Err(format!("{name} is over 100 MB."));- }- let id = uuid::Uuid::new_v4().to_string();- let mut offset = 0;- loop {- let end = (offset + CHUNK).min(data.len());- let chunk = gtk::glib::base64_encode(&data[offset..end]).to_string();- let done = end == data.len();- let chunk_body = json!({"botId": body["botId"], "uploadId": id, "name": name,- "offset": offset, "data": chunk, "done": done});- call_async("upload".into(), chunk_body).await?;- if done {- break;- }- offset = end;- }- ids.push(id);- }- body["attachments"] = ids.into();- call_async("send".into(), body).await- };- let _ = tx.send(r.await).await;- });- gtk::glib::spawn_future_local(async move {- if let Ok(r) = rx.recv().await {- done(r);- }- });-}--pub enum Event {- Online(bool),- Message(Value),-}--static REV: AtomicI64 = AtomicI64::new(0);--pub fn reset_rev() {- REV.store(0, Ordering::Relaxed);-}--/// Streams host events forever, reconnecting with `since = last rev`.-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)- );- if let Ok(res) = http().get(url).bearer_auth(token).send().await- && res.status().is_success()- {- let _ = tx.send(Event::Online(true)).await;- let mut body = res.bytes_stream();- let mut buf = String::new();- while let Some(Ok(chunk)) = body.next().await {- buf.push_str(&String::from_utf8_lossy(&chunk));- while let Some(i) = buf.find('\n') {- let line: String = buf.drain(..=i).collect();- if let Some(data) = line.trim_end().strip_prefix("data:")- && let Ok(v) = serde_json::from_str::<Value>(data.trim_start())- {- if let Some(rev) = v["rev"].as_i64() {- REV.fetch_max(rev, Ordering::Relaxed);- }- if tx.send(Event::Message(v)).await.is_err() {- return;- }- }- }- }- }- }- if tx.send(Event::Online(false)).await.is_err() {- return;- }- tokio::time::sleep(Duration::from_secs(2)).await;- }- });-}--/// `codync-host install`, for when the host isn't running yet.-pub fn install_host(done: impl FnOnce(Result<(), String>) + 'static) {- let (tx, rx) = async_channel::bounded(1);- runtime().spawn(async move {- let bin = ["codync-host", "/usr/local/bin/codync-host", "/home/linuxbrew/.linuxbrew/bin/codync-host"]- .iter()- .map(PathBuf::from)- .chain(dirs::home_dir().map(|h| h.join(".cargo/bin/codync-host")))- .chain(dirs::home_dir().map(|h| h.join(".local/bin/codync-host")))- .find(|p| p.components().count() == 1 || p.exists());- let r = match bin {- Some(bin) => match tokio::process::Command::new(bin).arg("install").output().await {- Ok(o) if o.status.success() => Ok(()),- Ok(o) => Err(String::from_utf8_lossy(&o.stderr).trim().to_owned()),- Err(_) => Err("codync-host isn't installed. Install it with Homebrew or from a release, then try again.".into()),- },- None => Err("codync-host isn't installed.".into()),- };- let _ = tx.send(r).await;- });- gtk::glib::spawn_future_local(async move {- if let Ok(r) = rx.recv().await {- done(r);- }- });-}--pub fn empty() -> Value {- json!({})-}--/// Save an attachment without overwriting an existing download or trusting a remote path.-pub fn save_file(- bot: String,- id: String,- name: String,- done: impl FnOnce(Result<PathBuf, String>) + 'static,-) {- let (tx, rx) = async_channel::bounded(1);- runtime().spawn(async move {- let result = async {- use tokio::io::AsyncWriteExt as _;- let dir = dirs::download_dir()- .or_else(dirs::home_dir)- .ok_or("No Downloads folder")?;- tokio::fs::create_dir_all(&dir)- .await- .map_err(|e| e.to_string())?;- let name = std::path::Path::new(&name)- .file_name()- .and_then(|n| n.to_str())- .filter(|n| !n.is_empty() && *n != "." && *n != "..")- .unwrap_or("attachment");- let mut suffix = 0;- let (path, mut file) = loop {- let path = dir.join(if suffix == 0 {- name.to_owned()- } else {- format!("{suffix}-{name}")- });- match tokio::fs::OpenOptions::new()- .write(true)- .create_new(true)- .open(&path)- .await- {- Ok(file) => break (path, file),- Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => suffix += 1,- Err(e) => return Err(e.to_string()),- }- };- let download = async {- let mut offset = 0_u64;- loop {- let v = call_async(- "readUpload".into(),- json!({"botId":bot,"uploadId":id,"offset":offset}),- )- .await?;- let chunk =- gtk::glib::base64_decode(v["data"].as_str().ok_or("Missing file data")?);- let size = v["size"].as_u64().ok_or("Missing file size")?;- if size > 100 * 1024 * 1024 || offset + chunk.len() as u64 > size {- return Err("Invalid attachment size".to_owned());- }- if chunk.is_empty() && offset < size {- return Err("Incomplete attachment".to_owned());- }- file.write_all(&chunk).await.map_err(|e| e.to_string())?;- offset += chunk.len() as u64;- if offset == size {- return Ok(());- }- }- }- .await;- drop(file);- if let Err(e) = download {- let _ = tokio::fs::remove_file(&path).await;- return Err(e);- }- Ok(path)- }- .await;- let _ = tx.send(result).await;- });- gtk::glib::spawn_future_local(async move {- if let Ok(r) = rx.recv().await {- done(r);- }- });-}--/// One ordered input queue and cancellable output stream for a host setup terminal.-pub fn terminal(- id: String,- events: async_channel::Sender<Result<Value, String>>,-) -> (async_channel::Sender<Vec<u8>>, tokio::task::AbortHandle) {- let (keys, input) = async_channel::unbounded::<Vec<u8>>();- let term = id.clone();- let errors = events.clone();- runtime().spawn(async move {- while let Ok(bytes) = input.recv().await {- let data = gtk::glib::base64_encode(&bytes).to_string();- if let Err(e) = call_async("termInput".into(), json!({"term":term,"data":data})).await {- let _ = errors.send(Err(e)).await;- }- }- });- let output = runtime().spawn(async move {- let read = async {- let token = token().ok_or("Host token is missing")?;- let response = http()- .get(format!("{}/term/{id}", base()))- .bearer_auth(token)- .send()- .await- .and_then(reqwest::Response::error_for_status)- .map_err(|e| e.to_string())?;- let mut stream = response.bytes_stream();- let mut buffer = Vec::new();- while let Some(chunk) = stream.next().await {- buffer.extend_from_slice(&chunk.map_err(|e| e.to_string())?);- while let Some(end) = buffer.iter().position(|b| *b == b'\n') {- let line: Vec<_> = buffer.drain(..=end).collect();- let line = String::from_utf8_lossy(&line);- if let Some(data) = line.trim_end().strip_prefix("data:") {- let event: Value =- serde_json::from_str(data.trim()).map_err(|e| e.to_string())?;- let exited = event["type"] == "exit";- if events.send(Ok(event)).await.is_err() || exited {- return Ok(());- }- }- }- }- Err("Terminal disconnected. Close it and retry setup.".to_owned())- }- .await;- if let Err(e) = read {- let _ = events.send(Err(e)).await;- }- });- (keys, output.abort_handle())-}diff --git a/apps/linux/src/compat.rs b/apps/linux/src/compat.rsdeleted file mode 100644index d0795b9e..00000000--- a/apps/linux/src/compat.rs+++ /dev/null@@ -1,109 +0,0 @@-//! Phone/host compatibility (docs/reference/compatibility.md), mirroring `host/src/compat.rs`:-//! the host sends the oldest app it serves as `minApp` in `hello`; this app keeps its own floor.--use serde_json::Value;--/// The oldest host this app works with. Raise it only when the app starts depending on-/// something older hosts don't have.-pub const MIN_HOST: &str = "2.3.0";--#[derive(Debug, Clone, PartialEq, Eq)]-pub enum Mismatch {- /// This app is older than the host's `minApp`.- UpdateApp { minimum: String },- /// The host is older than `MIN_HOST`.- UpdateHost { version: String, minimum: String },-}--/// `major.minor.patch`, ignoring a leading `v` and any pre-release or build suffix; missing-/// parts count as 0. `None` for anything else, which never blocks.-fn parse(version: &str) -> Option<(u64, u64, u64)> {- let core = version.trim().trim_start_matches('v');- let core = core.split(['-', '+']).next()?;- let mut parts = core.split('.');- let mut next = |required: bool| match parts.next() {- Some(p) => p.parse::<u64>().ok(),- None if required => None,- None => Some(0),- };- let v = (next(true)?, next(false)?, next(false)?);- parts.next().is_none().then_some(v)-}--pub fn below(version: &str, minimum: &str) -> bool {- matches!((parse(version), parse(minimum)), (Some(v), Some(m)) if v < m)-}--/// This app (`app`) against a host's `hello`; hosts that predate `minApp` only get the floor check.-pub fn check(app: &str, hello: &Value) -> Option<Mismatch> {- if let Some(minimum) = hello["minApp"].as_str()- && below(app, minimum)- {- return Some(Mismatch::UpdateApp {- minimum: minimum.to_owned(),- });- }- let version = hello["version"].as_str().unwrap_or_default();- below(version, MIN_HOST).then(|| Mismatch::UpdateHost {- version: version.to_owned(),- minimum: MIN_HOST.to_owned(),- })-}--/// What to update, in the words every client uses.-pub fn text(m: &Mismatch, host: &str) -> String {- match m {- Mismatch::UpdateApp { minimum } => {- format!("Update this app: {host} needs Codync {minimum} or newer here.")- }- Mismatch::UpdateHost { version, minimum } => format!(- "Update Codync on {host}: it runs {version}, this app needs {minimum} or newer."- ),- }-}--#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;-- #[test]- fn floor_never_exceeds_this_release() {- assert!(!below(env!("CARGO_PKG_VERSION"), MIN_HOST));- assert!(parse(MIN_HOST).is_some());- }-- #[test]- fn decides_which_side_updates() {- assert_eq!(- parse("2.10.0").cmp(&parse("2.9.9")),- std::cmp::Ordering::Greater- );- assert_eq!(parse("v2.4"), Some((2, 4, 0)));- assert_eq!(parse("2.4.0-dev"), Some((2, 4, 0)));- assert_eq!(parse("2.4.0.1"), None);- assert_eq!(- check("2.4.0", &json!({"version": "2.4.0", "minApp": "2.3.0"})),- None- );- assert_eq!(- check("2.4.0", &json!({"version": "2.6.0", "minApp": "2.5.0"})),- Some(Mismatch::UpdateApp {- minimum: "2.5.0".into()- })- );- assert_eq!(- check("2.4.0", &json!({"version": "2.2.3"})),- Some(Mismatch::UpdateHost {- version: "2.2.3".into(),- minimum: MIN_HOST.into()- })- );- // Unknown versions never lock anyone out.- assert_eq!(check("2.4.0", &json!({})), None);- assert_eq!(- check("dev", &json!({"version": "2.6.0", "minApp": "2.5.0"})),- None- );- }-}diff --git a/apps/linux/src/compose.rs b/apps/linux/src/compose.rsdeleted file mode 100644index 1f12905f..00000000--- a/apps/linux/src/compose.rs+++ /dev/null@@ -1,489 +0,0 @@-//! The "new message" page (kit NewChatView): a To: field that searches your bots or creates a-//! new one, with Ctrl+1…9 shortcuts, and the message box underneath. Picked bots become chips;-//! one opens its chat, several start a group chat with them (or open the one they share).--use crate::avatar;-use crate::client;-use crate::rows::{hline, icon_button, label};-use crate::ui::{self, App, flat_header};-use adw::prelude::*;-use serde_json::{Value, json};-use std::cell::{Cell, RefCell};--pub struct Page {- pub root: gtk::Box,- chips: gtk::Box,- to: gtk::Entry,- list: gtk::Box,- draft: gtk::Entry,- close_btn: gtk::Button,- recipients: RefCell<Vec<String>>,- creating: Cell<bool>,- /// The chat that was open before, restored when the page closes empty-handed.- previous: RefCell<Option<String>>,-}--pub fn build() -> Page {- let chips = gtk::Box::builder().spacing(6).build();- let to = gtk::Entry::builder()- .css_classes(["plain", "title3"])- .hexpand(true)- .width_chars(20)- .build();- chips.append(&to);- let to_row = gtk::Box::builder()- .spacing(8)- .hexpand(true)- .margin_start(16)- .margin_end(8)- .build();- to_row.append(&label("To:", &["title3", "secondary"]));- to_row.append(- >k::ScrolledWindow::builder()- .child(&chips)- .vscrollbar_policy(gtk::PolicyType::Never)- .hscrollbar_policy(gtk::PolicyType::External)- .hexpand(true)- .build(),- );- let close = icon_button("window-close-symbolic", "Close (Esc)");- to_row.append(&close);- let list = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(2)- .build();- let card = gtk::Box::builder()- .css_classes(["pick-card"])- .halign(gtk::Align::Start)- .valign(gtk::Align::Start)- .margin_start(22)- .margin_end(22)- .margin_top(10)- .build();- card.append(- >k::ScrolledWindow::builder()- .child(&list)- .hscrollbar_policy(gtk::PolicyType::Never)- .propagate_natural_height(true)- .propagate_natural_width(true)- .max_content_height(460)- .hexpand(true)- .build(),- );- let draft = gtk::Entry::builder()- .css_classes(["plain"])- .hexpand(true)- .margin_top(11)- .margin_bottom(11)- .build();- let pill = gtk::Box::builder()- .css_classes(["composer"])- .margin_start(16)- .margin_end(16)- .margin_bottom(16)- .margin_top(16)- .build();- pill.append(&draft);- let root = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .css_classes(["chat-bg"])- .build();- let header = flat_header(&to_row);- root.append(&header);- root.append(&hline());- root.append(&card);- root.append(>k::Box::builder().vexpand(true).build());- root.append(&pill);- Page {- root,- chips,- to,- list,- draft,- close_btn: close,- recipients: RefCell::new(vec![]),- creating: Cell::new(false),- previous: RefCell::new(None),- }-}--pub fn open(ui: &App) {- {- let mut st = ui.state.borrow_mut();- if !st.composing {- *ui.compose_page.previous.borrow_mut() = st.current.take();- }- st.composing = true;- st.open_thread = None;- }- let p = &ui.compose_page;- p.recipients.borrow_mut().clear();- p.to.set_text("");- p.draft.set_text("");- ui.roster.unselect_all();- ui.split.set_show_content(true);- ui::render(ui);- p.to.grab_focus();-}--fn close(ui: &App) {- {- let mut st = ui.state.borrow_mut();- st.composing = false;- if st.current.is_none() {- st.current = ui.compose_page.previous.borrow_mut().take();- }- }- ui::schedule(ui);-}--/// Bots not picked yet; a group can only be opened on its own, so groups go once someone's picked.-fn matches(ui: &App) -> Vec<Value> {- let st = ui.state.borrow();- let q = ui.compose_page.to.text().trim().to_lowercase();- let picked = ui.compose_page.recipients.borrow();- ui::roster(&st)- .into_iter()- .filter(|b| {- let id = b["id"].as_str().unwrap_or_default();- !picked.iter().any(|p| p == id)- && (!ui::is_group(b) || picked.is_empty())- && (q.is_empty()- || b["name"]- .as_str()- .is_some_and(|n| n.to_lowercase().contains(&q)))- })- .cloned()- .collect()-}--fn keycaps(n: usize) -> gtk::Box {- let b = gtk::Box::builder().spacing(3).build();- for k in ["Ctrl", &n.to_string()] {- let l = gtk::Label::builder()- .label(k)- .css_classes(["keycap"])- .build();- b.append(&l);- }- b-}--fn pick_row(icon: &impl IsA<gtk::Widget>, text: &str, shortcut: Option<usize>) -> gtk::Button {- let row = gtk::Box::builder().spacing(12).build();- row.append(icon);- let l = gtk::Label::builder()- .label(text)- .xalign(0.0)- .hexpand(true)- .ellipsize(gtk::pango::EllipsizeMode::End)- // Wide enough to fill the Mac's 620 pt card when there's room.- .width_chars(62)- .max_width_chars(62)- .build();- row.append(&l);- if let Some(n) = shortcut {- row.append(&keycaps(n));- }- gtk::Button::builder()- .child(&row)- .css_classes(["pick-row"])- .build()-}--pub fn render(ui: &App) {- let p = &ui.compose_page;- // Chips before the field.- while let Some(c) = p.chips.first_child() {- if c == p.to.clone().upcast::<gtk::Widget>() {- break;- }- p.chips.remove(&c);- }- let st = ui.state.borrow();- let picked: Vec<Value> = p- .recipients- .borrow()- .iter()- .filter_map(|id| st.bots.get(id).cloned())- .collect();- for b in &picked {- let id = b["id"].as_str().unwrap_or_default().to_owned();- let ui2 = ui.clone();- let chip = bot_chip(&st.bots, b, move || remove(&ui2, &id));- p.chips- .insert_child_after(&chip, p.to.prev_sibling().as_ref());- }- p.to.set_placeholder_text(Some(if picked.is_empty() {- "Search or create bots"- } else {- "Add another bot"- }));- p.draft.set_placeholder_text(Some(&match picked.len() {- 0 => "Message Bot".to_owned(),- _ => format!(- "Message {}",- picked- .iter()- .filter_map(|b| b["name"].as_str())- .collect::<Vec<_>>()- .join(", ")- ),- }));- drop(st);-- ui::clear(&p.list);- let q = p.to.text().trim().to_owned();- let plus_box = gtk::Image::builder()- .icon_name(if p.creating.get() {- "content-loading-symbolic"- } else {- "list-add-symbolic"- })- .pixel_size(13)- .width_request(26)- .height_request(26)- .css_classes(["plus-circle"])- .build();- let create_row = pick_row(- &plus_box,- &if q.is_empty() {- "Create new Bot".to_owned()- } else {- format!("Create “{q}”")- },- Some(1),- );- {- let ui2 = ui.clone();- create_row.connect_clicked(move |_| create(&ui2));- }- p.list.append(&create_row);- let st = ui.state.borrow();- for (i, b) in matches(ui).iter().enumerate() {- let n = i + 2;- let row = pick_row(- &avatar::of(&st.bots, b, 26, false),- b["name"].as_str().unwrap_or(""),- (n <= 9).then_some(n),- );- let (ui2, b2) = (ui.clone(), b.clone());- row.connect_clicked(move |_| choose(&ui2, &b2));- p.list.append(&row);- }-}--/// A picked bot (To: field, group editor); its x takes it back out.-pub fn bot_chip(- bots: &std::collections::HashMap<String, Value>,- b: &Value,- remove: impl Fn() + 'static,-) -> gtk::Box {- let chip = gtk::Box::builder()- .spacing(6)- .css_classes(["chip"])- .valign(gtk::Align::Center)- .build();- chip.append(&avatar::of(bots, b, 20, false));- let name = b["name"].as_str().unwrap_or("");- let l = label(name, &["body13"]);- l.set_max_width_chars(24);- l.set_ellipsize(gtk::pango::EllipsizeMode::End);- chip.append(&l);- let x = gtk::Button::builder()- .icon_name("window-close-symbolic")- .css_classes(["chip-x"])- .tooltip_text(format!("Remove {name}"))- .build();- x.connect_clicked(move |_| remove());- chip.append(&x);- chip-}--/// A bot becomes a chip; a group (with nobody picked) opens right away.-fn choose(ui: &App, b: &Value) {- let id = b["id"].as_str().unwrap_or_default().to_owned();- if ui::is_group(b) {- open_chat(ui, &id);- return;- }- ui.compose_page.recipients.borrow_mut().push(id);- ui.compose_page.to.set_text("");- render(ui);- ui.compose_page.to.grab_focus();-}--fn remove(ui: &App, id: &str) {- ui.compose_page.recipients.borrow_mut().retain(|x| x != id);- render(ui);-}--/// Return in To: picks the top match, or with the field empty, starts the chat.-fn submit_to(ui: &App) {- if ui::blocked_by_update(ui) {- return;- }- if ui.compose_page.to.text().trim().is_empty() {- start(ui);- } else if let Some(first) = matches(ui).first() {- choose(ui, first);- } else {- create(ui);- }-}--/// One bot: its chat. Several: their group chat.-fn start(ui: &App) {- if ui::blocked_by_update(ui) {- return;- }- let ids = ui.compose_page.recipients.borrow().clone();- match ids.len() {- 0 => {}- 1 => open_chat(ui, &ids[0]),- _ => {- let names = {- let st = ui.state.borrow();- ids.iter()- .filter_map(|id| st.bots.get(id)?["name"].as_str().map(str::to_owned))- .collect::<Vec<_>>()- .join(", ")- };- let ui2 = ui.clone();- client::call(- "createBot",- json!({"id": "", "kind": "group", "name": names, "members": ids}),- move |r| match r {- Ok(v) => {- let bot = v["bot"].clone();- let id = bot["id"].as_str().unwrap_or_default().to_owned();- ui2.state.borrow_mut().bots.insert(id.clone(), bot);- open_chat(&ui2, &id);- }- Err(e) => ui::toast(&ui2, &e),- },- );- }- }-}--/// Opens the chat and sends whatever was typed.-fn open_chat(ui: &App, id: &str) {- let text = ui.compose_page.draft.text().trim().to_owned();- ui.compose_page.draft.set_text("");- ui.compose_page.previous.borrow_mut().take();- ui::select(ui, id);- if !text.is_empty() {- ui::send_text(ui, id, &text, None, vec![]);- }-}--/// A bot with the typed name, or none (the host names it after its first conversations), with-/// sensible defaults: the first available agent and a personal workspace.-fn create(ui: &App) {- if ui.compose_page.creating.replace(true) {- return;- }- render(ui);- let name = ui.compose_page.to.text().trim().to_owned();- let body = {- let st = ui.state.borrow();- let backends = st.hello["backends"].as_array().cloned().unwrap_or_default();- let n = uuid::Uuid::new_v4().as_u128() as usize;- json!({- "name": name, "description": "", "permission": "auto", "model": null, "command": null,- "cwd": "",- "avatarShape": avatar::SHAPES[n % avatar::SHAPES.len()],- "avatarColor": avatar::COLORS[(n / 8) % avatar::COLORS.len()].0,- "backend": backends.iter().find(|b| b["available"] == true).and_then(|b| b["id"].as_str()).unwrap_or("claude"),- })- };- let ui2 = ui.clone();- client::call("createBot", body, move |r| {- ui2.compose_page.creating.set(false);- match r {- Ok(v) => {- let bot = v["bot"].clone();- let id = bot["id"].as_str().unwrap_or_default().to_owned();- ui2.state.borrow_mut().bots.insert(id.clone(), bot.clone());- if ui2.compose_page.recipients.borrow().is_empty() {- open_chat(&ui2, &id);- } else {- choose(&ui2, &bot);- }- }- Err(e) => {- ui::toast(&ui2, &e);- render(&ui2);- }- }- });-}--pub fn wire(ui: &App) {- let p = &ui.compose_page;- {- let ui2 = ui.clone();- p.to.connect_changed(move |_| render(&ui2));- }- {- let ui2 = ui.clone();- p.to.connect_activate(move |_| submit_to(&ui2));- }- {- let ui2 = ui.clone();- p.draft.connect_activate(move |_| start(&ui2));- }- // Backspace in an empty To: takes the last chip back out.- {- let ui2 = ui.clone();- let keys = gtk::EventControllerKey::builder()- .propagation_phase(gtk::PropagationPhase::Capture)- .build();- keys.connect_key_pressed(move |_, key, _, _| {- let p = &ui2.compose_page;- if key == gtk::gdk::Key::BackSpace && p.to.text().is_empty() {- let last = p.recipients.borrow().last().cloned();- if let Some(id) = last {- remove(&ui2, &id);- return gtk::glib::Propagation::Stop;- }- }- gtk::glib::Propagation::Proceed- });- p.to.add_controller(keys);- }- // Ctrl+1 creates, Ctrl+2…9 pick; Esc closes.- {- let ui2 = ui.clone();- let keys = gtk::EventControllerKey::builder()- .propagation_phase(gtk::PropagationPhase::Capture)- .build();- keys.connect_key_pressed(move |_, key, _, mods| {- if key == gtk::gdk::Key::Escape {- close(&ui2);- return gtk::glib::Propagation::Stop;- }- if mods.contains(gtk::gdk::ModifierType::CONTROL_MASK)- && let Some(d) = key.to_unicode().and_then(|c| c.to_digit(10))- {- match d {- 1 => create(&ui2),- 2..=9 => {- if let Some(b) = matches(&ui2).get(d as usize - 2) {- choose(&ui2, b);- }- }- _ => return gtk::glib::Propagation::Proceed,- }- return gtk::glib::Propagation::Stop;- }- gtk::glib::Propagation::Proceed- });- p.root.add_controller(keys);- }- {- let ui2 = ui.clone();- p.close_btn.connect_clicked(move |_| close(&ui2));- }-}diff --git a/apps/linux/src/connections.rs b/apps/linux/src/connections.rsdeleted file mode 100644index 95b9bcb2..00000000--- a/apps/linux/src/connections.rs+++ /dev/null@@ -1,692 +0,0 @@-//! Native connection cards use the same secure host workflow as iOS and macOS.-use crate::{- client,- rows::label,- ui::{App, toast},-};-use adw::prelude::*;-use serde_json::{Value, json};-use std::{cell::RefCell, rc::Rc};--pub fn card(ui: &App, entry: &Value) -> gtk::Widget {- let request = &entry["data"]["connectionRequest"];- let body = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(10)- .css_classes(["perm-card"])- .build();- body.append(&label(- request["title"].as_str().unwrap_or("Connect service"),- &["headline"],- ));- let reason = label(entry["data"]["text"].as_str().unwrap_or(""), &["secondary"]);- reason.set_wrap(true);- body.append(&reason);- if request["status"] != "pending" {- body.append(&label(- if request["status"] == "ready" {- "Connected"- } else {- "Cancelled"- },- &["secondary"],- ));- return body.upcast();- }- let input = gtk::PasswordEntry::builder()- .show_peek_icon(true)- .placeholder_text("Credential or op:// reference")- .build();- let username = gtk::Entry::builder()- .placeholder_text("Username or email")- .build();- let login = request["kind"] == "login";- let secret = login || request["kind"] == "secret";- if login {- input.set_placeholder_text(Some("Password or op:// reference"));- body.append(&username);- body.append(&input);- body.append(&label(- "Saved securely on this computer. The bot types it into the sign-in page but never sees it.",- &["small", "secondary"],- ));- } else if secret {- body.append(&label(- request["field"].as_str().unwrap_or("Credential"),- &["secondary"],- ));- body.append(&input);- body.append(&label(- "Saved securely; never included in the conversation.",- &["small", "secondary"],- ));- }- let actions = gtk::Box::builder().spacing(8).build();- let connect = gtk::Button::with_label(if login {- "Save login"- } else if secret {- "Save and connect"- } else {- "Connect"- });- let cancel = gtk::Button::with_label("Cancel");- actions.append(&connect);- actions.append(&cancel);- body.append(&actions);- let (ui2, e) = (ui.clone(), entry.clone());- connect.connect_clicked(move |button| {- let r = &e["data"]["connectionRequest"];- if secret {- let value = input.text().to_string();- if value.is_empty() {- return;- }- button.set_sensitive(false);- let (ui3, button, input) = (ui2.clone(), button.clone(), input.clone());- client::call(- "connectorRequestFinish",- json!({"entryId":e["id"],"value":value,"username":username.text().as_str()}),- move |result| {- button.set_sensitive(true);- match result {- Ok(_) => input.set_text(""),- Err(error) => toast(&ui3, &error),- }- },- );- } else if r["kind"] == "app" {- hosted_app(- &ui2,- e["id"].clone(),- r["toolkit"].as_str().unwrap_or("").to_owned(),- );- } else if let Some(id) = r["connectorId"].as_str() {- authorize(&ui2, e["id"].clone(), id.to_owned());- } else {- let (ui3, e) = (ui2.clone(), e.clone());- client::call(- "connectorInfo",- json!({"registryName":r["registryName"]}),- move |result| match result {- Ok(item) => install(&ui3, &item, e["id"].clone()),- Err(error) => toast(&ui3, &error),- },- );- }- });- let (ui2, id) = (ui.clone(), entry["id"].clone());- cancel.connect_clicked(move |button| {- button.set_sensitive(false);- let (ui3, button) = (ui2.clone(), button.clone());- client::call(- "connectorRequestFinish",- json!({"entryId":id,"cancel":true}),- move |r| {- button.set_sensitive(true);- if let Err(e) = r {- toast(&ui3, &e);- }- },- );- });- body.upcast()-}--fn dialog(ui: &App, title: &str) -> (adw::Dialog, gtk::Box) {- let body = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(12)- .margin_top(20)- .margin_bottom(20)- .margin_start(20)- .margin_end(20)- .build();- let view = adw::ToolbarView::new();- view.add_top_bar(&adw::HeaderBar::new());- let scroll = gtk::ScrolledWindow::builder().child(&body).build();- view.set_content(Some(&scroll));- let dialog = adw::Dialog::builder()- .title(title)- .content_width(480)- .content_height(440)- .child(&view)- .build();- dialog.present(Some(&ui.window));- (dialog, body)-}--fn install(ui: &App, item: &Value, entry: Value) {- if let Some(options) = item["options"].as_array()- && options.len() == 1- && options[0]["inputs"].as_array().is_some_and(Vec::is_empty)- {- let ui = ui.clone();- client::call(- "installConnector",- json!({"registryName":item["name"],"option":options[0]["id"],"inputs":{}}),- move |r| match r {- Ok(v) => added(&ui, entry, &v["connector"]),- Err(e) => toast(&ui, &e),- },- );- return;- }-- let (window, body) = dialog(ui, item["title"].as_str().unwrap_or("Connect"));- let options = item["options"].as_array().cloned().unwrap_or_default();- for option in options {- let section = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(8)- .build();- section.append(&label(- option["label"].as_str().unwrap_or("Setup"),- &["headline"],- ));- let mut inputs: Vec<(String, gtk::Entry)> = Vec::new();- for field in option["inputs"].as_array().into_iter().flatten() {- let input = gtk::Entry::builder()- .placeholder_text(field["name"].as_str().unwrap_or("Value"))- .visibility(field["secret"] != true)- .text(field["default"].as_str().unwrap_or(""))- .build();- section.append(&input);- inputs.push((field["name"].as_str().unwrap_or("").to_owned(), input));- }- let add = gtk::Button::with_label("Add");- section.append(&add);- body.append(§ion);- let (ui, item, entry, window) = (ui.clone(), item.clone(), entry.clone(), window.clone());- add.connect_clicked(move |button| {- button.set_sensitive(false);- let values: serde_json::Map<String, Value> = inputs- .iter()- .map(|(k, e)| (k.clone(), e.text().to_string().into()))- .collect();- let (ui, entry, window, button, inputs) = (- ui.clone(),- entry.clone(),- window.clone(),- button.clone(),- inputs.clone(),- );- client::call(- "installConnector",- json!({"registryName":item["name"],"option":option["id"],"inputs":values}),- move |r| {- button.set_sensitive(true);- match r {- Ok(v) => {- for (_, input) in inputs {- input.set_text("");- }- window.close();- added(&ui, entry, &v["connector"]);- }- Err(e) => toast(&ui, &e),- }- },- );- });- }-}--fn added(ui: &App, entry: Value, connector: &Value) {- let id = connector["id"].as_str().unwrap_or("").to_owned();- if connector["auth"] == "signedOut" {- authorize(ui, entry, id);- return;- }- let ui = ui.clone();- let method = if entry.is_null() {- "connectorVerify"- } else {- "connectorRequestFinish"- };- client::call(- method,- json!({"id":id,"connectorId":id,"entryId":entry}),- move |r| match r {- Ok(_) => toast(&ui, "Connected"),- Err(e) => toast(&ui, &e),- },- );-}--fn authorize(ui: &App, entry: Value, id: String) {- let (window, body) = dialog(ui, "Connect service");- body.append(&label(- "Sign in if needed, then check the connection.",- &["secondary"],- ));- let login = gtk::Button::with_label("Sign in");- body.append(&login);- let check = gtk::Button::with_label("Check connection");- body.append(&check);- let (ui2, id2) = (ui.clone(), id.clone());- login.connect_clicked(move |button| {- button.set_sensitive(false);- let (ui, button) = (ui2.clone(), button.clone());- client::call("connectorSignIn", json!({"id":id2}), move |r| {- button.set_sensitive(true);- match r {- Ok(v) => {- if let Some(url) = v["url"].as_str() {- let _ = gtk::gio::AppInfo::launch_default_for_uri(- url,- None::<>k::gio::AppLaunchContext>,- );- }- }- Err(e) => toast(&ui, &e),- }- });- });- let ui = ui.clone();- check.connect_clicked(move |button| {- button.set_sensitive(false);- let (ui, window, button) = (ui.clone(), window.clone(), button.clone());- let method = if entry.is_null() {- "connectorVerify"- } else {- "connectorRequestFinish"- };- client::call(- method,- json!({"entryId":entry,"connectorId":id,"id":id}),- move |r| {- button.set_sensitive(true);- match r {- Ok(_) => {- window.close();- }- Err(e) => toast(&ui, &e),- }- },- );- });-}--pub fn credentials(ui: &App) {- let (_window, body) = dialog(ui, "Credentials");- let status = label("Linux Secret Service · encrypted storage", &["headline"]);- body.append(&status);- let help = label(- "1Password: install the op CLI and use a service account restricted to a dedicated shared vault. Use op://vault/item/field in connector credential fields.",- &["secondary"],- );- help.set_wrap(true);- body.append(&help);- let composio = gtk::PasswordEntry::builder()- .placeholder_text("Composio API key (for hosted apps)")- .show_peek_icon(true)- .build();- body.append(&composio);- let setup = gtk::Button::with_label("Set up hosted apps");- body.append(&setup);- let ui2 = ui.clone();- setup.connect_clicked(move |button| {- button.set_sensitive(false);- let (ui, composio, button) = (ui2.clone(), composio.clone(), button.clone());- client::call(- "setComposioKey",- json!({"key":composio.text().as_str()}),- move |r| {- button.set_sensitive(true);- match r {- Ok(_) => {- composio.set_text("");- toast(&ui, "Hosted apps configured");- }- Err(e) => toast(&ui, &e),- }- },- );- });- let saved = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(8)- .build();- body.append(&saved);- let ui2 = ui.clone();- client::call("connectors", json!({}), move |r| {- if let Ok(v) = r {- for connector in v["items"].as_array().into_iter().flatten() {- if connector["keys"].as_array().is_none_or(Vec::is_empty) {- continue;- }- let button = gtk::Button::with_label(- connector["name"].as_str().unwrap_or("Saved connection"),- );- saved.append(&button);- let (ui, connector) = (ui2.clone(), connector.clone());- button.connect_clicked(move |_| edit_credentials(&ui, &connector));- }- }- });- body.append(&label("Sign-ins", &["headline"]));- let logins = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(8)- .build();- body.append(&logins);- let ui2 = ui.clone();- client::call("credentialLogins", json!({}), move |r| {- let Ok(v) = r else { return };- for login in v["items"].as_array().into_iter().flatten() {- let row = gtk::Box::builder().spacing(8).build();- let text = format!(- "{} · {}",- login["site"].as_str().unwrap_or(""),- login["username"].as_str().unwrap_or("")- );- let name = label(&text, &[]);- name.set_hexpand(true);- row.append(&name);- let remove = gtk::Button::from_icon_name("user-trash-symbolic");- remove.set_tooltip_text(Some("Remove"));- row.append(&remove);- logins.append(&row);- let (ui, row, logins, id) = (- ui2.clone(),- row.clone(),- logins.clone(),- login["id"].clone(),- );- remove.connect_clicked(move |_| {- let (ui, row, logins) = (ui.clone(), row.clone(), logins.clone());- client::call(- "credentialRemoveLogin",- json!({"id":id}),- move |r| match r {- Ok(_) => logins.remove(&row),- Err(e) => toast(&ui, &e),- },- );- });- }- });- let input = gtk::PasswordEntry::builder()- .placeholder_text("1Password service account token")- .show_peek_icon(true)- .build();- body.append(&input);- let connect = gtk::Button::with_label("Connect 1Password");- body.append(&connect);- let disconnect = gtk::Button::with_label("Disconnect 1Password");- body.append(&disconnect);- let busy = Rc::new(RefCell::new(false));- for (button, remove) in [(connect, false), (disconnect, true)] {- let (ui, input, status, busy) = (ui.clone(), input.clone(), status.clone(), busy.clone());- button.connect_clicked(move |_| {- if *busy.borrow() {- return;- }- *busy.borrow_mut() = true;- let token = if remove {- String::new()- } else {- input.text().to_string()- };- let (ui, input, status, busy) =- (ui.clone(), input.clone(), status.clone(), busy.clone());- client::call(- "credentialSetOnePassword",- json!({"token":token}),- move |r| {- *busy.borrow_mut() = false;- match r {- Ok(v) => {- input.set_text("");- status.set_label(if v["onePasswordConnected"] == true {- "1Password connected"- } else {- "1Password disconnected"- });- }- Err(e) => toast(&ui, &e),- }- },- );- });- }- client::call("credentialStatus", json!({}), move |r| match r {- Ok(v) => status.set_label(if v["onePasswordConnected"] == true {- "Secret Service · 1Password connected"- } else {- "Secret Service"- }),- Err(e) => status.set_label(&e),- });-}--/// Registry browsing is explicit and paged; Add uses the same secure setup form.-pub fn marketplace(ui: &App) {- let (_window, body) = dialog(ui, "Connectors");- let search = gtk::SearchEntry::new();- body.append(&search);- let results = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(12)- .build();- body.append(&results);- let load = gtk::Button::with_label("Search / load connectors");- body.append(&load);- let more = gtk::Button::with_label("Load more");- more.set_visible(false);- body.append(&more);- let cursor = Rc::new(RefCell::new(Value::Null));- let query = Rc::new(RefCell::new(String::new()));- let pending = Rc::new(RefCell::new(Vec::<Value>::new()));- let loading = Rc::new(RefCell::new(false));- for (button, next) in [(load, false), (more.clone(), true)] {- let (ui, search, results, more, cursor, query, pending, loading) = (- ui.clone(),- search.clone(),- results.clone(),- more.clone(),- cursor.clone(),- query.clone(),- pending.clone(),- loading.clone(),- );- button.connect_clicked(move |_| {- if *loading.borrow() {- return;- }- if !next {- *query.borrow_mut() = search.text().to_string();- *cursor.borrow_mut() = Value::Null;- pending.borrow_mut().clear();- while let Some(child) = results.first_child() {- results.remove(&child);- }- } else if !pending.borrow().is_empty() {- reveal(&ui, &results, &pending);- more.set_visible(!pending.borrow().is_empty() || cursor.borrow().is_string());- return;- }- *loading.borrow_mut() = true;- let (ui, results, more, cursor, pending, loading) = (- ui.clone(),- results.clone(),- more.clone(),- cursor.clone(),- pending.clone(),- loading.clone(),- );- client::call(- "marketConnectors",- json!({"search":*query.borrow(),"cursor":*cursor.borrow()}),- move |r| {- *loading.borrow_mut() = false;- match r {- Ok(v) => {- *cursor.borrow_mut() = v["nextCursor"].clone();- *pending.borrow_mut() =- v["items"].as_array().cloned().unwrap_or_default();- reveal(&ui, &results, &pending);- more.set_visible(- !pending.borrow().is_empty() || cursor.borrow().is_string(),- );- }- Err(e) => toast(&ui, &e),- }- },- );- });- }-}--fn reveal(ui: &App, results: >k::Box, pending: &Rc<RefCell<Vec<Value>>>) {- let count = pending.borrow().len().min(12);- let page: Vec<_> = pending.borrow_mut().drain(..count).collect();- for item in page {- let row = gtk::Box::builder().spacing(8).build();- let name = label(item["title"].as_str().unwrap_or("Connector"), &["headline"]);- name.set_hexpand(true);- row.append(&name);- let add = gtk::Button::with_label(if item["installed"] == true {- "Added"- } else {- "Add"- });- add.set_sensitive(item["installed"] != true);- row.append(&add);- results.append(&row);- let ui = ui.clone();- add.connect_clicked(move |_| install(&ui, &item, Value::Null));- }-}--fn hosted_app(ui: &App, entry: Value, toolkit: String) {- let (window, body) = dialog(ui, "Connect app");- let ui = ui.clone();- client::call("composioConnect", json!({"toolkit":toolkit}), move |r| {- let plan = match r {- Ok(v) => v,- Err(e) => {- toast(&ui, &e);- return;- }- };- if let Some(url) = plan["url"].as_str() {- let _ =- gtk::gio::AppInfo::launch_default_for_uri(url, None::<>k::gio::AppLaunchContext>);- }- let mut fields = Vec::new();- for field in plan["fields"].as_array().into_iter().flatten() {- let input = gtk::Entry::builder()- .placeholder_text(field["label"].as_str().unwrap_or("Value"))- .visibility(field["secret"] != true)- .build();- body.append(&input);- fields.push((field["name"].as_str().unwrap_or("").to_owned(), input));- }- let connect = gtk::Button::with_label(if fields.is_empty() {- "Check connection"- } else {- "Connect"- });- body.append(&connect);- connect.connect_clicked(move |button| {- button.set_sensitive(false);- let (method, args) = if plan["status"] == "needsFields" {- let values: serde_json::Map<String, Value> = fields- .iter()- .map(|(k, v)| (k.clone(), v.text().to_string().into()))- .collect();- (- "composioConnectFields",- json!({"toolkit":toolkit,"mode":plan["mode"],"fields":values}),- )- } else {- ("composioConnection", json!({"id":plan["connection"]}))- };- let (ui, entry, toolkit, window, button, fields) = (- ui.clone(),- entry.clone(),- toolkit.clone(),- window.clone(),- button.clone(),- fields.clone(),- );- client::call(method, args, move |r| {- button.set_sensitive(true);- match r {- Ok(v) if v["status"] == "active" => {- for (_, input) in fields {- input.set_text("");- }- client::call(- "connectorRequestFinish",- json!({"entryId":entry,"connectorId":format!("composio-{toolkit}")}),- move |r| match r {- Ok(_) => {- window.close();- }- Err(e) => toast(&ui, &e),- },- );- }- Ok(_) => toast(&ui, "Finish signing in, then check again."),- Err(e) => toast(&ui, &e),- }- });- });- });-}--fn edit_credentials(ui: &App, connector: &Value) {- let (window, body) = dialog(ui, connector["name"].as_str().unwrap_or("Credentials"));- body.append(&label(- "Enter only values to replace, or an op:// reference.",- &["secondary"],- ));- let mut fields = Vec::new();- for key in connector["keys"]- .as_array()- .into_iter()- .flatten()- .filter_map(Value::as_str)- {- let input = gtk::PasswordEntry::builder()- .placeholder_text(key)- .show_peek_icon(true)- .build();- body.append(&input);- fields.push((key.to_owned(), input));- }- let save = gtk::Button::with_label("Save credentials");- body.append(&save);- let (ui, id) = (ui.clone(), connector["id"].clone());- save.connect_clicked(move |button| {- let values: serde_json::Map<String, Value> = fields- .iter()- .filter(|(_, v)| !v.text().is_empty())- .map(|(k, v)| (k.clone(), v.text().to_string().into()))- .collect();- if values.is_empty() {- return;- }- button.set_sensitive(false);- let (ui, window, button, fields) =- (ui.clone(), window.clone(), button.clone(), fields.clone());- client::call(- "credentialUpdateConnector",- json!({"id":id,"fields":values}),- move |r| {- button.set_sensitive(true);- match r {- Ok(_) => {- for (_, input) in fields {- input.set_text("");- }- window.close();- }- Err(e) => toast(&ui, &e),- }- },- );- });-}diff --git a/apps/linux/src/dialogs.rs b/apps/linux/src/dialogs.rsdeleted file mode 100644index 509ac354..00000000--- a/apps/linux/src/dialogs.rs+++ /dev/null@@ -1,1724 +0,0 @@-//! Bot and group editors, full-conversation trace, settings/pairing and the bot menu.--use crate::client;-use crate::rows::{icon_button, label};-use crate::ui::{self, App, MenuItem};-use crate::{avatar, markup};-use adw::prelude::*;-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) {- 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();- (dialog, view, header)-}--// MARK: editor--pub 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 d = Rc::new(RefCell::new(bot.clone().unwrap_or_else(|| {- let n = client_seed();- json!({- "name": "", "description": "", "permission": "auto", "model": null, "command": null, "cwd": "",- "avatarShape": avatar::SHAPES[n % avatar::SHAPES.len()],- "avatarColor": avatar::COLORS[n % avatar::COLORS.len()].0,- "backend": backends.iter().find(|b| b["available"] == true).and_then(|b| b["id"].as_str()).unwrap_or("claude"),- })- })));-- if d.borrow()["managedWorkspace"] == true {- d.borrow_mut()["cwd"] = "".into();- }- let (dialog, view, header) =- header_dialog(if is_new { "New Bot" } else { "Edit Bot" }, 560, 720);- let save = gtk::Button::builder()- .icon_name("object-select-symbolic")- .tooltip_text(if is_new { "Create" } else { "Save" })- .css_classes(["accent-fill", "circular"])- .build();- header.pack_end(&save);-- let page = adw::PreferencesPage::new();- // Profile- let preview = gtk::Box::builder()- .halign(gtk::Align::Center)- .margin_bottom(8)- .build();- let redraw_preview = {- let (preview, d) = (preview.clone(), d.clone());- move || {- while let Some(c) = preview.first_child() {- preview.remove(&c);- }- let b = d.borrow();- preview.append(&avatar::shape(- b["avatarShape"].as_str().unwrap_or("blob"),- b["avatarColor"].as_str().unwrap_or("blue"),- 84,- avatar::Mood::Working,- ));- }- };- 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();- // A new bot is named from its first conversations (Grok Bot's flow); rename it any time after.- name.set_visible(!is_new);- profile.add(&name);- 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::shape(- s,- d.borrow()["avatarColor"].as_str().unwrap_or("blue"),- 30,- avatar::Mood::Idle,- ))- .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();- redraw();- });- shapes.insert(&btn, -1);- }- profile.add(&shapes);- 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 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.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 (d2, redraw) = (d.clone(), redraw_preview.clone());- btn.connect_clicked(move |_| {- d2.borrow_mut()["avatarColor"] = (*cname).into();- redraw();- });- colors.insert(&btn, -1);- }- profile.add(&colors);- page.add(&profile);-- // Standing instructions- let instructions_group = adw::PreferencesGroup::builder()- .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(),- );- 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 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"- };- names.append(&format!("{}{tag}", b["name"].as_str().unwrap_or("")));- ids.push(b["id"].as_str().unwrap_or("").to_owned());- }- names.append("Custom ACP command");- ids.push("custom".into());- let current = d.borrow()["backend"].as_str().unwrap_or("").to_owned();- let harness = adw::ComboRow::builder()- .title("Runs on")- .model(&names)- .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();- 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(),- );- move || {- 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(""),- );- d.borrow_mut()["backend"] = id.into();- }- };- sync_harness();- harness.connect_selected_notify(move |_| sync_harness());- page.add(&agent);-- // Project folder (native folder chooser: the host runs on this computer)- let project = adw::PreferencesGroup::builder()- .title("Workspace (project folder optional)")- .build();- let folder_row = adw::ActionRow::builder()- .title(- d.borrow()["cwd"]- .as_str()- .filter(|s| !s.is_empty())- .unwrap_or("Personal workspace · allocated automatically"),- )- .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);- let personal = gtk::Button::builder()- .icon_name("edit-undo-symbolic")- .tooltip_text("Use personal workspace")- .css_classes(["flat"])- .valign(gtk::Align::Center)- .build();- folder_row.add_suffix(&personal);- {- let (draft, row) = (d.clone(), folder_row.clone());- personal.connect_clicked(move |_| {- draft.borrow_mut()["cwd"] = "".into();- row.set_title("Personal workspace · allocated automatically");- });- }- {- let (d2, row, dialog2) = (d.clone(), folder_row.clone(), dialog.clone());- let pick = move || {- let chooser = gtk::FileDialog::builder().title("Project folder").build();- let (d3, row2) = (d2.clone(), row.clone());- let parent = dialog2.root().and_downcast::<gtk::Window>();- chooser.select_folder(parent.as_ref(), gtk::gio::Cancellable::NONE, move |res| {- if let Ok(f) = res- && let Some(path) = f.path()- {- let p = path.to_string_lossy().into_owned();- row2.set_title(&p);- d3.borrow_mut()["cwd"] = p.into();- }- });- };- let pick2 = pick.clone();- choose.connect_clicked(move |_| pick());- folder_row.connect_activated(move |_| pick2());- }- page.add(&project);-- // Permissions- 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();- perms.add(¬ify);- let computer = adw::SwitchRow::builder()- .title("Use the computer")- .subtitle("Let this bot see the screen and use the mouse and keyboard (needs Remote screen in Settings).")- .active(d.borrow()["computer"].as_bool().unwrap_or(false))- .build();- perms.add(&computer);- page.add(&perms);-- view.set_content(Some(&page));- let ui2 = ui.clone();- let dialog2 = dialog.clone();- save.connect_clicked(move |btn| {- 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["permission"] = if auto.is_active() { "auto" } else { "ask" }.into();- body["notify"] = notify.is_active().into();- body["computer"] = computer.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",- "workingChat",- "workingThread",- ] {- 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);- }- }- dialog3.close();- ui3.split.set_show_content(true);- ui::schedule(&ui3);- }- Err(e) => {- btn2.set_sensitive(true);- ui::toast(&ui3, &e);- }- },- );- });- dialog.present(Some(&ui.window));-}--// MARK: group editor--/// Create a group chat, or change its name, what it's for and who's in it (GroupEditorView).-/// Bots are picked like recipients: chips on top, a search, and the bots not in it yet.-pub fn group_editor(ui: &App, group: Option<Value>) {- let is_new = group.is_none();- let group_id = group- .as_ref()- .and_then(|g| g["id"].as_str())- .map(str::to_owned);- let members: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(- group- .as_ref()- .and_then(|g| g["members"].as_array())- .into_iter()- .flatten()- .filter_map(|m| m.as_str().map(str::to_owned))- .collect(),- ));- let (dialog, body, save) = modal(- if is_new {- "New group chat"- } else {- "Group chat"- },- if is_new { "Create" } else { "Save" },- 420,- 560,- );- let preview = gtk::Box::builder().halign(gtk::Align::Center).build();- body.append(&preview);-- let bots_label = field_label("Bots");- let chips = gtk::Box::builder().spacing(6).build();- let chips_scroll = gtk::ScrolledWindow::builder()- .child(&chips)- .vscrollbar_policy(gtk::PolicyType::Never)- .hscrollbar_policy(gtk::PolicyType::External)- .build();- let search = gtk::Entry::builder().css_classes(["field-box"]).build();- let candidates = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(2)- .build();- let bots_field = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(8)- .build();- bots_field.append(&bots_label);- bots_field.append(&chips_scroll);- bots_field.append(&search);- bots_field.append(&candidates);- let help = label(- "Everyone answers in turn unless you @mention someone. Each bot works in its own folder with its own tools.",- &["footnote", "tertiary"],- );- help.set_wrap(true);- bots_field.append(&help);- body.append(&bots_field);-- let name = gtk::Entry::builder()- .css_classes(["field-box"])- .text(- group- .as_ref()- .and_then(|g| g["name"].as_str())- .unwrap_or(""),- )- .build();- body.append(&field("Name", &name));- let about = gtk::TextView::builder()- .wrap_mode(gtk::WrapMode::WordChar)- .build();- about.buffer().set_text(- group- .as_ref()- .and_then(|g| g["description"].as_str())- .unwrap_or(""),- );- body.append(&field(- "About",- &text_area(&about, "What this group works on (optional)", 2, 5),- ));- if let Some(g) = group.as_ref() {- let del = gtk::Button::builder()- .label("Delete group chat")- .css_classes(["secondary-pill", "danger-text"])- .halign(gtk::Align::Start)- .margin_top(8)- .build();- let (ui2, dialog2, id, gname) = (- ui.clone(),- dialog.clone(),- g["id"].as_str().unwrap_or_default().to_owned(),- g["name"].as_str().unwrap_or("").to_owned(),- );- del.connect_clicked(move |_| {- dialog2.close();- confirm_delete(&ui2, &id, &gname, true);- });- body.append(&del);- }-- let names_of = {- let ui2 = ui.clone();- move |ids: &[String]| -> Vec<String> {- let st = ui2.state.borrow();- ids.iter()- .filter_map(|id| st.bots.get(id)?["name"].as_str().map(str::to_owned))- .collect()- }- };- // Redraws the avatar, chips, candidates and default name from `members` and the search.- let sync: Rc<RefCell<Box<dyn Fn()>>> = Rc::new(RefCell::new(Box::new(|| {})));- let toggle = {- let (members, sync, search) = (members.clone(), Rc::downgrade(&sync), search.clone());- move |id: &str| {- {- let mut m = members.borrow_mut();- if m.iter().any(|x| x == id) {- m.retain(|x| x != id);- } else {- m.push(id.to_owned());- }- }- search.set_text("");- if let Some(sync) = sync.upgrade() {- (sync.borrow())();- }- }- };- let toggle = Rc::new(toggle);- *sync.borrow_mut() = {- let (ui2, members, chips, chips_scroll, candidates, search, name, save, toggle) = (- ui.clone(),- members.clone(),- chips.clone(),- chips_scroll.clone(),- candidates.clone(),- search.clone(),- name.clone(),- save.clone(),- toggle.clone(),- );- let names_of = names_of.clone();- let preview = preview.clone();- Box::new(move || {- let m = members.borrow().clone();- let st = ui2.state.borrow();- ui::clear(&preview);- if m.is_empty() {- let icon = gtk::Image::builder()- .icon_name("system-users-symbolic")- .pixel_size(29)- .width_request(72)- .height_request(72)- .css_classes(["secondary"])- .build();- preview.append(&icon);- } else {- preview.append(&avatar::of(- &st.bots,- &json!({"kind": "group", "members": m}),- 72,- false,- ));- }- bots_label.set_label(&format!("Bots · {}", m.len()));- ui::clear(&chips);- chips_scroll.set_visible(!m.is_empty());- for id in &m {- if let Some(b) = st.bots.get(id) {- let (t, id) = (toggle.clone(), id.clone());- chips.append(&crate::compose::bot_chip(&st.bots, b, move || t(&id)));- }- }- search.set_placeholder_text(Some(if m.is_empty() {- "Search bots"- } else {- "Add another bot"- }));- let q = search.text().trim().to_lowercase();- ui::clear(&candidates);- for b in ui::roster(&st).into_iter().filter(|b| {- !ui::is_group(b)- && !m.iter().any(|x| b["id"] == x.as_str())- && (q.is_empty()- || b["name"]- .as_str()- .is_some_and(|n| n.to_lowercase().contains(&q)))- }) {- let row = gtk::Box::builder().spacing(12).build();- row.append(&avatar::of(&st.bots, b, 26, false));- let text = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(1)- .hexpand(true)- .build();- let bname = b["name"].as_str().unwrap_or("");- text.append(&label(bname, &["body13"]));- text.append(&label(&ui::folder(b), &["footnote", "tertiary"]));- row.append(&text);- let plus = gtk::Image::from_icon_name("list-add-symbolic");- plus.add_css_class("tertiary");- row.append(&plus);- let btn = gtk::Button::builder()- .child(&row)- .css_classes(["candidate"])- .tooltip_text(format!("Add {bname}"))- .build();- let (t, id) = (toggle.clone(), b["id"].as_str().unwrap_or("").to_owned());- btn.connect_clicked(move |_| t(&id));- candidates.append(&btn);- }- drop(st);- let names = names_of(&m);- name.set_placeholder_text(Some(&if names.is_empty() {- "Name".to_owned()- } else {- names.join(", ")- }));- save.set_sensitive(!m.is_empty());- })- };- {- let sync = sync.clone();- search.connect_changed(move |_| (sync.borrow())());- }- {- let (ui2, members, toggle) = (ui.clone(), members.clone(), toggle.clone());- search.connect_activate(move |s| {- let q = s.text().trim().to_lowercase();- let first = {- let st = ui2.state.borrow();- let m = members.borrow();- ui::roster(&st)- .into_iter()- .find(|b| {- !ui::is_group(b)- && !m.iter().any(|x| b["id"] == x.as_str())- && b["name"]- .as_str()- .is_some_and(|n| n.to_lowercase().contains(&q))- })- .and_then(|b| b["id"].as_str().map(str::to_owned))- };- if let Some(id) = first {- toggle(&id);- }- });- }- (sync.borrow())();-- let (ui2, dialog2) = (ui.clone(), dialog.clone());- save.connect_clicked(move |btn| {- let m = members.borrow().clone();- let typed = name.text().trim().to_owned();- let final_name = if typed.is_empty() {- names_of(&m).join(", ")- } else {- typed- };- let buf = about.buffer();- let description = buf- .text(&buf.start_iter(), &buf.end_iter(), false)- .trim()- .to_owned();- let (method, body) = match &group_id {- Some(id) => (- "updateBot",- json!({"id": id, "name": final_name, "members": m, "description": description}),- ),- None => (- "createBot",- json!({"id": "", "kind": "group", "name": final_name, "members": m, "description": description}),- ),- };- btn.set_sensitive(false);- let (ui3, dialog3, btn2) = (ui2.clone(), dialog2.clone(), btn.clone());- client::call(method, body, move |r| match r {- Ok(v) => {- let bot = v["bot"].clone();- let id = bot["id"].as_str().unwrap_or_default().to_owned();- ui3.state.borrow_mut().bots.insert(id.clone(), bot);- dialog3.close();- if is_new {- ui::select(&ui3, &id);- } else {- ui::schedule(&ui3);- }- }- Err(e) => {- btn2.set_sensitive(true);- ui::toast(&ui3, &e);- }- });- });- dialog.present(Some(&ui.window));-}--/// A sheet with Codync's modal header (title, a check to save, close) over a scrolling body.-fn modal(- title: &str,- save_tip: &str,- width: i32,- height: i32,-) -> (adw::Dialog, gtk::Box, gtk::Button) {- let save = icon_button("object-select-symbolic", save_tip);- let close = icon_button("window-close-symbolic", "Close");- let head = gtk::Box::builder()- .spacing(8)- .margin_start(16)- .margin_end(10)- .height_request(48)- .build();- let t = label(title, &["semibold"]);- t.set_hexpand(true);- head.append(&t);- head.append(&save);- head.append(&close);- let body = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(12)- .margin_start(16)- .margin_end(16)- .margin_top(4)- .margin_bottom(16)- .build();- let col = gtk::Box::new(gtk::Orientation::Vertical, 0);- col.append(&head);- col.append(- >k::ScrolledWindow::builder()- .child(&body)- .vexpand(true)- .hscrollbar_policy(gtk::PolicyType::Never)- .build(),- );- let dialog = adw::Dialog::builder()- .title(title)- .content_width(width)- .content_height(height)- .child(&col)- .build();- {- let d = dialog.clone();- close.connect_clicked(move |_| {- d.close();- });- }- (dialog, body, save)-}--fn field_label(text: &str) -> gtk::Label {- label(text, &["field-label"])-}--/// A labelled field (the editors' `Field`).-fn field(title: &str, content: &impl IsA<gtk::Widget>) -> gtk::Box {- let b = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(6)- .build();- b.append(&field_label(title));- b.append(content);- b-}--/// A multi-line field box with a placeholder, `min`…`max` lines tall.-fn text_area(view: >k::TextView, placeholder: &str, min: i32, max: i32) -> gtk::Box {- let hint = label(placeholder, &["tertiary"]);- hint.set_valign(gtk::Align::Start);- hint.set_can_target(false);- let buf = view.buffer();- hint.set_visible(buf.char_count() == 0);- {- let hint = hint.clone();- buf.connect_changed(move |b| hint.set_visible(b.char_count() == 0));- }- let scroll = gtk::ScrolledWindow::builder()- .child(view)- .hscrollbar_policy(gtk::PolicyType::Never)- .min_content_height(min * 16)- .max_content_height(max * 16)- .propagate_natural_height(true)- .build();- let overlay = gtk::Overlay::builder().child(&scroll).build();- overlay.add_overlay(&hint);- let b = gtk::Box::builder().css_classes(["field-box-area"]).build();- overlay.set_hexpand(true);- b.append(&overlay);- b-}--pub fn confirm(- ui: &App,- title: &str,- body: &str,- action: &str,- destructive: bool,- f: impl FnOnce() + 'static,-) {- let callback = std::cell::RefCell::new(Some(f));- let alert = adw::AlertDialog::new(Some(title), Some(body));- alert.add_responses(&[("cancel", "Cancel"), ("ok", action)]);- if destructive {- alert.set_response_appearance("ok", adw::ResponseAppearance::Destructive);- }- alert.connect_response(None, move |_, r| {- if r == "ok"- && let Some(f) = callback.borrow_mut().take()- {- f();- }- });- alert.present(Some(&ui.window));-}--fn confirm_delete(ui: &App, id: &str, name: &str, group: bool) {- let id = id.to_owned();- confirm(- ui,- &format!("Delete {name}?"),- if group {- "The group chat is removed. Its bots stay."- } else {- "Files it changed on your computer stay as they are."- },- if group {- "Delete group chat"- } else {- "Delete bot and its conversation"- },- true,- move || client::call("deleteBot", json!({"botId": id}), |_| {}),- );-}--fn client_seed() -> usize {- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.subsec_nanos() as usize)- .unwrap_or(0)-}--// MARK: trace--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 entries = st.entries.get(&id).cloned().unwrap_or_default();- // Main chat first, then each thread under its root's text.- for (thread, lane) in lanes(&entries) {- if let Some(root) = thread {- let text = entries- .iter()- .find(|x| x["id"] == root)- .map(crate::rows::message_text)- .unwrap_or_default();- list.append(- >k::Label::builder()- .label(format!("Thread · {}", short(&text, 60)))- .xalign(0.0)- .ellipsize(gtk::pango::EllipsizeMode::End)- .css_classes(["title-4"])- .margin_top(16)- .build(),- );- }- trace_lane(&list, &lane);- }- view.set_content(Some(- >k::ScrolledWindow::builder()- .child(&list)- .vexpand(true)- .build(),- ));- dialog.present(Some(&ui.window));-}--fn short(text: &str, n: usize) -> String {- let line = text.lines().next().unwrap_or("");- if line.chars().count() > n || text.contains('\n') {- format!("{}…", line.chars().take(n).collect::<String>())- } else {- line.to_owned()- }-}--/// Entries split by lane: the main chat (`None`) first, then threads in the order-/// they first appear, each keeping its entries' order.-fn lanes(entries: &[Value]) -> Vec<(Option<String>, Vec<&Value>)> {- let mut out: Vec<(Option<String>, Vec<&Value>)> = vec![(None, vec![])];- for e in entries {- let t = e["threadId"].as_str().map(str::to_owned);- match out.iter_mut().find(|(k, _)| *k == t) {- Some((_, l)) => l.push(e),- None => out.push((t, vec![e])),- }- }- out-}--/// One lane's entries grouped by turn, each group titled by that turn's message.-fn trace_lane(list: >k::Box, entries: &[&Value]) {- let mut turn = -1i64;- let mut group = adw::PreferencesGroup::new();- for e in entries {- 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")- .map(|x| crate::rows::message_text(x))- .unwrap_or_default();- group = adw::PreferencesGroup::builder()- .title(gtk::glib::markup_escape_text(- &title.chars().take(80).collect::<String>(),- ))- .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 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(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.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.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()- }- "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);- }-}--// MARK: menus--/// A bot's actions: from the roster (right-click) like the Mac sidebar's menu, or from-/// the chat header's More button.-pub fn bot_menu(ui: &App, parent: >k::Widget, point: Option<(f64, f64)>, id: &str, roster: bool) {- let Some(bot) = ui.state.borrow().bots.get(id).cloned() else {- return;- };- let group = bot["kind"] == "group";- let pinned = bot["pinned"].as_bool().unwrap_or(false);- let name = bot["name"].as_str().unwrap_or("").to_owned();- let mut items = vec![];- if !roster {- let ui2 = ui.clone();- items.push(MenuItem::new(- "view-list-symbolic",- "Full conversation",- Box::new(move || trace(&ui2)),- ));- }- {- let id2 = id.to_owned();- items.push(MenuItem::new(- "view-pin-symbolic",- if pinned { "Unpin" } else { "Pin" },- Box::new(move || {- client::call("updateBot", json!({"id": id2, "pinned": !pinned}), |_| {});- }),- ));- }- if roster {- let id2 = id.to_owned();- items.push(MenuItem::new(- "mail-unread-symbolic",- "Mark as Read",- Box::new(move || client::call("markRead", json!({"botId": id2, "all": true}), |_| {})),- ));- }- {- let (ui2, bot2) = (ui.clone(), bot.clone());- let item = MenuItem::new(- if group {- "system-users-symbolic"- } else {- "document-edit-symbolic"- },- if group {- "Edit group…"- } else {- "Edit profile…"- },- Box::new(move || {- if group {- group_editor(&ui2, Some(bot2.clone()));- } else {- editor(&ui2, Some(bot2.clone()));- }- }),- );- items.push(if roster { item.divider() } else { item });- }- if roster {- let id2 = id.to_owned();- items.push(- MenuItem::new(- "edit-copy-symbolic",- "Copy conversation ID",- Box::new(move || {- if let Some(d) = gtk::gdk::Display::default() {- d.clipboard().set_text(&id2);- }- }),- )- .divider(),- );- }- if !group {- for (icon, title, memory) in [- ("document-properties-symbolic", "Memory", true),- ("alarm-symbolic", "Routines", false),- ] {- let (ui2, id2) = (ui.clone(), id.to_owned());- items.push(MenuItem::new(- icon,- title,- Box::new(move || {- if memory {- crate::manage::memory(&ui2, &id2);- } else {- crate::manage::routines(&ui2, &id2);- }- }),- ));- }- }- if !group {- let (ui2, id2) = (ui.clone(), id.to_owned());- items.push(MenuItem::new(- "view-refresh-symbolic",- "New session",- Box::new(move || {- let id3 = id2.clone();- confirm(- &ui2,- "Start a new session?",- "The conversation stays here, but the agent starts with a fresh context.",- "New session",- false,- move || client::call("newSession", json!({"botId": id3}), |_| {}),- );- }),- ));- }- if roster {- let id2 = id.to_owned();- items.push(- MenuItem::new(- "view-conceal-symbolic",- "Hide from sidebar",- Box::new(move || {- client::call("updateBot", json!({"id": id2, "hidden": true}), |_| {});- }),- )- .divider(),- );- }- {- let (ui2, id2) = (ui.clone(), id.to_owned());- let item = MenuItem::new(- "user-trash-symbolic",- if group { "Delete group" } else { "Delete" },- Box::new(move || confirm_delete(&ui2, &id2, &name, group)),- )- .destructive();- items.push(if roster { item } else { item.divider() });- }- ui::popup_menu(parent, point, items);-}--/// The sidebar's Account panel: usage, the mobile app, help and Settings.-pub fn account_menu(ui: &App, anchor: >k::Button) {- let open = |url: &'static str| -> Box<dyn Fn()> {- Box::new(move || {- gtk::UriLauncher::new(url).launch(- None::<>k::Window>,- gtk::gio::Cancellable::NONE,- |_| {},- );- })- };- let (ui2, ui3) = (ui.clone(), ui.clone());- let items = vec![- MenuItem::new(- "power-profile-balanced-symbolic",- "Usage",- Box::new(move || settings_page(&ui2, "usage")),- )- .chevron(),- MenuItem::new(- "phone-symbolic",- "Get Codync for mobile",- open("https://apps.apple.com/app/id6760984418"),- ),- MenuItem::new(- "help-browser-symbolic",- "Help & documentation",- open("https://github.com/leepokai/codync#readme"),- )- .divider(),- MenuItem::new(- "dialog-warning-symbolic",- "Report an issue",- open("https://github.com/leepokai/codync/issues"),- ),- // Computers & devices, usage and updates are pages of Settings.- MenuItem::new(- "emblem-system-symbolic",- "Settings",- Box::new(move || settings(&ui3)),- )- .divider(),- ];- ui::popup_menu(anchor, None, items);-}--/// Settings' Usage page: limits per provider (`UsageLimits` on the Mac).-fn usage_page(ui: &App) -> adw::PreferencesPage {- let page = adw::PreferencesPage::builder()- .title("Usage")- .icon_name("power-profile-balanced-symbolic")- .name("usage")- .build();- let usage = adw::PreferencesGroup::new();- let st = ui.state.borrow();- let mut any = false;- for p in st.usage["providers"].as_array().into_iter().flatten() {- for w in p["windows"].as_array().into_iter().flatten() {- any = true;- 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("")- ))- .subtitle(gtk::glib::markup_escape_text(&reset))- .build();- let pct = w["percent"].as_f64().unwrap_or(0.0);- row.add_suffix(- >k::LevelBar::builder()- .min_value(0.0)- .max_value(100.0)- .value(pct)- .width_request(120)- .valign(gtk::Align::Center)- .build(),- );- row.add_suffix(>k::Label::new(Some(&format!("{pct:.0}%"))));- usage.add(&row);- }- }- if !any {- usage.add(&label("No usage information yet.", &["secondary"]));- }- page.add(&usage);- page-}--// MARK: settings & pairing--/// Remote screen: see and control this computer from the iPhone, and let bots use it.-/// Only this computer can turn it on (the host checks the request comes from itself).-fn remote_screen_group() -> adw::PreferencesGroup {- let group = adw::PreferencesGroup::builder()- .title("Remote screen")- .description("See and control this computer from your iPhone, and let bots use it. The first time, your desktop asks you to allow screen sharing.")- .build();- let row = adw::SwitchRow::builder()- .title("Allow remote screen")- .build();- let status = adw::ActionRow::builder().title("Status").build();- status.set_visible(false);- group.add(&row);- group.add(&status);- let show = {- let status = status.clone();- move |v: &Value| {- let text = if v["enabled"] != true {- None- } else if v["connected"] != true {- Some("Waiting for screen sharing approval…")- } else if v["input"] != true {- Some("Viewing only: control wasn't allowed")- } else {- Some("Ready")- };- status.set_visible(text.is_some());- status.set_subtitle(text.unwrap_or_default());- }- };- {- let row = row.clone();- let show = show.clone();- client::call("screenStatus", client::empty(), move |r| {- if let Ok(v) = r {- row.set_active(v["enabled"] == true);- show(&v);- } else {- // A host from before Remote screen.- row.set_sensitive(false);- }- });- }- row.connect_active_notify(move |row| {- let show = show.clone();- client::call(- "setScreenEnabled",- json!({"enabled": row.is_active()}),- move |r| {- if let Ok(v) = r {- show(&v);- }- },- );- });- group-}--fn host_updates_group(ui: &App) -> adw::PreferencesGroup {- let group = adw::PreferencesGroup::builder()- .title("Host updates")- .description("Automatic updates wait until this computer's bots are idle.")- .build();- let status = adw::ActionRow::builder()- .title("Checking update settings…")- .build();- let check = gtk::Button::builder()- .label("Check for updates")- .valign(gtk::Align::Center)- .build();- let install = gtk::Button::builder()- .label("Install update")- .valign(gtk::Align::Center)- .sensitive(false)- .build();- let automatic = adw::SwitchRow::builder()- .title("Automatically update the host")- .sensitive(false)- .build();- status.add_suffix(&check);- status.add_suffix(&install);- group.add(&status);- group.add(&automatic);- let syncing = std::rc::Rc::new(std::cell::Cell::new(false));- // The App Store couldn't be asked: installing is the person's call ("Update anyway").- let skip_app_check = std::rc::Rc::new(std::cell::Cell::new(false));- let render = {- let (status, install, automatic, syncing, skip_app_check) = (- status.clone(),- install.clone(),- automatic.clone(),- syncing.clone(),- skip_app_check.clone(),- );- move |value: &Value| {- let standalone = value["method"] == "standalone";- let version = value["state"]["availableVersion"].as_str();- status.set_title(- &version.map_or_else(|| "Host updates".to_owned(), |v| format!("Version {v}")),- );- let required = value["state"]["requiredApp"]- .as_str()- .filter(|_| value["state"]["phase"] == "waitingForApp");- let in_review = required.and(value["state"]["appStoreVersion"].as_str());- let description = match (value["method"].as_str(), required, in_review) {- (Some("homebrew"), ..) => {- "Update with brew upgrade leepokai/codync/codync-host".to_owned()- }- (Some("development"), ..) => {- "Rebuild this development installation to update it.".to_owned()- }- (Some("appBundle"), ..) => {- "Update the Codync Mac app to update its bundled host.".to_owned()- }- (_, Some(app), Some(store)) => format!(- "Waits for the iPhone app {app} (the App Store has {store}); it installs after review."- ),- (_, Some(app), None) => format!(- "Couldn't check the App Store for the iPhone app {app}. Paired iPhones may need it before they can connect."- ),- _ => value["state"]["error"]- .as_str()- .unwrap_or_else(|| match value["state"]["phase"].as_str() {- Some("complete") => "Update installed and host restarted.",- Some("installing" | "checking" | "scheduled") => "Updating the host…",- Some("upToDate") => "The host is up to date.",- _ => "Checks signed releases for this computer.",- })- .to_owned(),- };- status.set_subtitle(&description);- skip_app_check.set(required.is_some() && in_review.is_none());- install.set_label(if skip_app_check.get() {- "Update anyway"- } else {- "Install update"- });- install.set_sensitive(- standalone- && version.is_some()- && in_review.is_none()- && !matches!(- value["state"]["phase"].as_str(),- Some("installing" | "checking" | "scheduled" | "complete")- ),- );- syncing.set(true);- automatic.set_active(value["automatic"] == true);- automatic.set_sensitive(standalone);- syncing.set(false);- }- };- {- let (render, status) = (render.clone(), status.clone());- client::call(- "hostUpdateStatus",- client::empty(),- move |result| match result {- Ok(value) => render(&value),- Err(error) => status.set_subtitle(&error),- },- );- }- {- let (render, ui) = (render.clone(), ui.clone());- check.connect_clicked(move |button| {- button.set_sensitive(false);- let (button, render, ui) = (button.clone(), render.clone(), ui.clone());- client::call("checkHostUpdate", client::empty(), move |result| {- button.set_sensitive(true);- match result {- Ok(value) => render(&value),- Err(error) => ui::toast(&ui, &error),- }- });- });- }- {- let (render, ui) = (render.clone(), ui.clone());- automatic.connect_active_notify(move |row| {- if syncing.get() {- return;- }- let (row, render, ui, syncing) =- (row.clone(), render.clone(), ui.clone(), syncing.clone());- let enabled = row.is_active();- client::call(- "setHostAutomaticUpdates",- json!({"enabled": enabled}),- move |result| match result {- Ok(value) => render(&value),- Err(error) => {- syncing.set(true);- row.set_active(!enabled);- syncing.set(false);- ui::toast(&ui, &error);- }- },- );- });- }- {- let (ui, status, group) = (ui.clone(), status.clone(), group.downgrade());- install.connect_clicked(move |button| {- button.set_sensitive(false);- let (ui, status, button, render, group) = (- ui.clone(),- status.clone(),- button.clone(),- render.clone(),- group.clone(),- );- client::call(- "installHostUpdate",- json!({"force": false, "skipAppCheck": skip_app_check.get()}),- move |result| match result {- Ok(_) => {- status.set_subtitle("Updating the host; reconnecting when it is ready…");- let mut attempts = 0;- gtk::glib::timeout_add_seconds_local(3, move || {- attempts += 1;- if group.upgrade().is_none() || attempts > 120 {- return gtk::glib::ControlFlow::Break;- }- let render = render.clone();- client::call("hostUpdateStatus", client::empty(), move |result| {- if let Ok(value) = result {- render(&value);- }- });- gtk::glib::ControlFlow::Continue- });- }- Err(error) => {- button.set_sensitive(true);- ui::toast(&ui, &error);- }- },- );- });- }- group-}--/// Settings opened on its first page, Computers & devices.-pub fn settings(ui: &App) {- settings_page(ui, "computers");-}--/// Settings: Computers & devices, Usage and Updates as pages in a sidebar, like the Mac's.-pub fn settings_page(ui: &App, name: &str) {- let dialog = adw::PreferencesDialog::builder()- .title("Settings")- .content_width(760)- .content_height(640)- .build();- let page = adw::PreferencesPage::builder()- .title("Computers")- .icon_name("computer-symbolic")- .name("computers")- .build();- let credentials = adw::PreferencesGroup::new();- let button = gtk::Button::with_label("Credentials");- let ui2 = ui.clone();- button.connect_clicked(move |_| crate::connections::credentials(&ui2));- credentials.add(&button);- let marketplace = gtk::Button::with_label("Marketplace");- let ui2 = ui.clone();- marketplace.connect_clicked(move |_| crate::market::open(&ui2));- credentials.add(&marketplace);- page.add(&credentials);- let pair = adw::PreferencesGroup::builder()- .title("Pair your iPhone")- .description("Scan with the Codync app or the iPhone Camera.")- .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();- pair.add(©);- page.add(&pair);- client::call("pairing", client::empty(), move |r| {- if let Ok(v) = r- && let Some(url) = v["pairingUrl"].as_str()- && 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();- 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);- cr.paint().ok();- 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.fill().ok();- });- qr_area.queue_draw();- let url = url.to_owned();- copy.connect_clicked(move |b| b.clipboard().set_text(&url));- }- });-- page.add(&remote_screen_group());-- 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 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());- rescan.connect_clicked(move |_| {- let (ui3, dialog3) = (ui2.clone(), dialog2.clone());- client::call("refreshBackends", client::empty(), move |r| {- if let Ok(v) = r {- ui3.state.borrow_mut().hello["backends"] = v["backends"].clone();- }- dialog3.close();- settings(&ui3);- });- });- }- page.add(&agents);- dialog.add(&page);- dialog.add(&usage_page(ui));-- let updates = adw::PreferencesPage::builder()- .title("Updates")- .icon_name("software-update-available-symbolic")- .name("updates")- .build();- updates.add(&host_updates_group(ui));- 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(),- );- updates.add(&about);- dialog.add(&updates);- dialog.set_visible_page_name(name);- dialog.present(Some(&ui.window));-}--/// Shown when the host isn't running: offer to install/start it.-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.",- )- .icon_name("computer-symbolic")- .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));- let (ui2, dialog2) = (ui.clone(), dialog.clone());- btn.connect_clicked(move |b| {- b.set_sensitive(false);- let (ui3, dialog3, b2) = (ui2.clone(), dialog2.clone(), b.clone());- client::install_host(move |r| match r {- Ok(()) => {- dialog3.close();- gtk::glib::timeout_add_seconds_local_once(1, move || ui::reconnect(&ui3));- }- Err(e) => {- b2.set_sensitive(true);- ui::toast(&ui3, &e);- }- });- });- dialog.present(Some(&ui.window));-}--#[cfg(test)]-mod tests {- use super::lanes;- use serde_json::json;-- #[test]- fn trace_lanes() {- let e = [- json!({"id": "a"}),- json!({"id": "b", "threadId": "a"}),- json!({"id": "c"}),- json!({"id": "d", "threadId": "c"}),- json!({"id": "e", "threadId": "a"}),- ];- let ids = |l: &[&serde_json::Value]| {- l.iter()- .map(|x| x["id"].as_str().unwrap_or(""))- .collect::<String>()- };- let l = lanes(&e);- assert_eq!(l.len(), 3);- assert_eq!((l[0].0.as_deref(), ids(&l[0].1).as_str()), (None, "ac"));- assert_eq!(- (l[1].0.as_deref(), ids(&l[1].1).as_str()),- (Some("a"), "be")- );- assert_eq!((l[2].0.as_deref(), ids(&l[2].1).as_str()), (Some("c"), "d"));- }-}diff --git a/apps/linux/src/main.rs b/apps/linux/src/main.rsdeleted file mode 100644index 7dced416..00000000--- a/apps/linux/src/main.rs+++ /dev/null@@ -1,277 +0,0 @@-//! Codync for Linux — the same bot chat as the iPhone and Mac apps, in GTK 4 + libadwaita.--mod avatar;-mod client;-mod compat;-mod compose;-mod connections;-mod dialogs;-mod manage;-mod market;-mod markup;-mod orb;-mod rows;-mod ui;--use adw::prelude::*;--/// The Apple apps' `Palette` (CodyncKit/Design/Theme.swift), light then dark.-struct Palette {- background: &'static str,- surface: &'static str,- bubble_agent: &'static str,- bubble_user: &'static str,- border: &'static str,- text: &'static str,- secondary: &'static str,- tertiary: &'static str,- accent_fill: &'static str,- on_accent: &'static str,- accent_dim: &'static str,- danger: &'static str,- code: &'static str,- panel: &'static str,-}--const LIGHT: Palette = Palette {- background: "#FFFFFF",- surface: "#F4F4F4",- bubble_agent: "#F0F0F0",- bubble_user: "#E2E2E2",- border: "#E6E6E6",- text: "#141414",- secondary: "#6B6B6B",- tertiary: "#9B9B9B",- accent_fill: "#000000",- on_accent: "#FFFFFF",- accent_dim: "#D9D9D9",- danger: "#C23A2B",- code: "#F4F4F4",- panel: "#FAFAFA",-};--const DARK: Palette = Palette {- background: "#0A0A0A",- surface: "#141414",- bubble_agent: "#1C1C1C",- bubble_user: "#3A3A3A",- border: "#262626",- text: "#F2F2F2",- secondary: "#9A9A9A",- tertiary: "#6E6E6E",- accent_fill: "#FFFFFF",- on_accent: "#000000",- accent_dim: "#333333",- danger: "#F0A7A7",- code: "#111111",- panel: "#1B1B1B",-};--fn colors(p: &Palette) -> String {- format!(- "@define-color cd_bg {};\n@define-color cd_surface {};\n@define-color cd_agent {};\n@define-color cd_user {};\n\- @define-color cd_border {};\n@define-color cd_text {};\n@define-color cd_secondary {};\n@define-color cd_tertiary {};\n\- @define-color cd_accent {};\n@define-color cd_on_accent {};\n@define-color cd_accent_dim {};\n@define-color cd_danger {};\n\- @define-color cd_code {};\n@define-color cd_panel {};\n@define-color cd_warning #F0A030;\n",- p.background,- p.surface,- p.bubble_agent,- p.bubble_user,- p.border,- p.text,- p.secondary,- p.tertiary,- p.accent_fill,- p.on_accent,- p.accent_dim,- p.danger,- p.code,- p.panel- )-}--/// Sizes follow the Mac app (SwiftUI points = GTK px): body 12, secondary 11,-/// footnote/caption 10, headline 13, title3 15, title2 17.-const CSS: &str = r#"-@define-color window_bg_color @cd_bg;-@define-color window_fg_color @cd_text;-@define-color view_bg_color @cd_bg;-@define-color view_fg_color @cd_text;-@define-color headerbar_bg_color @cd_bg;-@define-color headerbar_fg_color @cd_text;-@define-color headerbar_border_color @cd_border;-@define-color headerbar_shade_color transparent;-@define-color sidebar_bg_color @cd_surface;-@define-color sidebar_fg_color @cd_text;-@define-color sidebar_border_color @cd_border;-@define-color dialog_bg_color @cd_bg;-@define-color dialog_fg_color @cd_text;-@define-color popover_bg_color @cd_panel;-@define-color popover_fg_color @cd_text;-@define-color card_bg_color @cd_agent;-@define-color accent_bg_color @cd_accent;-@define-color accent_fg_color @cd_on_accent;-@define-color accent_color @cd_text;-switch:checked > slider { background: @cd_on_accent; }-/* Settings groups, like the Mac's CardSection: a filled rounded group, no outline. */-list.boxed-list { background: @cd_surface; box-shadow: none; border-radius: 16px; }-list.boxed-list > row { background: transparent; }--window { font-size: 12px; }-.surface { background: @cd_surface; }-.chat-bg { background: @cd_bg; }-headerbar.flat-header { background: transparent; box-shadow: none; border: none; min-height: 44px; padding: 0; }-headerbar.flat-header windowhandle > box { padding: 0 6px; }-.hline { background: @cd_border; min-height: 1px; }-.vline { background: @cd_border; min-width: 1px; }--.name { font-weight: 600; font-size: 12px; color: @cd_text; }-.secondary { color: @cd_secondary; }-.tertiary { color: @cd_tertiary; }-.warning-text { color: @cd_warning; }-.danger-text { color: @cd_danger; }-.small { font-size: 11px; }-.footnote { font-size: 10px; }-.headline { font-size: 13px; font-weight: 700; }-.title3 { font-size: 15px; }-.title2 { font-size: 17px; font-weight: 600; }-.body13 { font-size: 13px; }-.semibold { font-weight: 600; }-.medium { font-weight: 500; }-.mono { font-family: monospace; }--/* Icon-only button (IconButtonStyle): no fill until hovered. */-button.icon-btn { min-width: 28px; min-height: 28px; padding: 0; border-radius: 8px; background: transparent;- color: @cd_secondary; box-shadow: none; border: none; transition: background 120ms, color 120ms; }-button.icon-btn:hover { background: alpha(@cd_text, 0.08); color: @cd_text; }-button.icon-btn:active { background: alpha(@cd_text, 0.14); }-button.plain { background: transparent; box-shadow: none; border: none; padding: 0; min-height: 0; min-width: 0; }-button.plain:hover { background: transparent; }--button.primary-pill { background: @cd_accent; color: @cd_on_accent; border-radius: 999px; padding: 6px 14px;- font-weight: 500; font-size: 13px; box-shadow: none; border: none; min-height: 0; }-button.primary-pill:hover { background: alpha(@cd_accent, 0.88); }-button.primary-pill:disabled { opacity: 0.4; }-button.secondary-pill { background: @cd_user; color: @cd_text; border-radius: 999px; padding: 6px 14px;- font-weight: 500; box-shadow: none; border: none; min-height: 0; }-button.secondary-pill.danger-text { color: @cd_danger; }--/* Sidebar */-entry.search-field, searchbar entry, entry.search-field:focus-within { background: @cd_agent; border-radius: 8px; min-height: 28px;- box-shadow: none; outline: none; border: none; font-size: 13px; padding: 0 9px; }-entry.search-field image { color: @cd_secondary; }-list.roster { background: transparent; }-list.roster > row { border-radius: 10px; padding: 6px 8px; margin-bottom: 2px; background: transparent;- transition: background 120ms; outline: none; }-list.roster > row:hover { background: @cd_agent; }-list.roster > row:selected, list.roster > row:selected:hover { background: @cd_user; color: @cd_text; }-.badge { background: @cd_accent; color: @cd_on_accent; border-radius: 999px; padding: 0 6px; min-width: 6px;- min-height: 18px; font-weight: bold; font-size: 10px; }-button.footer-row { border-radius: 10px; padding: 0 8px; min-height: 38px; background: transparent; box-shadow: none;- border: none; font-size: 13px; font-weight: 500; color: @cd_text; transition: background 120ms; }-button.footer-row:hover, button.footer-row:checked { background: @cd_agent; }-.person-circle { background: @cd_user; border-radius: 999px; color: @cd_secondary; }--/* Menus: a floating panel of rows (DesktopActionMenu / SidebarAccountPanel). */-popover.panel > contents { background: @cd_panel; border-radius: 18px; padding: 7px; box-shadow: 0 8px 20px rgba(0,0,0,0.25); }-popover.panel > arrow { background: transparent; border: none; }-button.menu-row { min-height: 30px; padding: 0 10px; border-radius: 10px; background: transparent; box-shadow: none;- border: none; font-size: 12px; font-weight: normal; color: @cd_text; }-button.menu-row:hover, button.menu-row:focus-visible { background: alpha(@cd_text, 0.08); }-button.menu-row.danger-text { color: @cd_danger; }-.menu-divider { background: alpha(@cd_text, 0.13); min-height: 1px; margin: 5px 10px; }--/* Conversation */-.bubble { border-radius: 22px; padding: 8px 12px; font-size: 12px; color: @cd_text; }-.bubble-user { background: @cd_user; }-.bubble-agent { background: @cd_agent; }-.time { font-size: 10px; color: @cd_tertiary; }-.author { font-size: 11px; font-weight: 500; }-button.thread-chip { border-radius: 999px; padding: 5px 10px; background: @cd_surface; box-shadow: none; border: none;- min-height: 0; transition: background 120ms; }-button.thread-chip:hover { background: @cd_agent; }-button.mention-chip { border-radius: 999px; padding: 6px 10px; background: @cd_surface; box-shadow: none; border: none; min-height: 0; }-button.working { background: @cd_agent; border-radius: 22px; padding: 12px; box-shadow: none; border: none; min-height: 0; }-.perm-card { background: @cd_agent; border-radius: 22px; padding: 16px; }-.choices { background: @cd_bg; border-radius: 14px; }-button.choice { min-height: 46px; padding: 0 14px; border-radius: 0; background: transparent; box-shadow: none; border: none;- font-size: 13px; }-button.choice:first-child { border-radius: 14px 14px 0 0; }-button.choice:last-child { border-radius: 0 0 14px 14px; }-button.choice:hover { background: alpha(@cd_text, 0.05); }-.codebox { font-family: monospace; font-size: 10px; background: @cd_code; border-radius: 8px; padding: 8px; }-.notice-error { background: alpha(@cd_danger, 0.12); border-radius: 12px; padding: 12px; }-.composer { background: @cd_user; border-radius: 24px; padding: 4px 6px 4px 14px; box-shadow: 0 2px 10px rgba(0,0,0,0.06); }-.composer textview, .composer textview text, .composer scrolledwindow { background: transparent; font-size: 12px; }-button.send { min-width: 28px; min-height: 28px; padding: 0; border-radius: 999px; background: @cd_accent;- color: @cd_on_accent; box-shadow: none; border: none; }-button.send:disabled { background: @cd_accent_dim; color: @cd_tertiary; }-.reply-btn { opacity: 0; transition: opacity 150ms ease-out; }-.reply-host:hover .reply-btn, .reply-btn:focus-visible { opacity: 1; }-.details-box { background: @cd_surface; border-radius: 8px; }--/* Compose page and editors */-floating-sheet > sheet, dialog.floating sheet, dialog sheet { outline: none; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.45); border-radius: 18px; }-entry.plain, entry.plain:focus-within { background: transparent; box-shadow: none; outline: none; border: none; padding: 0; min-height: 0; }-.file-card { background: @cd_user; border-radius: 14px; padding: 8px 12px; }-.chip { background: @cd_agent; border-radius: 999px; padding: 3px 4px 3px 8px; }-button.chip-x { min-width: 18px; min-height: 18px; padding: 0; background: transparent; box-shadow: none; border: none; color: @cd_secondary; }-.pick-card { background: @cd_surface; border-radius: 18px; padding: 8px; box-shadow: 0 6px 16px rgba(0,0,0,0.08); }-button.pick-row { padding: 8px 12px; border-radius: 12px; background: transparent; box-shadow: none; border: none;- font-weight: normal; font-size: 13px; transition: background 120ms; }-button.pick-row:hover, button.pick-row.first { background: @cd_agent; }-.keycap { font-family: monospace; font-size: 10px; color: @cd_secondary; background: @cd_bg; border-radius: 4px;- min-width: 18px; min-height: 18px; padding: 0 3px; }-.plus-circle { background: @cd_agent; border-radius: 999px; }-.field-label { font-size: 11px; color: @cd_secondary; margin-left: 4px; }-entry.field-box, entry.field-box:focus-within { background: @cd_surface; border-radius: 12px; padding: 0 10px; min-height: 32px;- box-shadow: none; outline: none; border: none; }-.field-box-area { background: @cd_surface; border-radius: 12px; padding: 8px 10px; }-.field-box-area textview, .field-box-area textview text { background: transparent; }-button.candidate { padding: 8px 12px; border-radius: 12px; background: transparent; box-shadow: none; border: none;- font-weight: normal; transition: background 120ms; }-button.candidate:hover { background: @cd_agent; }-"#;--fn main() -> gtk::glib::ExitCode {- let app = adw::Application::builder()- .application_id("com.pokai.Codync")- .build();- app.connect_startup(|_| {- let display = gtk::gdk::Display::default().expect("no display");- let base = gtk::CssProvider::new();- base.load_from_string(CSS);- let palette = gtk::CssProvider::new();- let style = adw::StyleManager::default();- // Black and white like the Apple apps: follow the system, default dark.- style.set_color_scheme(adw::ColorScheme::PreferDark);- let apply = {- let palette = palette.clone();- move |s: &adw::StyleManager| {- palette.load_from_string(&colors(if s.is_dark() { &DARK } else { &LIGHT }));- }- };- apply(&style);- style.connect_dark_notify(apply);- // The palette's named colors must exist before the rules that use them.- gtk::style_context_add_provider_for_display(- &display,- &palette,- gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,- );- gtk::style_context_add_provider_for_display(- &display,- &base,- gtk::STYLE_PROVIDER_PRIORITY_APPLICATION + 1,- );- });- app.connect_activate(|app| {- if let Some(win) = app.active_window() {- win.present();- return;- }- ui::build(app);- });- // Our own flags (`--bot <id>`) are read in ui::connect; keep GTK from rejecting them.- app.run_with_args(&std::env::args().take(1).collect::<Vec<_>>())-}diff --git a/apps/linux/src/manage.rs b/apps/linux/src/manage.rsdeleted file mode 100644index 88f536f6..00000000--- a/apps/linux/src/manage.rs+++ /dev/null@@ -1,683 +0,0 @@-//! Memory and routines use the same host-owned state and schedule validation as SwiftUI.-use crate::{- client,- rows::{icon_button, label},- ui::{self, App, toast},-};-use adw::prelude::*;-use serde_json::{Value, json};-use std::{cell::RefCell, rc::Rc};--pub fn dialog(ui: &App, title: &str) -> (adw::Dialog, gtk::Box) {- let body = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(14)- .margin_top(20)- .margin_bottom(20)- .margin_start(20)- .margin_end(20)- .build();- let scroll = gtk::ScrolledWindow::builder()- .child(&body)- .vexpand(true)- .build();- let view = adw::ToolbarView::new();- view.add_top_bar(&adw::HeaderBar::new());- view.set_content(Some(&scroll));- let dialog = adw::Dialog::builder()- .title(title)- .content_width(620)- .content_height(650)- .child(&view)- .build();- dialog.present(Some(&ui.window));- (dialog, body)-}--pub fn memory(ui: &App, bot: &str) {- let (_, body) = dialog(ui, "Memory");- let refresh = icon_button("view-refresh-symbolic", "Refresh memory");- body.append(&refresh);- let list = gtk::Box::new(gtk::Orientation::Vertical, 12);- body.append(&list);- let (ui2, bot2, list2) = (ui.clone(), bot.to_owned(), list.clone());- refresh.connect_clicked(move |_| load_memory(&ui2, &bot2, &list2));- load_memory(ui, bot, &list);-}--fn load_memory(ui: &App, bot: &str, list: >k::Box) {- ui::clear(list);- list.append(&label("Loading…", &["secondary"]));- let (ui, bot, list) = (ui.clone(), bot.to_owned(), list.clone());- client::call("memory", json!({"botId":bot}), move |r| {- ui::clear(&list);- let v = match r {- Ok(v) => v,- Err(e) => {- list.append(&label(&e, &["danger-text"]));- return;- }- };- let facts = v["facts"].as_array().cloned().unwrap_or_default();- if facts.is_empty() {- list.append(&label(- "Nothing yet. The bot remembers as you chat.",- &["secondary"],- ));- }- for fact in &facts {- let row = gtk::Box::new(gtk::Orientation::Horizontal, 10);- let text = label(fact["content"].as_str().unwrap_or(""), &[]);- text.set_wrap(true);- text.set_hexpand(true);- text.set_selectable(true);- row.append(&text);- let remove = icon_button("edit-delete-symbolic", "Forget");- row.append(&remove);- list.append(&row);- let (ui, bot, list, id) = (ui.clone(), bot.clone(), list.clone(), fact["id"].clone());- remove.connect_clicked(move |button| {- button.set_sensitive(false);- let (ui, bot, list) = (ui.clone(), bot.clone(), list.clone());- client::call("forgetMemory", json!({"botId":bot,"id":id}), move |r| {- if let Err(e) = r {- toast(&ui, &e);- }- load_memory(&ui, &bot, &list);- });- });- }- if !facts.is_empty() {- let clear = gtk::Button::with_label("Forget everything");- list.append(&clear);- let (ui, bot, list) = (ui.clone(), bot.clone(), list.clone());- clear.connect_clicked(move |_| {- let (ui2, bot, list) = (ui.clone(), bot.clone(), list.clone());- crate::dialogs::confirm(- &ui,- "Forget everything?",- "All remembered facts will be removed. Your chat stays.",- "Forget everything",- true,- move || {- client::call("clearMemory", json!({"botId":bot}), move |r| {- if let Err(e) = r {- toast(&ui2, &e);- }- load_memory(&ui2, &bot, &list);- });- },- );- });- }- });-}--pub fn routines(ui: &App, bot: &str) {- let (window, body) = dialog(ui, "Routines");- let actions = gtk::Box::new(gtk::Orientation::Horizontal, 8);- let add = icon_button("list-add-symbolic", "Set up a routine");- let ask = icon_button("chat-message-new-symbolic", "Ask the bot for a routine");- let refresh = icon_button("view-refresh-symbolic", "Refresh routines");- actions.append(&add);- actions.append(&ask);- actions.append(&refresh);- body.append(&actions);- let list = gtk::Box::new(gtk::Orientation::Vertical, 14);- body.append(&list);- let (ui2, bot2, list2) = (ui.clone(), bot.to_owned(), list.clone());- add.connect_clicked(move |_| routine_editor(&ui2, &bot2, Value::Null, &list2));- // Or ask the bot to set one up: start the ask in its chat.- let ui2 = ui.clone();- ask.connect_clicked(move |_| {- window.close();- ui::insert_draft(&ui2, "I want a routine that ");- });- let (ui2, bot2, list2) = (ui.clone(), bot.to_owned(), list.clone());- refresh.connect_clicked(move |_| load_routines(&ui2, &bot2, &list2));- load_routines(ui, bot, &list);-}--fn load_routines(ui: &App, bot: &str, list: >k::Box) {- ui::clear(list);- list.append(&label("Loading…", &["secondary"]));- let (ui, bot, list) = (ui.clone(), bot.to_owned(), list.clone());- client::call("routines", json!({"botId":bot}), move |r| {- ui::clear(&list);- let v = match r {- Ok(v) => v,- Err(e) => {- list.append(&label(&e, &["danger-text"]));- return;- }- };- let items = v["routines"].as_array().cloned().unwrap_or_default();- if items.is_empty() {- let empty = label(- "No routines yet. Ask the bot for one, or set it up yourself with +.",- &["secondary"],- );- empty.set_wrap(true);- list.append(&empty);- return;- }- let rows = gtk::ListBox::builder()- .selection_mode(gtk::SelectionMode::None)- .css_classes(["boxed-list"])- .build();- list.append(&rows);- for item in items {- let active = v["runs"].as_array().into_iter().flatten().find(|run| {- run["routineId"] == item["id"]- && matches!(- run["status"].as_str(),- Some("pending" | "starting" | "running" | "recovering")- )- });- // What's happening now, else when it runs.- let summary = if let Some(run) = active {- run_label(run["status"].as_str().unwrap_or(""))- } else if item["lastError"].is_string() {- "Schedule needs attention".to_owned()- } else {- item["triggerDescriptions"]- .as_array()- .into_iter()- .flatten()- .filter_map(Value::as_str)- .collect::<Vec<_>>()- .join(" · ")- };- let row = adw::ActionRow::builder()- .title(item["name"].as_str().unwrap_or("Routine"))- .subtitle(summary)- .tooltip_text(item["instruction"].as_str().unwrap_or(""))- .build();- rows.append(&row);- // A row opens the same form as a new routine, filled in.- row.set_activatable(true);- let (ui2, bot2, item2, list2) = (ui.clone(), bot.clone(), item.clone(), list.clone());- row.connect_activated(move |_| routine_editor(&ui2, &bot2, item2.clone(), &list2));- for (icon, title, method) in [- ("media-playback-start-symbolic", "Test run", "runRoutine"),- ("user-trash-symbolic", "Delete routine", "deleteRoutine"),- ] {- let button = icon_button(icon, title);- button.set_valign(gtk::Align::Center);- button.set_sensitive(method != "runRoutine" || active.is_none());- row.add_suffix(&button);- let (ui, bot, item, list) = (ui.clone(), bot.clone(), item.clone(), list.clone());- button.connect_clicked(move |_| {- let (ui2, bot, list, id) =- (ui.clone(), bot.clone(), list.clone(), item["id"].clone());- let run = move || {- routine_call(&ui2, method, json!({"botId":bot,"id":id}), &bot, &list)- };- if method == "deleteRoutine" {- crate::dialogs::confirm(- &ui,- "Delete routine?",- "This stops future runs. Past messages stay.",- "Delete",- true,- run,- );- } else {- run();- }- });- }- let on = gtk::Switch::builder()- .active(item["enabled"] == true)- .valign(gtk::Align::Center)- .tooltip_text(if item["enabled"] == true {- "Pause"- } else {- "Resume"- })- .build();- row.add_suffix(&on);- let (ui, bot, id, list) = (ui.clone(), bot.clone(), item["id"].clone(), list.clone());- on.connect_state_set(move |_, enabled| {- routine_call(- &ui,- "setRoutineEnabled",- json!({"botId":bot,"id":id,"enabled":enabled}),- &bot,- &list,- );- gtk::glib::Propagation::Proceed- });- }- });-}--fn routine_call(ui: &App, method: &str, args: Value, bot: &str, list: >k::Box) {- let (ui, bot, list) = (ui.clone(), bot.to_owned(), list.clone());- client::call(method, args, move |r| {- if let Err(e) = r {- toast(&ui, &e);- }- load_routines(&ui, &bot, &list);- });-}--fn run_label(status: &str) -> String {- match status {- "pending" => "Queued",- "starting" => "Starting",- "running" => "Running",- _ => "Resuming after restart",- }- .to_owned()-}--fn schedule_time(at: i64) -> String {- gtk::glib::DateTime::from_unix_local(at / 1000)- .ok()- .and_then(|date| date.format("%b %e, %Y · %H:%M %Z").ok())- .map(|s| s.to_string())- .unwrap_or_default()-}--fn entry(body: >k::Box, title: &str, value: &str) -> gtk::Entry {- let group = gtk::Box::new(gtk::Orientation::Vertical, 6);- group.append(&label(title, &["secondary"]));- let field = gtk::Entry::builder().text(value).build();- group.append(&field);- body.append(&group);- field-}--fn routine_editor(ui: &App, bot: &str, routine: Value, list: >k::Box) {- let (window, body) = dialog(- ui,- if routine.is_null() {- "Set up a routine"- } else {- "Edit routine"- },- );- let name = entry(&body, "Name", routine["name"].as_str().unwrap_or(""));- body.append(&label("Instruction", &["secondary"]));- let instruction = gtk::TextView::builder()- .wrap_mode(gtk::WrapMode::WordChar)- .height_request(100)- .build();- instruction- .buffer()- .set_text(routine["instruction"].as_str().unwrap_or(""));- let scroll = gtk::ScrolledWindow::builder()- .child(&instruction)- .hscrollbar_policy(gtk::PolicyType::Never)- .min_content_height(80)- .max_content_height(120)- .propagate_natural_height(true)- .vexpand(false)- .build();- body.append(&scroll);- // Schedule or webhook, as in Claude Code routines. Anything else the bot set up- // (a one-off time, an interval, events, several triggers) stays until replaced.- let triggers = routine["triggers"].as_array().cloned().unwrap_or_default();- let mut kinds = vec!["cron", "webhook"];- let keeps = match triggers.as_slice() {- [] => false,- [t] => !matches!(t["type"].as_str(), Some("cron" | "webhook")),- _ => true,- };- if keeps {- kinds.insert(0, "keep");- } else if triggers.first().is_some_and(|t| t["type"] == "webhook") {- kinds.reverse();- }- let current = routine["triggerDescriptions"]- .as_array()- .into_iter()- .flatten()- .filter_map(Value::as_str)- .collect::<Vec<_>>()- .join(" · ");- body.append(&label("When to run", &["secondary"]));- let labels: Vec<&str> = kinds- .iter()- .map(|k| match *k {- "keep" => current.as_str(),- "cron" => "Schedule",- _ => "Webhook",- })- .collect();- let kind = gtk::DropDown::from_strings(&labels);- body.append(&kind);- // An existing cron trigger fills the fields, so switching to Cron edits it.- let cron = routine["triggers"]- .as_array()- .into_iter()- .flatten()- .find(|t| t["type"] == "cron");- let expression = entry(- &body,- "Cron (minute hour day month weekday)",- cron.and_then(|t| t["expression"].as_str())- .unwrap_or("0 9 * * *"),- );- let local_zone = gtk::glib::TimeZone::local().identifier().to_string();- let zone = entry(- &body,- "Time zone",- cron.and_then(|t| t["timeZone"].as_str())- .unwrap_or(&local_zone),- );- let existing = label(- "Set up by the bot. Pick Schedule or Webhook to replace it.",- &["secondary"],- );- existing.set_wrap(true);- body.append(&existing);- let saved_hook = triggers- .iter()- .any(|t| matches!(t["type"].as_str(), Some("webhook" | "event")));- let hook = if saved_hook {- webhook_panel(ui, bot, routine["id"].as_str().unwrap_or_default())- } else {- let note = label(- "Runs each time something is posted to its URL. Save to get the URL and key.",- &["secondary"],- );- note.set_wrap(true);- note.upcast()- };- body.append(&hook);- let update_fields = {- let (kinds, zone, expression, existing, hook) = (- kinds.clone(),- zone.clone(),- expression.clone(),- existing.clone(),- hook.clone(),- );- move |kind: >k::DropDown| {- let style = kinds[kind.selected() as usize];- for (field, visible) in [(&expression, style == "cron"), (&zone, style == "cron")] {- if let Some(group) = field.parent() {- group.set_visible(visible);- }- }- existing.set_visible(style == "keep");- hook.set_visible(style == "webhook");- }- };- update_fields(&kind);- kind.connect_selected_notify(update_fields);- let timeout = entry(- &body,- "Run timeout (seconds)",- &routine["timeoutSeconds"]- .as_i64()- .unwrap_or(3600)- .to_string(),- );- let status = label("", &["secondary"]);- status.set_wrap(true);- body.append(&status);- let actions = gtk::Box::builder()- .orientation(gtk::Orientation::Horizontal)- .spacing(8)- .margin_top(12)- .margin_bottom(12)- .margin_start(20)- .margin_end(20)- .build();- if let Some(view) = window- .child()- .and_then(|w| w.downcast::<adw::ToolbarView>().ok())- {- view.add_bottom_bar(&actions);- }- for (title, save) in [("Preview schedule", false), ("Save", true)] {- let button = gtk::Button::with_label(title);- actions.append(&button);- let (- ui,- bot,- routine,- list,- window,- name,- instruction,- kind,- kinds,- zone,- expression,- timeout,- status,- ) = (- ui.clone(),- bot.to_owned(),- routine.clone(),- list.clone(),- window.clone(),- name.clone(),- instruction.clone(),- kind.clone(),- kinds.clone(),- zone.clone(),- expression.clone(),- timeout.clone(),- status.clone(),- );- button.connect_clicked(move |button| {- let style = kinds[kind.selected() as usize];- let draft = schedule_draft(style, &zone.text(), &expression.text(), &routine["triggers"]);- let buffer = instruction.buffer();- let text = buffer.text(&buffer.start_iter(), &buffer.end_iter(), false).to_string();- let timeout = match timeout.text().parse::<u64>() { Ok(v) if (1..=86400).contains(&v) => v, _ => { status.set_label("Timeout must be between 1 and 86400 seconds."); return; } };- if save && (name.text().trim().is_empty() || text.trim().is_empty()) { status.set_label("Enter a name and instruction."); return; }- button.set_sensitive(false);- let mut args = json!({"draft":draft});- if save { args = json!({"botId":bot,"name":name.text().as_str(),"instruction":text,"schedule":draft,"timeoutSeconds":timeout}); if !routine.is_null() { args["id"] = routine["id"].clone(); } }- let (ui, bot, list, window, status, button, routine) = (ui.clone(), bot.clone(), list.clone(), window.clone(), status.clone(), button.clone(), routine.clone());- client::call(if save { "saveRoutine" } else { "routineSchedule" }, args, move |r| {- button.set_sensitive(true);- match r {- Ok(v) if save => {- window.close();- load_routines(&ui, &bot, &list);- // A new webhook routine reopens on its URL and key, which exist only now.- if routine.is_null() && style == "webhook" { routine_editor(&ui, &bot, v["routine"].clone(), &list); }- }- Ok(v) => status.set_label(&format!("{}{}{}", v["summary"].as_str().unwrap_or(""),- v["nextRunAt"].as_i64().map(|at| format!("\nNext: {}", schedule_time(at))).unwrap_or_default(),- v["warning"].as_str().map(|w| format!("\n{w}")).unwrap_or_default())),- Err(e) => status.set_label(&e),- }- });- });- }-}--/// A saved webhook routine's URL and key, each with a copy button; the key can be shown and-/// replaced. Same as the Apple editor's webhook panel.-fn webhook_panel(ui: &App, bot: &str, id: &str) -> gtk::Widget {- let panel = gtk::Box::new(gtk::Orientation::Vertical, 8);- let url_title = label("URL", &["secondary"]);- let url = label("Loading webhook…", &["monospace"]);- url.set_wrap(true);- url.set_wrap_mode(gtk::pango::WrapMode::Char);- url.set_selectable(true);- url.set_hexpand(true);- let copy_url = icon_button("edit-copy-symbolic", "Copy URL");- let url_row = gtk::Box::new(gtk::Orientation::Horizontal, 6);- url_row.append(&url);- url_row.append(©_url);- let key = label("", &["monospace"]);- key.set_hexpand(true);- key.set_selectable(true);- let show = icon_button("view-reveal-symbolic", "Show key");- let rotate = icon_button("view-refresh-symbolic", "Replace key");- let copy_key = icon_button("edit-copy-symbolic", "Copy key");- let key_row = gtk::Box::new(gtk::Orientation::Horizontal, 6);- for w in [- key.upcast_ref::<gtk::Widget>(),- show.upcast_ref(),- rotate.upcast_ref(),- copy_key.upcast_ref(),- ] {- key_row.append(w);- }- let note = label("", &["secondary"]);- note.set_wrap(true);- panel.append(&url_title);- panel.append(&url_row);- panel.append(&label("Key", &["secondary"]));- panel.append(&key_row);- panel.append(¬e);-- let state: Rc<RefCell<Value>> = Rc::new(RefCell::new(Value::Null));- let shown = Rc::new(std::cell::Cell::new(false));- let render = {- let (state, shown, url_title, url, key, show, note) = (- state.clone(),- shown.clone(),- url_title.clone(),- url.clone(),- key.clone(),- show.clone(),- note.clone(),- );- move || {- let v = state.borrow();- let public = v["url"].as_str();- url_title.set_label(if public.is_some() { "URL" } else { "Local URL" });- url.set_label(- public- .or_else(|| v["localUrl"].as_str())- .unwrap_or_default(),- );- let secret = v["key"].as_str().unwrap_or_default();- key.set_label(&if shown.get() {- secret.to_owned()- } else {- "•".repeat(24)- });- show.set_icon_name(if shown.get() {- "view-conceal-symbolic"- } else {- "view-reveal-symbolic"- });- show.set_tooltip_text(Some(if shown.get() { "Hide key" } else { "Show key" }));- note.set_label(if public.is_some() {- "POST with Authorization: Bearer <key>. For GitHub, use content type application/json and the key as the secret. Deliveries wait up to 72 hours while this computer is off. They pass through the Codync cloud, which can read them."- } else {- "The Codync cloud is off, so only this computer can send to it."- });- }- };- let load = {- let (ui, bot, id, state, shown, render, note) = (- ui.clone(),- bot.to_owned(),- id.to_owned(),- state.clone(),- shown.clone(),- render.clone(),- note.clone(),- );- Rc::new(move |rotate: bool| {- let (ui, state, shown, render, note) = (- ui.clone(),- state.clone(),- shown.clone(),- render.clone(),- note.clone(),- );- client::call(- "routineWebhook",- json!({"botId": bot, "id": id, "rotate": rotate}),- move |r| match r {- Ok(v) => {- *state.borrow_mut() = v;- if rotate {- shown.set(true);- toast(&ui, "Key replaced");- }- render();- }- Err(e) => note.set_label(&e),- },- );- })- };- load(false);- {- let (shown, render) = (shown.clone(), render.clone());- show.connect_clicked(move |_| {- shown.set(!shown.get());- render();- });- }- {- let (ui, load) = (ui.clone(), load.clone());- rotate.connect_clicked(move |_| {- let load = load.clone();- crate::dialogs::confirm(- &ui,- "Replace the key?",- "Senders using the current key stop working until they get the new one.",- "Replace key",- true,- move || load(true),- );- });- }- for (button, field) in [(©_url, "url"), (©_key, "key")] {- let (ui, state) = (ui.clone(), state.clone());- button.connect_clicked(move |b| {- let v = state.borrow();- let text = match field {- "key" => v["key"].as_str(),- _ => v["url"].as_str().or_else(|| v["localUrl"].as_str()),- };- if let Some(text) = text {- b.clipboard().set_text(text);- toast(- &ui,- if field == "key" {- "Copied the key"- } else {- "Copied the URL"- },- );- }- });- }- panel.upcast()-}--/// The form as the host's schedule draft: cron is sent as written, the host checks it.-fn schedule_draft(style: &str, zone: &str, expression: &str, original: &Value) -> Value {- let mut draft = json!({"kind":style,"zone":zone,"original":original.as_array().cloned().unwrap_or_default()});- if style == "cron" {- draft["calendarStyle"] = "custom".into();- draft["expression"] = expression.into();- }- draft-}--#[cfg(test)]-mod tests {- use super::*;- #[test]- fn edits_preserve_existing_event_triggers() {- let original = json!([{"type":"event","source":"github","event":"pull_request.opened","filters":{"repo":"a/b"}}]);- let draft = schedule_draft("keep", "Asia/Taipei", "", &original);- assert_eq!(draft["original"], original);- assert_eq!(draft["kind"], "keep");- }- #[test]- fn cron_is_sent_as_written() {- let draft = schedule_draft("cron", "Asia/Taipei", "20 14 * * 0", &Value::Null);- assert_eq!(draft["calendarStyle"], "custom");- assert_eq!(draft["expression"], "20 14 * * 0");- assert_eq!(draft["zone"], "Asia/Taipei");- }-}diff --git a/apps/linux/src/market.rs b/apps/linux/src/market.rsdeleted file mode 100644index a4f37d6b..00000000--- a/apps/linux/src/market.rs+++ /dev/null@@ -1,428 +0,0 @@-//! Agent setup and skill management alongside the connector registry.-use crate::{- client,- manage::dialog,- rows::{icon_button, label},- ui::{self, App, toast},-};-use adw::prelude::*;-use serde_json::{Value, json};-use std::{cell::RefCell, rc::Rc};-use vte::prelude::*;--pub fn open(ui: &App) {- let (_, body) = dialog(ui, "Marketplace");- let connectors = gtk::Button::with_label("Connectors");- body.append(&connectors);- let ui2 = ui.clone();- connectors.connect_clicked(move |_| crate::connections::marketplace(&ui2));- let credentials = gtk::Button::with_label("Credentials");- body.append(&credentials);- let ui2 = ui.clone();- credentials.connect_clicked(move |_| crate::connections::credentials(&ui2));- body.append(&label("Agents", &["headline"]));- let agents = gtk::Box::new(gtk::Orientation::Vertical, 8);- body.append(&agents);- let ui2 = ui.clone();- client::call("refreshBackends", json!({}), move |r| match r {- Ok(v) => {- ui2.state.borrow_mut().hello["backends"] = v["backends"].clone();- for backend in v["backends"].as_array().into_iter().flatten().filter(|b| {- b["available"] == true || b["installed"] == true || b["curated"] == true- }) {- let button = gtk::Button::with_label(backend["name"].as_str().unwrap_or("Agent"));- agents.append(&button);- let (ui, backend) = (ui2.clone(), backend.clone());- button.connect_clicked(move |_| agent(&ui, &backend));- }- }- Err(e) => agents.append(&label(&e, &["danger-text"])),- });- body.append(&label("Skills", &["headline"]));- let search = gtk::SearchEntry::new();- body.append(&search);- let list = gtk::Box::new(gtk::Orientation::Vertical, 8);- body.append(&list);- let refresh = icon_button("view-refresh-symbolic", "Refresh skills");- body.append(&refresh);- let (ui2, list2, search2) = (ui.clone(), list.clone(), search.clone());- refresh.connect_clicked(move |_| skills(&ui2, &list2, &search2.text()));- let (ui2, list2) = (ui.clone(), list.clone());- search.connect_activate(move |s| skills(&ui2, &list2, &s.text()));- skills(ui, &list, "");-}--fn skills(ui: &App, list: >k::Box, query: &str) {- ui::clear(list);- list.append(&label("Loading…", &["secondary"]));- let (ui, list, query) = (ui.clone(), list.clone(), query.to_lowercase());- client::call("skills", json!({}), move |r| {- ui::clear(&list);- let installed = match r {- Ok(v) => v["items"].as_array().cloned().unwrap_or_default(),- Err(e) => {- list.append(&label(&e, &["danger-text"]));- return;- }- };- for item in &installed {- let row = gtk::Box::new(gtk::Orientation::Horizontal, 8);- let text = label(item["name"].as_str().unwrap_or("Skill"), &[]);- text.set_hexpand(true);- row.append(&text);- let remove = icon_button("user-trash-symbolic", "Remove skill");- row.append(&remove);- list.append(&row);- let (ui, list, id, query) =- (ui.clone(), list.clone(), item["id"].clone(), query.clone());- remove.connect_clicked(move |_| {- let (ui2, list, id, query) = (ui.clone(), list.clone(), id.clone(), query.clone());- crate::dialogs::confirm(- &ui,- "Remove skill?",- "Bots will no longer have this skill.",- "Remove",- true,- move || {- client::call("removeSkill", json!({"id":id}), move |r| {- if let Err(e) = r {- toast(&ui2, &e);- }- skills(&ui2, &list, &query);- });- },- );- });- }- client::call("marketSkills", json!({}), move |r| match r {- Ok(v) => {- let items: Vec<_> = v["items"]- .as_array()- .into_iter()- .flatten()- .filter(|i| {- format!("{} {}", i["name"], i["description"])- .to_lowercase()- .contains(&query)- })- .collect();- if items.is_empty() {- list.append(&label("No matching skills", &["secondary"]));- }- for item in items {- let row = gtk::Box::new(gtk::Orientation::Horizontal, 8);- let text = label(- &format!(- "{}\n{}",- item["name"].as_str().unwrap_or("Skill"),- item["description"].as_str().unwrap_or("")- ),- &[],- );- text.set_wrap(true);- text.set_hexpand(true);- row.append(&text);- let added = item["installed"] == true- || installed- .iter()- .any(|s| s["source"] == item["source"] && s["source"].is_string());- let add = gtk::Button::with_label(if added { "Added" } else { "Add" });- add.set_sensitive(!added);- row.append(&add);- list.append(&row);- let (ui, list, source, query) = (- ui.clone(),- list.clone(),- item["source"].clone(),- query.clone(),- );- add.connect_clicked(move |button| {- button.set_sensitive(false);- let (ui, list, query) = (ui.clone(), list.clone(), query.clone());- client::call("installSkill", json!({"source":source}), move |r| {- if let Err(e) = r {- toast(&ui, &e);- }- skills(&ui, &list, &query);- });- });- }- }- Err(e) => list.append(&label(&e, &["danger-text"])),- });- });-}--pub fn agent(ui: &App, backend: &Value) {- let (_, body) = dialog(ui, backend["name"].as_str().unwrap_or("Agent"));- let id = backend["id"].as_str().unwrap_or("").to_owned();- if backend["installed"] != true && backend["canInstall"] == true {- let install = gtk::Button::with_label("Install");- body.append(&install);- let (ui, id) = (ui.clone(), id.clone());- install.connect_clicked(move |_| setup(&ui, &id, "install", None));- }- let check = gtk::Button::with_label("Check sign-in");- body.append(&check);- let auth = gtk::Box::new(gtk::Orientation::Vertical, 10);- body.append(&auth);- let (ui2, id2, auth2) = (ui.clone(), id.clone(), auth.clone());- check.connect_clicked(move |_| load_auth(&ui2, &id2, &auth2));- if backend["installed"] == true || backend["available"] == true {- load_auth(ui, &id, &auth);- }-}--fn load_auth(ui: &App, id: &str, body: >k::Box) {- ui::clear(body);- body.append(&label("Checking sign-in…", &["secondary"]));- let (ui, id, body) = (ui.clone(), id.to_owned(), body.clone());- client::call("agentAuth", json!({"backend":id}), move |r| {- ui::clear(&body);- let v = match r {- Ok(v) => v,- Err(e) => {- body.append(&label(&e, &["danger-text"]));- return;- }- };- let status = label(- if v["signedIn"] == true {- "Signed in"- } else {- "Sign-in required"- },- &["headline"],- );- body.append(&status);- if let Some(detail) = v["detail"].as_str() {- let text = label(detail, &[]);- text.set_wrap(true);- body.append(&text);- }- if v["login"] == true {- let login = gtk::Button::with_label("Sign in in terminal");- body.append(&login);- let (ui, id) = (ui.clone(), id.clone());- login.connect_clicked(move |_| setup(&ui, &id, "login", None));- }- for method in v["methods"].as_array().into_iter().flatten() {- let button = gtk::Button::with_label(method["name"].as_str().unwrap_or("Sign in"));- body.append(&button);- let (ui, id, method, body) = (ui.clone(), id.clone(), method.clone(), body.clone());- button.connect_clicked(move |button| match method["kind"].as_str() {- Some("terminal") => setup(&ui, &id, "login", method["id"].as_str()),- Some("envVar") => env_fields(&ui, &id, &method, &body),- _ => {- button.set_sensitive(false);- let (ui, id, body) = (ui.clone(), id.clone(), body.clone());- client::call(- "agentAuthenticate",- json!({"backend":id,"method":method["id"]}),- move |r| {- if let Err(e) = r {- toast(&ui, &e);- }- load_auth(&ui, &id, &body);- },- );- }- });- }- });-}--fn env_fields(ui: &App, id: &str, method: &Value, auth: >k::Box) {- let (window, body) = dialog(ui, "Sign in with credentials");- let mut fields = vec![];- for var in method["vars"].as_array().into_iter().flatten() {- body.append(&label(- var["label"].as_str().unwrap_or("Credential"),- &["secondary"],- ));- let entry = gtk::Entry::builder()- .visibility(var["secret"] == false)- .build();- body.append(&entry);- fields.push((- var["name"].as_str().unwrap_or("").to_owned(),- var["optional"] != true,- entry,- ));- }- let error = label("", &["danger-text"]);- body.append(&error);- let save = gtk::Button::with_label("Save and sign in");- body.append(&save);- let (ui, id, auth) = (ui.clone(), id.to_owned(), auth.clone());- save.connect_clicked(move |button| {- if fields- .iter()- .any(|(_, required, e)| *required && e.text().is_empty())- {- error.set_label("Fill in the required credentials.");- return;- }- let vars: serde_json::Map<String, Value> = fields- .iter()- .filter(|(_, _, e)| !e.text().is_empty())- .map(|(k, _, e)| (k.clone(), e.text().to_string().into()))- .collect();- button.set_sensitive(false);- let (ui, id, auth, window, fields, error, button) = (- ui.clone(),- id.clone(),- auth.clone(),- window.clone(),- fields.clone(),- error.clone(),- button.clone(),- );- client::call("setAgentEnv", json!({"backend":id,"vars":vars}), move |r| {- button.set_sensitive(true);- match r {- Ok(_) => {- for (_, _, e) in fields {- e.set_text("");- }- window.close();- load_auth(&ui, &id, &auth);- }- Err(e) => error.set_label(&e),- }- });- });-}--fn setup(ui: &App, backend: &str, step: &str, method: Option<&str>) {- let (window, body) = dialog(- ui,- if step == "install" {- "Install agent"- } else {- "Sign in"- },- );- window.set_content_width(900);- window.set_content_height(650);- let terminal = vte::Terminal::new();- terminal.set_vexpand(true);- terminal.set_hexpand(true);- terminal.set_size(90, 28);- terminal.set_input_enabled(false);- terminal.set_allow_hyperlink(true);- // Only a user gesture opens URLs printed by the agent.- const PCRE2_MULTILINE: u32 = 0x0000_0400;- if let Ok(regex) = vte::Regex::for_match(r#"https?://[^\s<>\"']+"#, PCRE2_MULTILINE) {- terminal.match_add_regex(®ex, 0);- }- let click = gtk::GestureClick::new();- let terminal_link = terminal.downgrade();- click.connect_pressed(move |gesture, _, x, y| {- if !gesture- .current_event_state()- .contains(gtk::gdk::ModifierType::CONTROL_MASK)- {- return;- }- if let Some(terminal) = terminal_link.upgrade()- && let Some(url) = terminal- .check_hyperlink_at(x, y)- .or_else(|| terminal.check_match_at(x, y).0)- && (url.starts_with("https://") || url.starts_with("http://"))- {- let _ = gtk::gio::AppInfo::launch_default_for_uri(- &url,- None::<>k::gio::AppLaunchContext>,- );- }- });- terminal.add_controller(click);- body.append(&terminal);- let status = label("Starting…", &["secondary"]);- body.append(&status);- let state = Rc::new(RefCell::new(- None::<(- String,- async_channel::Sender<Vec<u8>>,- tokio::task::AbortHandle,- )>,- ));- let closed = Rc::new(std::cell::Cell::new(false));- let state2 = state.clone();- let closed2 = closed.clone();- window.connect_closed(move |_| {- closed2.set(true);- if let Some((id, keys, output)) = state2.borrow_mut().take() {- keys.close();- output.abort();- client::call("termClose", json!({"term":id}), |_| {});- }- });- let state2 = state.clone();- terminal.connect_commit(move |_, text, _| {- if let Some((_, keys, _)) = &*state2.borrow() {- let _ = keys.try_send(text.as_bytes().to_vec());- }- });- let state2 = state.clone();- let last_size = RefCell::new((0, 0));- terminal.add_tick_callback(move |t, _| {- if let Some((id, _, _)) = &*state2.borrow() {- let size = (t.column_count(), t.row_count());- if *last_size.borrow() != size {- *last_size.borrow_mut() = size;- client::call(- "termResize",- json!({"term":id,"cols":size.0,"rows":size.1}),- |_| {},- );- }- }- gtk::glib::ControlFlow::Continue- });- let args = json!({"backend":backend,"step":step,"method":method,"cols":90,"rows":28});- client::call("agentSetup", args, move |r| {- let id = match r {- Ok(v) => v["term"].as_str().unwrap_or("").to_owned(),- Err(e) => {- status.set_label(&e);- return;- }- };- if closed.get() {- client::call("termClose", json!({"term":id}), |_| {});- return;- }- let (tx, rx) = async_channel::unbounded();- let (keys, output) = client::terminal(id.clone(), tx);- *state.borrow_mut() = Some((id, keys, output));- terminal.set_input_enabled(true);- terminal.grab_focus();- status.set_label("Running on your computer · Ctrl+click opens a link");- gtk::glib::spawn_future_local(async move {- while let Ok(event) = rx.recv().await {- match event {- Ok(v) if v["type"] == "output" => {- terminal.feed(>k::glib::base64_decode(v["data"].as_str().unwrap_or("")))- }- Ok(v) if v["type"] == "exit" => {- terminal.set_input_enabled(false);- status.set_label(if v["code"] == 0 {- "Finished"- } else {- "Ended with an error"- });- break;- }- Ok(_) => {}- Err(e) => {- terminal.set_input_enabled(false);- status.set_label(&e);- break;- }- }- }- });- });-}diff --git a/apps/linux/src/markup.rs b/apps/linux/src/markup.rsdeleted file mode 100644index 1c3f246b..00000000--- a/apps/linux/src/markup.rs+++ /dev/null@@ -1,97 +0,0 @@-//! Markdown → Pango markup (the subset agents actually send).--use gtk::glib::markup_escape_text;--fn inline(line: &str) -> String {- let escaped = markup_escape_text(line).to_string();- let mut out = String::new();- let mut code = false;- for (i, part) in escaped.split('`').enumerate() {- if i > 0 {- code = !code;- }- if code {- out.push_str(&format!("<tt>{part}</tt>"));- } else {- out.push_str(&emphasis(part));- }- }- out-}--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))- }- }- out-}--fn links(s: &str) -> String {- // [text](http…) → <a>- 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 url = &rest[close + 2..end];- if !url.starts_with("http") {- break;- }- out.push_str(&rest[..open]);- out.push_str(&format!("<a href=\"{url}\">{}</a>", &rest[open + 1..close]));- rest = &rest[end + 1..];- }- out.push_str(rest);- out-}--pub fn to_pango(src: &str) -> String {- let mut out = Vec::new();- let mut in_code = false;- for line in src.lines() {- let t = line.trim_start();- if t.starts_with("```") {- in_code = !in_code;- continue;- }- 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("# "))- {- 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)));- } else {- out.push(inline(line));- }- }- out.join("\n")-}--#[cfg(test)]-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>"- );- }-}diff --git a/apps/linux/src/orb.rs b/apps/linux/src/orb.rsdeleted file mode 100644index 19be9f56..00000000--- a/apps/linux/src/orb.rs+++ /dev/null@@ -1,164 +0,0 @@-//! `ThinkingOrb` from the Apple apps (CodyncKit/Design/ThinkingOrbGeometry.swift, a port of-//! thinking-orbs 0.3.1, MIT, Jakub Antalik): the *working* orbits and the *listening* lattice.-//! Drawn in the widget's CSS color, so a `warning-text` / `secondary` class tints it.--use gtk::prelude::*;-use std::f64::consts::PI;--struct Dot {- x: f64,- y: f64,- z: f64,- radius: f64,- white: f64,- alpha: f64,-}--fn hash(a: f64, b: f64) -> f64 {- let h = (a * 12.9898 + b * 78.233).sin() * 43758.5453;- h - h.floor()-}--type P = (f64, f64, f64);--fn projector(yaw: f64, tilt: f64, size: f64, scale: f64) -> impl Fn(P) -> P {- let (sy, cy, st, ct) = (yaw.sin(), yaw.cos(), tilt.sin(), tilt.cos());- move |(px, py, pz)| {- let x = px * cy + pz * sy;- let z = -px * sy + pz * cy;- (- size / 2.0 + x * scale,- size / 2.0 - (py * ct - z * st) * scale,- py * st + z * ct,- )- }-}--fn orbits(size: f64, t: f64) -> Vec<Dot> {- let small = size < 40.0;- let radius = size / 2.0 * 0.82;- let project = projector(t * 0.12, 0.3, size, 1.0);- let rs = (size / 300.0).powf(0.6);- let multiplier = if small { 2.4 } else { 1.0 };- let (orbit_count, ghost_count) = if small { (3, 10) } else { (12, 40) };- let mut dots = vec![];- for orb in 0..orbit_count {- let o = f64::from(orb);- let (h1, h2, h3) = (hash(o, 1.7), hash(o, 5.2), hash(o, 8.9));- let ro = radius * (0.45 + 0.52 * h1);- let (theta, phi) = (h1 * 2.0 * PI, (2.0 * h2 - 1.0).acos());- let n = (phi.sin() * theta.cos(), phi.cos(), phi.sin() * theta.sin());- let mut u = (-n.1, n.0, 0.0);- let len = (u.0 * u.0 + u.1 * u.1).sqrt().max(1e-6);- u = (u.0 / len, u.1 / len, 0.0);- let v = (-n.2 * u.1, n.2 * u.0, n.0 * u.1 - n.1 * u.0);- let speed = (0.25 + 0.55 * h3) * if h3 > 0.5 { 1.0 } else { -1.0 };- let at = |angle: f64| {- project((- (u.0 * angle.cos() + v.0 * angle.sin()) * ro,- (u.1 * angle.cos() + v.1 * angle.sin()) * ro,- (u.2 * angle.cos() + v.2 * angle.sin()) * ro,- ))- };- for k in 0..ghost_count {- let p = at(f64::from(k) / f64::from(ghost_count) * 2.0 * PI);- let depth = (p.2 / ro + 1.0) / 2.0;- dots.push(Dot {- x: p.0,- y: p.1,- z: p.2,- radius: 0.9 * multiplier * rs,- white: 0.72,- alpha: 0.5 * (0.4 + 0.6 * depth),- });- }- for m in 0..3 {- let p = at(t * speed + f64::from(m) / 3.0 * 2.0 * PI + h2 * 6.0);- let depth = (p.2 / ro + 1.0) / 2.0;- dots.push(Dot {- x: p.0,- y: p.1,- z: p.2,- radius: (1.2 + 1.6 * depth) * multiplier * rs,- white: 0.3 - 0.22 * depth,- alpha: 1.0,- });- }- }- dots-}--fn listening(size: f64, t: f64) -> Vec<Dot> {- let small = size < 40.0;- let rs = (size / 300.0).powf(0.6);- let rings = if small { 5 } else { 9 };- let density = if small { 13.0 } else { 23.0 };- let multiplier = if small { 1.6 } else { 1.0 };- let radius = size / 2.0 * 0.874;- let project = projector(t * 0.18, 0.38, size, 1.0);- let mut dots = vec![];- for ri in 0..=rings {- let r = f64::from(ri);- let lat = -PI / 2.0 + r / f64::from(rings) * PI;- let wave = 0.62 * (t * 2.1 - r * 0.52).sin() + 0.38 * (t * 1.27 + r * 0.83).sin();- let rr = radius * (0.88 + 0.105 * wave);- let lon_count = ((lat.cos().abs() * density).round() as i32).max(1);- for j in 0..lon_count {- let lon = f64::from(j) / f64::from(lon_count) * 2.0 * PI;- let p = project((- lat.cos() * lon.cos() * rr,- lat.sin() * rr,- lat.cos() * lon.sin() * rr,- ));- let depth = (p.2 / radius + 1.0) / 2.0;- let crest = wave.max(0.0);- dots.push(Dot {- x: p.0,- y: p.1,- z: p.2,- radius: (0.6 + 1.7 * depth) * multiplier * (1.0 + 0.4 * crest) * rs,- white: 0.66 - 0.56 * depth - 0.1 * crest,- alpha: 1.0,- });- }- }- dots-}--/// A turning orb; `listening` is the "needs you" state.-pub fn widget(listening_state: bool, size: i32) -> gtk::DrawingArea {- let area = gtk::DrawingArea::builder()- .content_width(size)- .content_height(size)- .valign(gtk::Align::Center)- .build();- let start = std::time::Instant::now();- area.set_draw_func(move |area, cr, w, _| {- let s = f64::from(w);- let c = area.color();- let speed = if listening_state { 3.998 } else { 3.9 };- let t = 0.6 + start.elapsed().as_secs_f64() * speed;- let mut dots = if listening_state {- listening(s, t)- } else {- orbits(s, t)- };- dots.sort_by(|a, b| a.z.total_cmp(&b.z));- for d in dots.iter().filter(|d| d.alpha >= 0.02) {- let ink = (1.0 - d.white.clamp(0.0, 1.0)) * d.alpha;- cr.set_source_rgba(- f64::from(c.red()),- f64::from(c.green()),- f64::from(c.blue()),- ink,- );- cr.arc(d.x, d.y, d.radius.max(0.3), 0.0, 2.0 * PI);- cr.fill().ok();- }- });- area.add_tick_callback(|a, _| {- a.queue_draw();- gtk::glib::ControlFlow::Continue- });- area-}diff --git a/apps/linux/src/rows.rs b/apps/linux/src/rows.rsdeleted file mode 100644index a84d9ad6..00000000--- a/apps/linux/src/rows.rs+++ /dev/null@@ -1,850 +0,0 @@-//! The rows a conversation is made of (kit/Sources/CodyncUI/Thread/ChatRows.swift and-//! PermissionCard.swift): bubbles, author labels, thread chips, notices, approval cards and-//! the working indicator.--use crate::client;-use crate::ui::{self, App, State, folder_name, toast};-use crate::{avatar, markup, orb};-use adw::prelude::*;-use gtk::glib::DateTime;-use serde_json::{Value, json};--// MARK: time--fn local(ms: i64) -> Option<DateTime> {- DateTime::from_unix_local(ms / 1000).ok()-}--fn fmt(d: &DateTime, f: &str) -> String {- d.format(f)- .map(|s| s.trim().replace(" ", " "))- .unwrap_or_default()-}--/// Days between the date and today (0 = today).-fn days_ago(d: &DateTime) -> i32 {- let Ok(now) = DateTime::now_local() else {- return 0;- };- let day = |x: &DateTime| {- DateTime::from_local(x.year(), x.month(), x.day_of_month(), 0, 0, 0.0)- .map(|d| d.to_unix())- .unwrap_or(0)- };- i32::try_from((day(&now) - day(d)) / 86_400).unwrap_or(i32::MAX)-}--/// 3:27 PM-pub fn clock(ms: i64) -> String {- local(ms).map(|d| fmt(&d, "%l:%M %p")).unwrap_or_default()-}--/// Roster/thread stamp: 3:45 AM · Yesterday · Wednesday · Sep 16-pub fn day(ms: i64) -> String {- let Some(d) = local(ms) else {- return String::new();- };- match days_ago(&d) {- ..=0 => fmt(&d, "%l:%M %p"),- 1 => "Yesterday".into(),- 2..6 => fmt(&d, "%A"),- _ => fmt(&d, "%b %e"),- }-}--/// Chat separator: Today 3:27 AM · Yesterday 5:20 PM · Sep 16 9:02 AM-pub fn separator(ms: i64) -> String {- let Some(d) = local(ms) else {- return String::new();- };- let when = match days_ago(&d) {- ..=0 => "Today".to_owned(),- 1 => "Yesterday".to_owned(),- _ => fmt(&d, "%b %e"),- };- format!("{when} {}", fmt(&d, "%l:%M %p"))-}--// MARK: small pieces--pub fn label(text: &str, classes: &[&str]) -> gtk::Label {- gtk::Label::builder()- .label(text)- .xalign(0.0)- .css_classes(classes.iter().map(|c| (*c).to_owned()).collect::<Vec<_>>())- .build()-}--/// An icon-only button with its tooltip (IconButton).-pub fn icon_button(icon: &str, tooltip: &str) -> gtk::Button {- gtk::Button::builder()- .icon_name(icon)- .tooltip_text(tooltip)- .css_classes(["icon-btn"])- .valign(gtk::Align::Center)- .build()-}--pub fn hline() -> gtk::Box {- gtk::Box::builder().css_classes(["hline"]).build()-}--fn bubble(text: &str, markup: bool, class: &str) -> gtk::Label {- let l = gtk::Label::builder()- .wrap(true)- .wrap_mode(gtk::pango::WrapMode::WordChar)- .selectable(true)- .xalign(0.0)- .css_classes(["bubble", class])- .build();- if markup {- l.set_markup(&markup::to_pango(text));- } else {- l.set_label(text);- }- l-}--// MARK: messages--/// Main-chat context for a message: the entry id it starts a thread on.-pub struct Reply<'a> {- pub ui: &'a App,- pub root: Option<&'a str>,-}--pub fn user_bubble(r: &Reply, e: &Value, bot_working: bool, start: bool) -> gtk::Widget {- let col = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(4)- .halign(gtk::Align::End)- .margin_start(56)- .margin_top(if start { 12 } else { 4 })- .build();- let text = e["data"]["text"].as_str().unwrap_or("");- for a in e["data"]["attachments"].as_array().into_iter().flatten() {- col.append(&file_card(r.ui, e, a));- }- if !text.is_empty() {- let b = bubble(text, false, "bubble-user");- col.append(&with_menu(r, b.upcast_ref(), true, text, false));- }- let status = match e["data"]["status"].as_str() {- Some("sending") => "Sending…".to_owned(),- Some("queued") if bot_working => "Waiting to send — it'll read this when it's done".into(),- Some("failed") => "Failed to send".into(),- Some("cancelled") => "Not sent — stopped".into(),- _ => clock(e["createdAt"].as_i64().unwrap_or(0)),- };- let s = label(&status, &["time"]);- s.set_halign(gtk::Align::End);- if e["data"]["status"] == "failed" {- s.add_css_class("danger-text");- }- col.append(&s);- if e["data"]["status"] == "failed"- && let Some(nonce) = e["data"]["clientNonce"].as_str()- {- let actions = gtk::Box::new(gtk::Orientation::Horizontal, 6);- for (icon, title, retry) in [- ("view-refresh-symbolic", "Resend", true),- ("user-trash-symbolic", "Delete", false),- ] {- let button = icon_button(icon, title);- let (ui, nonce) = (r.ui.clone(), nonce.to_owned());- button.connect_clicked(move |_| {- if retry {- ui::retry(&ui, &nonce)- } else {- ui::discard(&ui, &nonce)- }- });- actions.append(&button);- }- col.append(&actions);- }- col.append(&reactions(r.ui, e));- col.upcast()-}--/// A message as one line of text: its text, or else its file names.-pub fn message_text(e: &Value) -> String {- match e["data"]["text"].as_str().filter(|t| !t.is_empty()) {- Some(t) => t.to_owned(),- None => e["data"]["attachments"]- .as_array()- .into_iter()- .flatten()- .filter_map(|a| a["name"].as_str())- .collect::<Vec<_>>()- .join(", "),- }-}--/// A file sent with a message: its name and size.-fn file_card(ui: &App, entry: &Value, a: &Value) -> gtk::Widget {- let card = gtk::Box::builder()- .spacing(8)- .halign(gtk::Align::End)- .css_classes(["file-card"])- .build();- card.append(>k::Image::from_icon_name("text-x-generic-symbolic"));- let col = gtk::Box::new(gtk::Orientation::Vertical, 0);- let name = label(a["name"].as_str().unwrap_or("File"), &[]);- name.set_ellipsize(gtk::pango::EllipsizeMode::Middle);- name.set_max_width_chars(36);- name.set_xalign(0.0);- col.append(&name);- let size = label(&file_size(a["size"].as_u64().unwrap_or(0)), &["time"]);- size.set_xalign(0.0);- col.append(&size);- card.append(&col);- if let (Some(id), Some(bot)) = (a["id"].as_str(), entry["botId"].as_str()) {- let save = icon_button("document-save-symbolic", "Save attachment");- let (ui, id, bot, name) = (- ui.clone(),- id.to_owned(),- bot.to_owned(),- a["name"].as_str().unwrap_or("File").to_owned(),- );- save.connect_clicked(move |button| {- button.set_sensitive(false);- let (ui, button) = (ui.clone(), button.clone());- client::save_file(bot.clone(), id.clone(), name.clone(), move |result| {- button.set_sensitive(true);- match result {- Ok(path) => toast(&ui, &format!("Saved {}", path.display())),- Err(e) => toast(&ui, &e),- }- });- });- card.append(&save);- }- card.upcast()-}--fn file_size(bytes: u64) -> String {- match bytes {- 0..1024 => format!("{bytes} B"),- 1024..1_048_576 => format!("{} KB", bytes / 1024),- _ => format!(- "{}.{} MB",- bytes / 1_048_576,- bytes % 1_048_576 * 10 / 1_048_576- ),- }-}--pub fn agent_bubble(r: &Reply, st: &State, e: &Value, group: bool, start: bool) -> gtk::Widget {- let col = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(4)- .margin_end(64)- .margin_top(if start { 12 } else { 4 })- .build();- if group && start {- col.append(&author_label(st, e["data"]["author"].as_str()));- }- let text = e["data"]["text"].as_str().unwrap_or("");- let b = bubble(text, true, "bubble-agent");- b.set_halign(gtk::Align::Start);- col.append(&with_menu(r, b.upcast_ref(), false, text, true));- let t = label(&clock(e["createdAt"].as_i64().unwrap_or(0)), &["time"]);- t.set_margin_start(12);- col.append(&t);- col.append(&reactions(r.ui, e));- col.upcast()-}--fn reactions(ui: &App, entry: &Value) -> gtk::Box {- let row = gtk::Box::new(gtk::Orientation::Horizontal, 4);- if entry["id"]- .as_str()- .unwrap_or_default()- .starts_with("local-")- {- return row;- }- for emoji in entry["data"]["reactions"]- .as_array()- .into_iter()- .flatten()- .filter_map(Value::as_str)- {- let button = gtk::Button::with_label(emoji);- button.set_tooltip_text(Some("Remove reaction"));- button.add_css_class("flat");- let (ui, id, emoji) = (ui.clone(), entry["id"].clone(), emoji.to_owned());- button.connect_clicked(move |button| {- button.set_sensitive(false);- let (ui, button) = (ui.clone(), button.clone());- client::call("react", json!({"entryId": id, "emoji": emoji}), move |r| {- button.set_sensitive(true);- if let Err(e) = r {- toast(&ui, &e);- }- });- });- row.append(&button);- }- let add = icon_button("face-smile-symbolic", "React");- let (ui, id) = (ui.clone(), entry["id"].clone());- add.connect_clicked(move |button| {- let items = ["👍", "❤️", "😂", "🎉", "👀", "✅"]- .into_iter()- .map(|emoji| {- let (ui, id) = (ui.clone(), id.clone());- ui::MenuItem::new(- "",- emoji,- Box::new(move || {- let ui = ui.clone();- client::call("react", json!({"entryId":id,"emoji":emoji}), move |r| {- if let Err(e) = r {- toast(&ui, &e);- }- });- }),- )- })- .collect();- ui::popup_menu(button, None, items);- });- row.append(&add);- row-}--pub fn notice(e: &Value) -> gtk::Widget {- let mut text = e["data"]["text"].as_str().unwrap_or("").to_owned();- // A voice call from the phone: "Voice chat · 00:16".- if let Some(s) = e["data"]["callSeconds"].as_u64() {- text = format!("{text} · {:02}:{:02}", s / 60, s % 60);- }- let text = text.as_str();- match e["data"]["style"].as_str() {- Some("divider") => {- let row = gtk::Box::builder()- .spacing(10)- .margin_top(16)- .margin_bottom(6)- .build();- let l = gtk::Label::builder()- .label(text)- .wrap(true)- .justify(gtk::Justification::Center)- .max_width_chars(40)- .css_classes(["footnote", "tertiary"])- .build();- let (a, b) = (hline(), hline());- for w in [&a, &b] {- w.set_hexpand(true);- w.set_valign(gtk::Align::Center);- }- row.append(&a);- row.append(&l);- row.append(&b);- row.upcast()- }- Some("error") => {- let row = gtk::Box::builder()- .spacing(8)- .css_classes(["notice-error"])- .margin_top(10)- .build();- let icon = gtk::Image::from_icon_name("dialog-warning-symbolic");- icon.add_css_class("danger-text");- icon.set_valign(gtk::Align::Start);- row.append(&icon);- let l = label(text, &["small"]);- l.set_wrap(true);- l.set_selectable(true);- l.set_hexpand(true);- row.append(&l);- row.upcast()- }- _ => {- let l = gtk::Label::builder()- .label(text)- .wrap(true)- .justify(gtk::Justification::Center)- .css_classes(["footnote", "secondary"])- .margin_top(10)- .build();- l.upcast()- }- }-}--pub fn permission_card(ui: &App, st: &State, e: &Value, group: bool) -> gtk::Widget {- let outer = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(4)- .margin_top(12)- .build();- if group {- outer.append(&author_label(st, e["data"]["author"].as_str()));- }- let d = &e["data"];- let pending = d["status"] == "pending";- let card = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(10)- .css_classes(["perm-card"])- .margin_end(40)- .build();- 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",- };- let top = gtk::Box::builder().spacing(8).build();- top.append(&label(headline, &["headline"]));- if pending {- let dot = gtk::DrawingArea::builder()- .content_width(7)- .content_height(7)- .valign(gtk::Align::Center)- .build();- dot.set_draw_func(|_, cr, w, _| {- let r = f64::from(w) / 2.0;- cr.arc(r, r, r, 0.0, std::f64::consts::TAU);- let (red, g, b) = avatar::rgb(0xF0A030);- cr.set_source_rgb(red, g, b);- cr.fill().ok();- });- top.append(&dot);- }- card.append(&top);- let title = label(- d["title"].as_str().unwrap_or(""),- &["small", "mono", "secondary"],- );- title.set_wrap(true);- title.set_wrap_mode(gtk::pango::WrapMode::WordChar);- card.append(&title);- let host = st.hello["name"].as_str().unwrap_or("this computer");- let runs = gtk::Box::builder().spacing(5).build();- let icon = gtk::Image::from_icon_name("computer-symbolic");- icon.add_css_class("tertiary");- icon.set_pixel_size(12);- runs.append(&icon);- let cwd = d["cwd"].as_str().map(folder_name);- runs.append(&label(- &format!(- "Runs on {host}{}",- cwd.map(|c| format!(" · {c}")).unwrap_or_default()- ),- &["footnote", "tertiary"],- ));- card.append(&runs);-- let mut detail = String::new();- if let Some(c) = d["command"].as_str() {- detail.push_str(c);- }- if let Some(c) = d["detail"].as_str() {- detail.push('\n');- detail.push_str(&c.chars().take(2000).collect::<String>());- }- 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() {- card.append(&disclosure("Details", &{- let l = label(detail.trim(), &["codebox"]);- l.set_selectable(true);- l.set_wrap(true);- l.set_wrap_mode(gtk::pango::WrapMode::WordChar);- l- }));- }- if pending {- let choices = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .css_classes(["choices"])- .margin_top(4)- .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,- "reject_always" => 3,- _ => 9,- };- opts.sort_by_key(|o| rank(o["kind"].as_str().unwrap_or("")));- for (i, o) in opts.iter().enumerate() {- let kind = o["kind"].as_str().unwrap_or("");- let text = match kind {- "allow_once" => "Allow once",- "allow_always" => "Always allow",- "reject_once" => "Deny",- "reject_always" => "Never",- _ => o["name"].as_str().unwrap_or("OK"),- };- if i > 0 {- choices.append(&hline());- }- let l = label(text, &[]);- if kind == "allow_once" {- l.add_css_class("semibold");- }- if !kind.starts_with("allow") {- l.add_css_class("danger-text");- }- l.set_hexpand(true);- let spinner = gtk::Spinner::builder().visible(false).build();- let row = gtk::Box::new(gtk::Orientation::Horizontal, 8);- row.append(&l);- row.append(&spinner);- let btn = gtk::Button::builder()- .child(&row)- .css_classes(["choice"])- .build();- let (entry_id, opt) = (- e["id"].as_str().unwrap_or("").to_owned(),- o["optionId"].clone(),- );- let (ui2, choices2) = (ui.clone(), choices.clone());- btn.connect_clicked(move |_| {- // One answer per card: while it is on its way, the chosen row spins and the rest wait.- choices2.set_sensitive(false);- spinner.set_visible(true);- spinner.start();- let (ui3, choices3, spinner2) = (ui2.clone(), choices2.clone(), spinner.clone());- client::call(- "respondPermission",- json!({"entryId": entry_id, "optionId": opt}),- move |r| {- let settle = move || {- spinner2.stop();- spinner2.set_visible(false);- choices3.set_sensitive(true);- };- match r {- Err(e) => {- settle();- toast(&ui3, &e);- }- // The card's own update follows on the events stream; hold the spinner until then.- Ok(_) => {- gtk::glib::timeout_add_seconds_local_once(2, settle);- }- }- },- );- });- choices.append(&btn);- }- card.append(&choices);- } 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"), Some("reject_always")) => "Never allowed",- (Some("answered"), _) => chosen- .and_then(|o| o["name"].as_str())- .unwrap_or("Answered"),- (Some("cancelled"), _) => "Cancelled",- _ => "Expired — the agent moved on",- };- card.append(&label(outcome, &["footnote", "medium", "secondary"]));- }- outer.append(&card);- outer.upcast()-}--/// A "Details ›" line that slides its content open.-pub fn disclosure(title: &str, content: &impl IsA<gtk::Widget>) -> gtk::Box {- let col = gtk::Box::new(gtk::Orientation::Vertical, 0);- let head = gtk::Box::builder().spacing(4).build();- head.append(&label(title, &["footnote", "medium", "secondary"]));- let chevron = gtk::Image::from_icon_name("go-next-symbolic");- chevron.set_pixel_size(10);- chevron.add_css_class("secondary");- head.append(&chevron);- let btn = gtk::Button::builder()- .child(&head)- .css_classes(["plain"])- .halign(gtk::Align::Start)- .build();- let rev = gtk::Revealer::builder()- .child(content)- .transition_type(gtk::RevealerTransitionType::SlideDown)- .build();- content.set_margin_top(6);- {- let rev = rev.clone();- btn.connect_clicked(move |_| {- let open = !rev.reveals_child();- rev.set_reveal_child(open);- chevron.set_icon_name(Some(if open {- "go-down-symbolic"- } else {- "go-next-symbolic"- }));- });- }- col.append(&btn);- col.append(&rev);- col-}--/// Who wrote a message in a group: their avatar and name in their color.-pub fn author_label(st: &State, id: Option<&str>) -> gtk::Widget {- let bot = id.and_then(|id| st.bots.get(id));- let name = bot- .and_then(|b| b["name"].as_str())- .unwrap_or("A deleted bot");- let row = gtk::Box::builder().spacing(8).build();- if let Some(b) = bot {- row.append(&avatar::of(&st.bots, b, 26, false));- }- let l = gtk::Label::builder()- .use_markup(true)- .label(match bot {- Some(b) => format!(- "<span foreground=\"#{:06X}\">{}</span>",- avatar::color_of(b["avatarColor"].as_str().unwrap_or("gray")),- gtk::glib::markup_escape_text(name)- ),- None => gtk::glib::markup_escape_text(name).to_string(),- })- .css_classes(["author"])- .build();- if bot.is_none() {- l.add_css_class("secondary");- }- row.append(&l);- row.upcast()-}--/// Copy / Reply in thread / Show what it did on right-click or long-press, and a-/// "Reply in thread" button that shows beside a main-chat message on hover.-fn with_menu(r: &Reply, w: >k::Widget, end: bool, text: &str, agent: bool) -> gtk::Widget {- let host = gtk::Box::builder()- .spacing(4)- .css_classes(["reply-host"])- .halign(if end {- gtk::Align::End- } else {- gtk::Align::Start- })- .build();- let btn = r.root.map(|root| {- let btn = icon_button("mail-reply-sender-symbolic", "Reply in thread");- btn.add_css_class("reply-btn");- let (ui2, root2) = (r.ui.clone(), root.to_owned());- btn.connect_clicked(move |_| ui::open_thread(&ui2, &root2));- btn- });- if end && let Some(b) = &btn {- host.append(b);- }- host.append(w);- if !end && let Some(b) = &btn {- host.append(b);- }- let menu = {- let (ui2, root, text, host2) = (- r.ui.clone(),- r.root.map(str::to_owned),- text.to_owned(),- host.clone(),- );- move |x: f64, y: f64| {- let mut items: Vec<ui::MenuItem> = vec![];- let t = text.clone();- items.push(ui::MenuItem::new(- "edit-copy-symbolic",- "Copy",- Box::new(move || {- if let Some(d) = gtk::gdk::Display::default() {- d.clipboard().set_text(&t);- }- }),- ));- if let Some(root) = root.clone() {- let ui3 = ui2.clone();- items.push(ui::MenuItem::new(- "mail-reply-sender-symbolic",- "Reply in thread",- Box::new(move || ui::open_thread(&ui3, &root)),- ));- }- if agent {- let ui3 = ui2.clone();- items.push(ui::MenuItem::new(- "view-list-symbolic",- "Show what it did",- Box::new(move || crate::dialogs::trace(&ui3)),- ));- }- ui::popup_menu(&host2, Some((x, y)), items);- }- };- // Capture phase: runs before the selectable label's own context menu.- let click = gtk::GestureClick::builder()- .button(gtk::gdk::BUTTON_SECONDARY)- .propagation_phase(gtk::PropagationPhase::Capture)- .build();- {- let menu = menu.clone();- click.connect_pressed(move |g, _, x, y| {- g.set_state(gtk::EventSequenceState::Claimed);- menu(x, y);- });- }- host.add_controller(click);- let hold = gtk::GestureLongPress::builder()- .touch_only(true)- .propagation_phase(gtk::PropagationPhase::Capture)- .build();- hold.connect_pressed(move |g, x, y| {- g.set_state(gtk::EventSequenceState::Claimed);- menu(x, y);- });- host.add_controller(hold);- host.upcast()-}--/// Under a message with a thread (Slack's): who replied, how many, how recently.-pub fn thread_chip(ui: &App, st: &State, e: &Value, end: bool, indent: i32) -> Option<gtk::Widget> {- let t = &e["data"]["thread"];- let count = t["count"].as_i64().filter(|c| *c > 0)?;- let inner = gtk::Box::builder().spacing(6).build();- let looks: Vec<(&str, &str, avatar::Mood)> = t["authors"]- .as_array()- .into_iter()- .flatten()- .filter_map(|a| st.bots.get(a.as_str()?))- .take(3)- .map(|b| {- (- b["avatarShape"].as_str().unwrap_or("blob"),- b["avatarColor"].as_str().unwrap_or("blue"),- avatar::Mood::Idle,- )- })- .collect();- if !looks.is_empty() {- inner.append(&avatar::row(&looks, 18, 6));- }- inner.append(&label(- &if count == 1 {- "1 reply".to_owned()- } else {- format!("{count} replies")- },- &["footnote", "semibold"],- ));- match t["unread"].as_i64().unwrap_or(0) {- 0 => inner.append(&label(- &day(t["lastAt"].as_i64().unwrap_or(0)),- &["footnote", "tertiary"],- )),- unread => inner.append(&label(&format!("{unread} new"), &["footnote", "semibold"])),- }- let chevron = gtk::Image::from_icon_name("go-next-symbolic");- chevron.set_pixel_size(10);- chevron.add_css_class("tertiary");- inner.append(&chevron);- let btn = gtk::Button::builder()- .child(&inner)- .tooltip_text("View thread")- .css_classes(["thread-chip"])- .halign(if end {- gtk::Align::End- } else {- gtk::Align::Start- })- .margin_start(indent)- .margin_top(4)- .build();- let (ui2, root) = (ui.clone(), e["id"].as_str().unwrap_or_default().to_owned());- btn.connect_clicked(move |_| ui::open_thread(&ui2, &root));- Some(btn.upcast())-}--/// The bot's live activity line: a turning orb, what it's doing and for how long.-pub fn working(ui: &App, bot: &Value) -> gtk::Widget {- let needs = bot["status"] == "needsInput";- let inner = gtk::Box::builder().spacing(8).build();- let o = orb::widget(needs, 16);- o.add_css_class(if needs { "warning-text" } else { "secondary" });- inner.append(&o);- let act = bot["activity"]- .as_str()- .filter(|s| !s.is_empty())- .unwrap_or("Working…");- let l = label(- act,- &["small", if needs { "warning-text" } else { "secondary" }],- );- l.set_ellipsize(gtk::pango::EllipsizeMode::End);- inner.append(&l);- if let Some(started) = bot["startedAt"].as_i64() {- let timer = label("", &["footnote", "tertiary"]);- let tick = {- let timer = timer.downgrade();- move || {- let Some(timer) = timer.upgrade() else {- return gtk::glib::ControlFlow::Break;- };- let s = ((ui::now_ms() - started) / 1000).max(0);- timer.set_label(&if s >= 3600 {- format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)- } else {- format!("{}:{:02}", s / 60, s % 60)- });- gtk::glib::ControlFlow::Continue- }- };- tick();- gtk::glib::timeout_add_seconds_local(1, tick);- inner.append(&timer);- }- let chevron = gtk::Image::from_icon_name("go-next-symbolic");- chevron.set_pixel_size(10);- chevron.add_css_class("tertiary");- inner.append(&chevron);- let btn = gtk::Button::builder()- .child(&inner)- .css_classes(["working"])- .halign(gtk::Align::Start)- .tooltip_text("Show what it's doing")- .margin_top(6)- .build();- let ui2 = ui.clone();- btn.connect_clicked(move |_| crate::dialogs::trace(&ui2));- btn.upcast()-}--#[cfg(test)]-mod tests {- #[test]- fn stamps() {- let now = crate::ui::now_ms();- assert!(super::separator(now).starts_with("Today "));- assert!(super::separator(now - 86_400_000).starts_with("Yesterday "));- assert!(super::clock(now).ends_with('M'));- assert_eq!(super::day(now - 86_400_000), "Yesterday");- }-}diff --git a/apps/linux/src/ui.rs b/apps/linux/src/ui.rsdeleted file mode 100644index 090980e7..00000000--- a/apps/linux/src/ui.rs+++ /dev/null@@ -1,2345 +0,0 @@-//! Main window, laid out like the Mac chat window (apps/macos/Views/ChatWindow.swift and-//! kit ThreadView): a roster sidebar (+, Search, rows, Account), and the conversation with-//! its header, the details panel or an open thread on the right, and the composer.--use crate::client::{self, Event};-use crate::rows::{- self, Reply, agent_bubble, hline, icon_button, label, notice, permission_card, thread_chip,- user_bubble,-};-use crate::{avatar, compose, dialogs, orb};-use adw::prelude::*;-use serde_json::{Value, json};-use std::cell::{Cell, RefCell};-use std::collections::{HashMap, HashSet};-use std::rc::Rc;--#[derive(Clone)]-pub struct Outgoing {- pub bot: String,- pub text: String,- pub thread: Option<String>,- pub files: Vec<std::path::PathBuf>,-}--#[derive(Default)]-pub struct State {- pub bots: HashMap<String, Value>,- pub entries: HashMap<String, Vec<Value>>,- pub usage: Value,- pub hello: Value,- /// Remote screen status (`screenStatus`), for the details panel.- pub screen: Value,- pub current: Option<String>,- /// Root entry of the thread open beside the current chat.- pub open_thread: Option<String>,- /// The To: page is showing instead of a chat.- pub composing: bool,- /// The details panel beside the chat is closed.- pub hide_details: bool,- pub search: String,- pub online: bool,- /// This app and the host can't work together until one of them updates.- pub mismatch: Option<crate::compat::Mismatch>,- /// The host/app versions a newer-release reminder was shown for (once each).- reminded: Option<String>,- pub outbox: HashMap<String, Outgoing>,- history_busy: HashSet<String>,- history_done: HashSet<String>,-}--/// A message box: send, or stop while the chat (or thread) is working. In a group,-/// typing `@` suggests its bots.-pub struct Composer {- view: gtk::TextView,- attach_btn: gtk::Button,- /// Files picked or dropped for the next message, shown as chips above the box.- files: RefCell<Vec<std::path::PathBuf>>,- files_box: gtk::Box,- files_rev: gtk::Revealer,- placeholder: gtk::Label,- send_btn: gtk::Button,- stop_btn: gtk::Button,- mentions: gtk::Box,- mentions_rev: gtk::Revealer,- root: gtk::Box,-}--fn composer() -> Composer {- let view = gtk::TextView::builder()- .wrap_mode(gtk::WrapMode::WordChar)- .accepts_tab(false)- .hexpand(true)- .top_margin(6)- .bottom_margin(6)- .build();- let scroll = gtk::ScrolledWindow::builder()- .child(&view)- .max_content_height(150)- .propagate_natural_height(true)- .hscrollbar_policy(gtk::PolicyType::Never)- .vscrollbar_policy(gtk::PolicyType::External)- .hexpand(true)- .build();- let placeholder = gtk::Label::builder()- .xalign(0.0)- .css_classes(["tertiary"])- .can_target(false)- .ellipsize(gtk::pango::EllipsizeMode::End)- .valign(gtk::Align::Center)- .build();- let field = gtk::Overlay::builder().child(&scroll).hexpand(true).build();- field.add_overlay(&placeholder);- let send_btn = gtk::Button::builder()- .icon_name("go-up-symbolic")- .tooltip_text("Send")- .css_classes(["send"])- .valign(gtk::Align::End)- .margin_bottom(2)- .build();- let stop_btn = gtk::Button::builder()- .icon_name("media-playback-stop-symbolic")- .tooltip_text("Stop")- .css_classes(["send"])- .valign(gtk::Align::End)- .margin_bottom(2)- .build();- let pill = gtk::Box::builder()- .spacing(8)- .css_classes(["composer"])- .margin_start(16)- .margin_end(16)- .margin_top(6)- .margin_bottom(16)- .build();- let attach_btn = gtk::Button::builder()- .icon_name("mail-attachment-symbolic")- .tooltip_text("Attach files")- .css_classes(["icon-btn"])- .valign(gtk::Align::End)- .margin_bottom(2)- .build();- pill.append(&attach_btn);- pill.append(&field);- pill.append(&stop_btn);- pill.append(&send_btn);- let mentions = gtk::Box::builder()- .spacing(6)- .margin_start(16)- .margin_end(16)- .margin_top(6)- .build();- let mentions_rev = gtk::Revealer::builder()- .transition_type(gtk::RevealerTransitionType::SlideUp)- .child(- >k::ScrolledWindow::builder()- .vscrollbar_policy(gtk::PolicyType::Never)- .child(&mentions)- .build(),- )- .build();- let files_box = gtk::Box::builder()- .spacing(6)- .margin_start(16)- .margin_end(16)- .margin_top(6)- .build();- let files_rev = gtk::Revealer::builder()- .transition_type(gtk::RevealerTransitionType::SlideUp)- .child(- >k::ScrolledWindow::builder()- .vscrollbar_policy(gtk::PolicyType::Never)- .child(&files_box)- .build(),- )- .build();- let col = gtk::Box::new(gtk::Orientation::Vertical, 0);- col.append(&mentions_rev);- col.append(&files_rev);- col.append(&pill);- let root = gtk::Box::new(gtk::Orientation::Vertical, 0);- root.append(- &adw::Clamp::builder()- .maximum_size(820)- .tightening_threshold(820)- .child(&col)- .build(),- );- Composer {- view,- attach_btn,- files: RefCell::default(),- files_box,- files_rev,- placeholder,- send_btn,- stop_btn,- mentions,- mentions_rev,- root,- }-}--pub struct Ui {- pub window: adw::ApplicationWindow,- pub toasts: adw::ToastOverlay,- pub split: adw::NavigationSplitView,- pub roster: gtk::ListBox,- roster_empty: gtk::Label,- banner: adw::Banner,- pub search: gtk::SearchEntry,- content_stack: gtk::Stack,- chat_header: adw::HeaderBar,- head_avatar: gtk::Box,- head_name: gtk::Label,- details_btn: gtk::Button,- chat_list: gtk::Box,- scroller: gtk::ScrolledWindow,- compose: Composer,- convo: gtk::Box,- side: gtk::Revealer,- side_stack: gtk::Stack,- details_content: gtk::Box,- details_gear: gtk::Button,- thread_back: gtk::Button,- close_thread: gtk::Button,- /// Below the breakpoint an open thread covers the chat instead of sitting beside it.- narrow: Cell<bool>,- pane_sub: gtk::Label,- pane_box: gtk::Box,- pane_list: gtk::Box,- pane_scroller: gtk::ScrolledWindow,- reply: Composer,- pub compose_page: compose::Page,- /// Bot shown in the last render; switching bots jumps to the newest message.- shown_bot: RefCell<String>,- /// Thread shown in the last render; opening one jumps to its newest reply.- shown_thread: RefCell<String>,- pub state: RefCell<State>,- rendering: Cell<bool>,- /// Debug builds: `CODYNC_DEBUG_OPEN=compose | group | <bot name>[/thread]` opens a screen- /// once the bots arrive (screenshot checks, like the Mac's).- debug_open: RefCell<Option<String>>,- account: gtk::Button,-}--pub type App = Rc<Ui>;--impl Ui {- fn composer(&self, in_thread: bool) -> &Composer {- if in_thread {- &self.reply- } else {- &self.compose- }- }-}--/// A flat header bar (44 px) whose title area is `title`.-pub fn flat_header(title: &impl IsA<gtk::Widget>) -> adw::HeaderBar {- adw::HeaderBar::builder()- .title_widget(title)- .css_classes(["flat-header"])- .build()-}--/// The header of a panel right of the chat: it carries the window's end buttons.-fn side_header(content: >k::Box) -> adw::HeaderBar {- content.set_hexpand(true);- let h = flat_header(content);- h.set_show_start_title_buttons(false);- h-}--fn sidebar(- new_btn: >k::Button,- search: >k::SearchEntry,- banner: &adw::Banner,-) -> (gtk::Box, gtk::ListBox, gtk::Label, gtk::Button) {- let header = flat_header(>k::Box::builder().hexpand(true).build());- header.pack_end(new_btn);- let roster = gtk::ListBox::builder()- .css_classes(["roster"])- .selection_mode(gtk::SelectionMode::Single)- .margin_start(12)- .margin_end(12)- .margin_top(4)- .build();- let roster_empty = gtk::Label::builder()- .justify(gtk::Justification::Center)- .use_markup(true)- .can_target(false)- .valign(gtk::Align::Center)- .build();- let list = gtk::Overlay::builder()- .child(- >k::ScrolledWindow::builder()- .vexpand(true)- .hscrollbar_policy(gtk::PolicyType::Never)- .child(&roster)- .build(),- )- .build();- list.add_overlay(&roster_empty);- let face = gtk::Image::builder()- .icon_name("avatar-default-symbolic")- .pixel_size(15)- .width_request(28)- .height_request(28)- .css_classes(["person-circle"])- .build();- let acct_inner = gtk::Box::builder().spacing(10).build();- acct_inner.append(&face);- acct_inner.append(>k::Label::new(Some("Account")));- let account = gtk::Button::builder()- .child(&acct_inner)- .css_classes(["footer-row"])- .tooltip_text("Account menu")- .build();- let footer = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(4)- .margin_start(12)- .margin_end(12)- .margin_top(6)- .margin_bottom(10)- .build();- footer.append(&account);- let col = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .css_classes(["surface"])- .build();- col.append(&header);- search.set_margin_start(12);- search.set_margin_end(12);- search.set_margin_top(4);- search.set_margin_bottom(8);- col.append(search);- col.append(banner);- col.append(&list);- col.append(&footer);- (col, roster, roster_empty, account)-}--fn empty_page(ui_new: >k::Button) -> gtk::Box {- let page = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .css_classes(["chat-bg"])- .build();- page.append(&flat_header(>k::Box::new(- gtk::Orientation::Horizontal,- 0,- )));- let center = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(14)- .valign(gtk::Align::Center)- .vexpand(true)- .margin_start(32)- .margin_end(32)- .margin_bottom(44)- .build();- use avatar::Mood;- center.append(&avatar::row(- &[- ("blob", "blue", Mood::Working),- ("squircle", "orange", Mood::Idle),- ("teardrop", "violet", Mood::Working),- ],- 60,- 10,- ));- let title = gtk::Label::builder()- .label("Your coding agents, as teammates.")- .css_classes(["title2"])- .build();- center.append(&title);- center.append(- >k::Label::builder()- .label("Pick a bot, or create one for each kind of work and point it at a project.")- .wrap(true)- .justify(gtk::Justification::Center)- .max_width_chars(52)- .css_classes(["body13", "secondary"])- .build(),- );- ui_new.set_halign(gtk::Align::Center);- center.append(ui_new);- page.append(¢er);- page-}--pub fn build(app: &adw::Application) -> App {- let new_btn = icon_button("list-add-symbolic", "New chat (Ctrl+N)");- let search = gtk::SearchEntry::builder()- .placeholder_text("Search")- .css_classes(["search-field"])- .build();- let banner = adw::Banner::new("Reconnecting to the Codync host…");-- let (sidebar_box, roster, roster_empty, account_btn) = sidebar(&new_btn, &search, &banner);- let sidebar_page = adw::NavigationPage::new(&sidebar_box, "Codync");-- // Chat header: avatar + name (toggles details), details toggle, more.- let head_avatar = gtk::Box::new(gtk::Orientation::Horizontal, 0);- let head_name = gtk::Label::builder()- .css_classes(["body13", "semibold"])- .ellipsize(gtk::pango::EllipsizeMode::End)- .build();- let head_inner = gtk::Box::builder().spacing(7).build();- head_inner.append(&head_avatar);- head_inner.append(&head_name);- let head_btn = gtk::Button::builder()- .child(&head_inner)- .css_classes(["plain"])- .tooltip_text("View conversation details")- .build();- let details_btn = icon_button("sidebar-show-right-symbolic", "Conversation details");- let menu_btn = icon_button("view-more-symbolic", "More");- let head_row = gtk::Box::builder()- .spacing(4)- .hexpand(true)- .margin_start(10)- .build();- head_row.append(&head_btn);- head_row.append(>k::Box::builder().hexpand(true).build());- head_row.append(&details_btn);- head_row.append(&menu_btn);- let chat_header = flat_header(&head_row);-- let chat_list = entry_list();- let scroller = gtk::ScrolledWindow::builder()- .vexpand(true)- .hscrollbar_policy(gtk::PolicyType::Never)- .child(- &adw::Clamp::builder()- .maximum_size(820)- .tightening_threshold(820)- .child(&chat_list)- .build(),- )- .build();- let compose = composer();- let convo = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .hexpand(true)- .css_classes(["chat-bg"])- .build();- convo.append(&chat_header);- convo.append(&hline());- convo.append(&scroller);- convo.append(&compose.root);-- // Details panel (the Mac inspector).- let details_gear = icon_button("emblem-system-symbolic", "Bot settings");- let details_close = icon_button("sidebar-show-right-symbolic", "Close details");- let dh = gtk::Box::builder()- .spacing(4)- .margin_start(12)- .margin_end(12)- .height_request(44)- .build();- dh.append(>k::Box::builder().hexpand(true).build());- dh.append(&details_gear);- dh.append(&details_close);- let details_content = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(22)- .margin_start(16)- .margin_end(16)- .margin_bottom(16)- .build();- let details_box = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .width_request(292)- .css_classes(["chat-bg"])- .build();- details_box.append(&side_header(&dh));- details_box.append(- >k::ScrolledWindow::builder()- .vexpand(true)- .hscrollbar_policy(gtk::PolicyType::Never)- .child(&details_content)- .build(),- );-- // Thread pane (RepliesView).- let pane_sub = label("", &["footnote", "tertiary"]);- pane_sub.set_ellipsize(gtk::pango::EllipsizeMode::End);- let titles = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .hexpand(true)- .valign(gtk::Align::Center)- .build();- titles.append(&label("Thread", &["semibold"]));- titles.append(&pane_sub);- let thread_back = icon_button("go-previous-symbolic", "Back to chat");- thread_back.set_visible(false);- let close_thread = icon_button("window-close-symbolic", "Close thread (Esc)");- let ph = gtk::Box::builder()- .spacing(8)- .margin_start(16)- .margin_end(10)- .height_request(48)- .build();- ph.append(&thread_back);- ph.append(&titles);- ph.append(&close_thread);- let pane_list = entry_list();- let pane_scroller = gtk::ScrolledWindow::builder()- .vexpand(true)- .hscrollbar_policy(gtk::PolicyType::Never)- .child(&pane_list)- .build();- let reply = composer();- let pane_box = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .width_request(420)- .css_classes(["chat-bg"])- .build();- pane_box.append(&side_header(&ph));- pane_box.append(&hline());- pane_box.append(&pane_scroller);- pane_box.append(&reply.root);-- let side_stack = gtk::Stack::builder()- .transition_type(gtk::StackTransitionType::Crossfade)- .hhomogeneous(false)- .build();- side_stack.add_named(&details_box, Some("details"));- side_stack.add_named(&pane_box, Some("thread"));- let side_outer = gtk::Box::new(gtk::Orientation::Horizontal, 0);- side_outer.append(>k::Box::builder().css_classes(["vline"]).build());- side_outer.append(&side_stack);- let side = gtk::Revealer::builder()- .transition_type(gtk::RevealerTransitionType::SlideLeft)- .child(&side_outer)- .build();- let chat_area = gtk::Box::new(gtk::Orientation::Horizontal, 0);- chat_area.append(&convo);- chat_area.append(&side);-- let new_bot = gtk::Button::builder()- .label("New Bot")- .css_classes(["primary-pill"])- .build();- let compose_page = compose::build();- let content_stack = gtk::Stack::builder()- .transition_type(gtk::StackTransitionType::Crossfade)- .transition_duration(150)- .build();- content_stack.add_named(&empty_page(&new_bot), Some("empty"));- content_stack.add_named(&chat_area, Some("chat"));- content_stack.add_named(&compose_page.root, Some("compose"));- let content_page = adw::NavigationPage::new(&content_stack, "Chat");-- let split = adw::NavigationSplitView::builder()- .sidebar(&sidebar_page)- .content(&content_page)- .min_sidebar_width(260.0)- .max_sidebar_width(296.0)- .sidebar_width_fraction(0.27)- .sidebar_width_unit(adw::LengthUnit::Px)- .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)- .width_request(360)- .height_request(400)- .content(&toasts)- .build();- let bp = adw::Breakpoint::new(adw::BreakpointCondition::new_length(- adw::BreakpointConditionLengthType::MaxWidth,- 640.0,- adw::LengthUnit::Px,- ));- bp.add_setter(&split, "collapsed", Some(&true.to_value()));- window.add_breakpoint(bp.clone());- // Below this the details panel starts closed (the Mac's 680 pt conversation width).- let bp_details = adw::Breakpoint::new(adw::BreakpointCondition::new_length(- adw::BreakpointConditionLengthType::MaxWidth,- 980.0,- adw::LengthUnit::Px,- ));- window.add_breakpoint(bp_details.clone());-- let ui: App = Rc::new(Ui {- window,- toasts,- split,- roster,- roster_empty,- banner,- search,- content_stack,- chat_header,- head_avatar,- head_name,- details_btn: details_btn.clone(),- chat_list,- scroller,- compose,- convo,- side,- side_stack,- details_content,- details_gear: details_gear.clone(),- thread_back: thread_back.clone(),- close_thread: close_thread.clone(),- narrow: Cell::new(false),- pane_sub,- pane_box,- pane_list,- pane_scroller,- reply,- compose_page,- shown_bot: RefCell::new(String::new()),- shown_thread: RefCell::new(String::new()),- state: RefCell::new(State::default()),- rendering: Cell::new(false),- account: account_btn.clone(),- debug_open: RefCell::new(if cfg!(debug_assertions) {- std::env::var("CODYNC_DEBUG_OPEN").ok()- } else {- None- }),- });-- // Wiring- {- let ui2 = ui.clone();- ui.banner- .connect_button_clicked(move |_| update_for_mismatch(&ui2));- }- {- let ui2 = ui.clone();- ui.roster.connect_row_activated(move |_, row| {- select(&ui2, row.widget_name().as_str());- });- }- {- let ui2 = ui.clone();- ui.search.connect_search_changed(move |s| {- ui2.state.borrow_mut().search = s.text().to_string();- render_roster(&ui2);- });- }- {- let ui2 = ui.clone();- ui.search.connect_stop_search(move |s| {- s.set_text("");- ui2.roster.grab_focus();- });- }- for b in [&new_btn, &new_bot] {- let ui2 = ui.clone();- b.connect_clicked(move |_| compose::open(&ui2));- }- {- let ui2 = ui.clone();- account_btn.connect_clicked(move |b| dialogs::account_menu(&ui2, b));- }- for b in [&close_thread, &thread_back] {- let ui2 = ui.clone();- b.connect_clicked(move |_| close_open_thread(&ui2));- }- for b in [&head_btn, &details_btn, &details_close] {- let ui2 = ui.clone();- b.connect_clicked(move |_| {- let mut st = ui2.state.borrow_mut();- st.hide_details = !st.hide_details;- drop(st);- schedule(&ui2);- });- }- {- let ui2 = ui.clone();- details_gear.connect_clicked(move |_| {- let bot = {- let st = ui2.state.borrow();- st.current.as_ref().and_then(|id| st.bots.get(id)).cloned()- };- if let Some(b) = bot {- if is_group(&b) {- dialogs::group_editor(&ui2, Some(b));- } else {- dialogs::editor(&ui2, Some(b));- }- }- });- }- {- let ui2 = ui.clone();- menu_btn.connect_clicked(move |b| {- if let Some(id) = ui2.state.borrow().current.clone() {- dialogs::bot_menu(&ui2, b.upcast_ref(), None, &id, false);- }- });- }- for narrow in [true, false] {- let ui2 = ui.clone();- let f = move |_: &adw::Breakpoint| {- ui2.narrow.set(narrow);- schedule(&ui2);- };- if narrow {- bp.connect_apply(f);- } else {- bp.connect_unapply(f);- }- }- for compact in [true, false] {- let ui2 = ui.clone();- let f = move |_: &adw::Breakpoint| {- ui2.state.borrow_mut().hide_details = compact;- schedule(&ui2);- };- if compact {- bp_details.connect_apply(f);- } else {- bp_details.connect_unapply(f);- }- }- // Ctrl+N: new chat; Ctrl+F: search; Esc closes an open thread.- {- let actions = gtk::gio::SimpleActionGroup::new();- let new_chat = gtk::gio::SimpleAction::new("new-chat", None);- let ui2 = ui.clone();- new_chat.connect_activate(move |_, _| compose::open(&ui2));- actions.add_action(&new_chat);- let find = gtk::gio::SimpleAction::new("search", None);- let ui2 = ui.clone();- find.connect_activate(move |_, _| {- ui2.split.set_show_content(false);- ui2.search.grab_focus();- });- actions.add_action(&find);- ui.window.insert_action_group("codync", Some(&actions));- app.set_accels_for_action("codync.new-chat", &["<Control>n"]);- app.set_accels_for_action("codync.search", &["<Control>f"]);- let keys = gtk::EventControllerKey::new();- let ui2 = ui.clone();- keys.connect_key_pressed(move |_, key, _, _| {- if key == gtk::gdk::Key::Escape && ui2.state.borrow().open_thread.is_some() {- close_open_thread(&ui2);- return gtk::glib::Propagation::Stop;- }- gtk::glib::Propagation::Proceed- });- ui.window.add_controller(keys);- }- wire_composer(&ui, false);- wire_composer(&ui, true);- compose::wire(&ui);-- ui.window.present();- connect(&ui);- ui-}--fn close_open_thread(ui: &App) {- ui.state.borrow_mut().open_thread = None;- schedule(ui);-}--/// Opens a bot's (or group's) chat.-pub fn select(ui: &App, id: &str) {- {- let mut st = ui.state.borrow_mut();- st.current = Some(id.to_owned());- st.open_thread = None;- st.composing = false;- }- ui.split.set_show_content(true);- mark_read(ui);- render(ui);-}--fn entry_list() -> gtk::Box {- gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .margin_start(16)- .margin_end(16)- .margin_top(8)- .margin_bottom(8)- .build()-}--fn wire_composer(ui: &App, in_thread: bool) {- let c = ui.composer(in_thread);- {- let ui2 = ui.clone();- c.send_btn.connect_clicked(move |_| send(&ui2, in_thread));- }- {- let ui2 = ui.clone();- c.stop_btn.connect_clicked(move |_| {- if let Some(id) = ui2.state.borrow().current.clone() {- client::call("stop", json!({"botId": id}), |_| {});- }- });- }- {- 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)- {- send(&ui2, in_thread);- return gtk::glib::Propagation::Stop;- }- gtk::glib::Propagation::Proceed- });- c.view.add_controller(keys);- }- {- let ui2 = ui.clone();- c.view- .buffer()- .connect_changed(move |_| update_composer(&ui2, in_thread));- }- {- let ui2 = ui.clone();- c.attach_btn.connect_clicked(move |b| {- let ui3 = ui2.clone();- gtk::FileDialog::builder()- .title("Attach files")- .build()- .open_multiple(- b.root().and_downcast_ref::<gtk::Window>(),- gtk::gio::Cancellable::NONE,- move |r| {- let Ok(list) = r else { return };- let paths = (0..list.n_items())- .filter_map(|i| list.item(i).and_downcast::<gtk::gio::File>())- .filter_map(|f| f.path());- add_files(&ui3, in_thread, paths);- },- );- });- }- {- // Files dropped on the box.- let ui2 = ui.clone();- let drop = gtk::DropTarget::new(- gtk::gdk::FileList::static_type(),- gtk::gdk::DragAction::COPY,- );- drop.connect_drop(move |_, v, _, _| {- let Ok(list) = v.get::<gtk::gdk::FileList>() else {- return false;- };- add_files(- &ui2,- in_thread,- list.files().iter().filter_map(|f| f.path()),- );- true- });- c.root.add_controller(drop);- }-}--/// Adds files to the next message (not in a group: it has no folder of its own).-fn add_files(ui: &App, in_thread: bool, paths: impl Iterator<Item = std::path::PathBuf>) {- let group = {- let st = ui.state.borrow();- st.current- .as_ref()- .and_then(|id| st.bots.get(id))- .is_some_and(is_group)- };- if group {- toast(ui, "Files can't be sent to a group.");- return;- }- ui.composer(in_thread)- .files- .borrow_mut()- .extend(paths.filter(|p| p.is_file()));- show_files(ui, in_thread);-}--/// The chips for the picked files; × removes one.-fn show_files(ui: &App, in_thread: bool) {- let c = ui.composer(in_thread);- clear(&c.files_box);- let files = c.files.borrow().clone();- for (i, path) in files.iter().enumerate() {- let chip = gtk::Box::builder().spacing(4).css_classes(["chip"]).build();- chip.append(>k::Image::from_icon_name("text-x-generic-symbolic"));- let name = path- .file_name()- .map(|n| n.to_string_lossy().into_owned())- .unwrap_or_default();- chip.append(&label(&name, &["small"]));- let x = gtk::Button::builder()- .icon_name("window-close-symbolic")- .tooltip_text("Remove")- .css_classes(["chip-x"])- .build();- let ui2 = ui.clone();- x.connect_clicked(move |_| {- let c = ui2.composer(in_thread);- if i < c.files.borrow().len() {- c.files.borrow_mut().remove(i);- }- show_files(&ui2, in_thread);- });- chip.append(&x);- c.files_box.append(&chip);- }- c.files_rev.set_reveal_child(!files.is_empty());- update_composer(ui, in_thread);-}--fn connect(ui: &App) {- if client::token().is_none() {- dialogs::host_missing(ui);- return;- }- let ui2 = ui.clone();- client::call("hello", client::empty(), move |r| match r {- Ok(hello) => {- let mut st = ui2.state.borrow_mut();- st.mismatch = crate::compat::check(env!("CARGO_PKG_VERSION"), &hello);- st.hello = hello;- drop(st);- remind_updates(&ui2);- let mut st = ui2.state.borrow_mut();- // Open a specific bot on launch: `codync --bot <id>` (also used by desktop notifications).- let args: Vec<String> = std::env::args().collect();- if let Some(i) = args.iter().position(|a| a == "--bot") {- st.current = args.get(i + 1).cloned();- }- drop(st);- refresh_screen(&ui2);- let (tx, rx) = async_channel::unbounded();- client::stream(tx);- let ui3 = ui2.clone();- gtk::glib::spawn_future_local(async move {- while let Ok(ev) = rx.recv().await {- handle(&ui3, ev);- }- });- }- Err(_) => dialogs::host_missing(&ui2),- });-}--fn recheck_versions(ui: &App) {- let ui2 = ui.clone();- client::call("hello", client::empty(), move |r| {- if let Ok(hello) = r {- let mut st = ui2.state.borrow_mut();- st.mismatch = crate::compat::check(env!("CARGO_PKG_VERSION"), &hello);- st.hello = hello;- drop(st);- remind_updates(&ui2);- schedule(&ui2);- }- });-}--/// Still compatible, but this app is behind the host's release: a toast (gone on its own or-/// when closed) offers the update, once per pair of versions. A host behind this app updates-/// itself, so it gets no reminder.-fn remind_updates(ui: &App) {- let host_version = {- let mut st = ui.state.borrow_mut();- let host_version = st.hello["version"].as_str().unwrap_or_default().to_owned();- let key = format!("{host_version}/{}", env!("CARGO_PKG_VERSION"));- if st.mismatch.is_some() || st.reminded.as_deref() == Some(key.as_str()) {- return;- }- st.reminded = Some(key);- host_version- };- if !crate::compat::below(env!("CARGO_PKG_VERSION"), &host_version) {- return;- }- let reminder = adw::Toast::builder()- .title(format!("Codync {host_version} is available for this app"))- .button_label("Get update")- .timeout(10)- .build();- reminder.connect_button_clicked(|_| {- let _ = gtk::gio::AppInfo::launch_default_for_uri(- "https://github.com/leepokai/Codync/releases/latest",- None::<>k::gio::AppLaunchContext>,- );- });- ui.toasts.add_toast(reminder);-}--/// While one side needs an update nothing is sent: says so and returns true.-pub fn blocked_by_update(ui: &App) -> bool {- let st = ui.state.borrow();- let Some(m) = &st.mismatch else {- return false;- };- let text = crate::compat::text(m, st.hello["name"].as_str().unwrap_or("this computer"));- drop(st);- toast(ui, &text);- true-}--/// The banner's button: what this app can do about a version mismatch.-fn update_for_mismatch(ui: &App) {- let Some(mismatch) = ui.state.borrow().mismatch.clone() else {- return;- };- match mismatch {- crate::compat::Mismatch::UpdateHost { .. } => {- let ui2 = ui.clone();- client::call(- "installHostUpdate",- json!({"force": false}),- move |r| match r {- // The host restarts; the reconnect checks the versions again.- Ok(_) => toast(&ui2, "Updating the host; reconnecting when it's ready…"),- Err(e) => toast(&ui2, &e),- },- );- }- crate::compat::Mismatch::UpdateApp { .. } => {- // The desktop app is package-managed; its releases are on GitHub.- let _ = gtk::gio::AppInfo::launch_default_for_uri(- "https://github.com/leepokai/Codync/releases/latest",- None::<>k::gio::AppLaunchContext>,- );- }- }-}--pub fn refresh_screen(ui: &App) {- let ui2 = ui.clone();- client::call("screenStatus", client::empty(), move |r| {- ui2.state.borrow_mut().screen = r.unwrap_or(Value::Null);- schedule(&ui2);- });-}--pub fn reconnect(ui: &App) {- client::reset_rev();- connect(ui);-}--fn handle(ui: &App, ev: Event) {- {- let mut st = ui.state.borrow_mut();- match ev {- Event::Online(on) => {- if on && !st.online {- // Back after a drop: the host may have been updated (or replaced) meanwhile.- recheck_versions(ui);- }- st.online = on;- }- Event::Message(m) => match m["type"].as_str().unwrap_or_default() {- "hello" | "usage" => st.usage = m["usage"].clone(),- "bot" => {- let bot = &m["bot"];- let id = bot["id"].as_str().unwrap_or_default().to_owned();- if bot["deleted"].as_bool().unwrap_or(false) {- st.bots.remove(&id);- st.entries.remove(&id);- if st.current.as_deref() == Some(&id) {- st.current = None;- st.open_thread = None;- }- } else {- if let Some(old) = st.bots.get(&id) {- notify(ui, old, bot);- }- st.bots.insert(id, bot.clone());- }- }- "entry" => upsert(&mut st, m["entry"].clone()),- _ => {}- },- }- }- schedule(ui);- debug_open(ui);-}--fn debug_open(ui: &App) {- let Some(target) = ui.debug_open.borrow().clone() else {- return;- };- // Bots arrive one event at a time: give the catch-up a moment.- if ui.state.borrow().bots.len() < 2 {- return;- }- let ui2 = ui.clone();- let target = target.clone();- ui.debug_open.replace(None);- gtk::glib::timeout_add_local_once(std::time::Duration::from_millis(800), move || {- debug_open_now(&ui2, &target);- });-}--fn debug_open_now(ui: &App, target: &str) {- let (name, thread) = target.split_once('/').unwrap_or((target, ""));- match name {- "compose" => compose::open(ui),- "group" => dialogs::group_editor(ui, None),- "account" => {- dialogs::account_menu(ui, &ui.account);- }- _ => {- let st = ui.state.borrow();- let Some(id) = st- .bots- .values()- .find(|b| b["name"] == name)- .and_then(|b| b["id"].as_str().map(str::to_owned))- else {- return;- };- let root = st.entries.get(&id).and_then(|l| {- l.iter()- .rev()- .find(|e| e["data"]["thread"]["count"].as_i64().unwrap_or(0) > 0)- .and_then(|e| e["id"].as_str().map(str::to_owned))- });- if !thread.is_empty() && root.is_none() {- return;- }- drop(st);- select(ui, &id);- if let Some(root) = root.filter(|_| !thread.is_empty()) {- open_thread(ui, &root);- }- }- }-}--/// Desktop notification when a bot needs you or finishes, unless Codync is focused.-fn notify(ui: &App, old: &Value, new: &Value) {- if ui.window.is_active() || new["notify"] == false || new["hidden"] == true {- return;- }- // A bot's turn in a group is announced by the group.- if [old, new].iter().any(|b| {- b["workingChat"]- .as_str()- .is_some_and(|c| Some(c) != b["id"].as_str())- }) {- return;- }- 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(),- ),- _ => return,- };- let n = gtk::gio::Notification::new(&title);- n.set_body(Some(&body.chars().take(140).collect::<String>()));- if let Some(app) = ui.window.application() {- app.send_notification(new["id"].as_str(), &n);- }-}--pub fn upsert(st: &mut State, e: Value) {- let bot = e["botId"].as_str().unwrap_or_default().to_owned();- if !e["id"].as_str().unwrap_or_default().starts_with("local-")- && let Some(nonce) = e["data"]["clientNonce"].as_str()- {- st.outbox.remove(nonce);- }- let list = st.entries.entry(bot).or_default();- let id = e["id"].as_str().unwrap_or_default();- if let Some(i) = list.iter().position(|x| x["id"] == id) {- // A late command response mustn't undo a newer streamed update.- if e["rev"].as_i64() >= list[i]["rev"].as_i64() {- list[i] = e;- }- return;- }- if e["kind"] == "user"- && let Some(nonce) = e["data"]["clientNonce"].as_str().filter(|n| !n.is_empty())- {- list.retain(|x| x["id"] != format!("local-{nonce}"));- }- list.push(e);- list.sort_by_key(|x| x["seq"].as_i64().unwrap_or(i64::MAX));-}--/// Coalesces bursts of events into one render per frame.-pub fn schedule(ui: &App) {- if ui.rendering.replace(true) {- return;- }- let ui2 = ui.clone();- gtk::glib::idle_add_local_once(move || {- ui2.rendering.set(false);- render(&ui2);- });-}--pub fn render(ui: &App) {- {- let st = ui.state.borrow();- let host = st.hello["name"].as_str().unwrap_or("this computer");- // A version mismatch outranks a reconnect: it won't go away by waiting.- if let Some(m) = &st.mismatch {- ui.banner.set_title(&crate::compat::text(m, host));- ui.banner.set_button_label(Some(match m {- crate::compat::Mismatch::UpdateApp { .. } => "Get update",- crate::compat::Mismatch::UpdateHost { .. } => "Update host",- }));- ui.banner.set_revealed(true);- } else {- ui.banner.set_title("Reconnecting to the Codync host…");- ui.banner.set_button_label(None);- ui.banner.set_revealed(!st.online);- }- }- render_roster(ui);- let composing = ui.state.borrow().composing;- if composing {- ui.content_stack.set_visible_child_name("compose");- compose::render(ui);- return;- }- render_chat(ui);- render_side(ui);-}--pub fn working(b: &Value) -> bool {- matches!(b["status"].as_str(), Some("working" | "needsInput"))-}--/// Working in this lane: the chat `chat` (its main chat, or the thread on `thread`).-pub fn working_in(b: &Value, chat: &str, thread: Option<&str>) -> bool {- working(b)- && b["workingChat"].as_str().or(b["id"].as_str()) == Some(chat)- && b["workingThread"].as_str() == thread-}--pub fn is_group(b: &Value) -> bool {- b["kind"] == "group"-}--pub fn members<'a>(st: &'a State, group: &Value) -> Vec<&'a Value> {- group["members"]- .as_array()- .into_iter()- .flatten()- .filter_map(|m| st.bots.get(m.as_str()?))- .collect()-}--fn member_names(st: &State, group: &Value) -> String {- members(st, group)- .iter()- .filter_map(|b| b["name"].as_str())- .collect::<Vec<_>>()- .join(" · ")-}--/// The `@partial` being typed at the end of a group message, if any.-fn mention_query(draft: &str) -> Option<&str> {- let at = draft.rfind('@')?;- if draft[..at]- .chars()- .next_back()- .is_some_and(|c| !c.is_whitespace())- {- return None;- }- let q = &draft[at + 1..];- (!q.contains('\n') && q.chars().count() <= 24).then_some(q)-}--pub fn backend_name(st: &State, id: &str) -> String {- st.hello["backends"]- .as_array()- .and_then(|l| l.iter().find(|b| b["id"] == id))- .and_then(|b| b["name"].as_str())- .unwrap_or(if id == "custom" { "Custom agent" } else { id })- .to_owned()-}--/// Where a bot works, short: its project folder's name, or its personal workspace.-pub fn folder(bot: &Value) -> String {- if bot["managedWorkspace"] == true {- return "personal workspace".into();- }- folder_name(bot["cwd"].as_str().unwrap_or(""))-}--pub fn folder_name(p: &str) -> String {- std::path::Path::new(p)- .file_name()- .map_or_else(|| p.to_owned(), |s| s.to_string_lossy().into_owned())-}--/// The sidebar's bots, pinned first then most recent (the Mac `roster`).-pub fn roster(st: &State) -> Vec<&Value> {- 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),- )- });- bots-}--/// Live activity while working, otherwise the last message (BotRow's preview).-fn preview(st: &State, b: &Value) -> gtk::Widget {- let row = gtk::Box::builder().spacing(6).hexpand(true).build();- let text = |s: &str, class: &str| {- let l = label(&s.replace('\n', " "), &["small", class]);- l.set_ellipsize(gtk::pango::EllipsizeMode::End);- l.set_hexpand(true);- l- };- let activity = b["activity"].as_str().filter(|s| !s.is_empty());- match b["status"].as_str() {- Some("needsInput") => {- let o = orb::widget(true, 16);- o.add_css_class("warning-text");- row.append(&o);- row.append(&text(- activity.unwrap_or("Needs your approval"),- "warning-text",- ));- }- Some("working") => {- let o = orb::widget(false, 13);- o.add_css_class("secondary");- row.append(&o);- row.append(&text(activity.unwrap_or("Working…"), "secondary"));- }- Some("error") => row.append(&text(- b["lastMessage"].as_str().unwrap_or("Something went wrong"),- "danger-text",- )),- _ => row.append(&text(- &b["lastMessage"].as_str().map_or_else(- || {- if is_group(b) {- member_names(st, b)- } else {- format!(- "{} · {}",- backend_name(st, b["backend"].as_str().unwrap_or("")),- folder(b)- )- }- },- str::to_owned,- ),- "secondary",- )),- }- row.upcast()-}--fn render_roster(ui: &App) {- let st = ui.state.borrow();- let q = st.search.trim().to_lowercase();- let bots: Vec<&Value> = roster(&st)- .into_iter()- .filter(|b| {- q.is_empty()- || [&b["name"], &b["lastMessage"]]- .iter()- .any(|v| v.as_str().is_some_and(|s| s.to_lowercase().contains(&q)))- })- .collect();- while let Some(c) = ui.roster.first_child() {- ui.roster.remove(&c);- }- ui.roster_empty.set_visible(bots.is_empty());- ui.roster_empty.set_markup(if q.is_empty() {- "<span weight=\"500\" size=\"13pt\">No bots yet</span>\n<span size=\"12pt\" alpha=\"60%\">Use + to start a new chat.</span>"- } else {- "<span weight=\"500\" size=\"13pt\">No matching bots</span>\n<span size=\"12pt\" alpha=\"60%\">Try another name or message.</span>"- });- for b in bots {- let id = b["id"].as_str().unwrap_or_default();- let unread = b["unread"].as_i64().unwrap_or(0);- let row_box = gtk::Box::builder().spacing(8).build();- row_box.append(&avatar::with_status(&st.bots, b, 30));- let text = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(1)- .hexpand(true)- .valign(gtk::Align::Center)- .build();- let top = gtk::Box::builder().spacing(4).build();- if b["pinned"] == true {- let pin = gtk::Image::from_icon_name("view-pin-symbolic");- pin.set_pixel_size(10);- pin.add_css_class("tertiary");- top.append(&pin);- }- let name = label(b["name"].as_str().unwrap_or(""), &["name"]);- name.set_ellipsize(gtk::pango::EllipsizeMode::End);- top.append(&name);- text.append(&top);- let bottom = gtk::Box::builder().spacing(6).build();- bottom.append(&preview(&st, b));- if unread > 0 {- bottom.append(&label(&unread.to_string(), &["badge"]));- }- text.append(&bottom);- row_box.append(&text);- let row = gtk::ListBoxRow::builder()- .child(&row_box)- .name(id)- .tooltip_text(b["name"].as_str().unwrap_or(""))- .build();- // Right-click: the conversation menu (Pin, Mark as Read, Edit, …).- let click = gtk::GestureClick::builder()- .button(gtk::gdk::BUTTON_SECONDARY)- .build();- let (ui2, id2, row2) = (ui.clone(), id.to_owned(), row.clone());- click.connect_pressed(move |_, _, x, y| {- dialogs::bot_menu(&ui2, row2.upcast_ref(), Some((x, y)), &id2, true);- });- row.add_controller(click);- ui.roster.append(&row);- if st.current.as_deref() == Some(id) && !st.composing {- ui.roster.select_row(Some(&row));- }- }-}--fn is_chat(e: &Value) -> bool {- match e["kind"].as_str() {- Some("user" | "permission" | "notice") => true,- Some("agent") => e["data"]["final"].as_bool().unwrap_or(false),- _ => false,- }-}--fn visible_entries<'a>(entries: &[&'a Value], streaming: bool) -> Vec<&'a Value> {- let live = entries.last().filter(|e| {- streaming- && e["kind"] == "agent"- && e["data"]["final"] == false- && e["data"]["text"]- .as_str()- .is_some_and(|t| !t.is_empty() && t != "(pass)")- });- entries- .iter()- .copied()- .filter(|e| is_chat(e) || live.is_some_and(|l| l["id"] == e["id"]))- .collect()-}--fn load_older(ui: &App, bot: &str) {- let before = {- let mut st = ui.state.borrow_mut();- if !st.history_busy.insert(bot.to_owned()) {- return;- }- st.entries- .get(bot)- .into_iter()- .flatten()- .filter(|e| {- e["threadId"].is_null()- && !e["id"].as_str().unwrap_or_default().starts_with("local-")- })- .filter_map(|e| e["seq"].as_i64())- .min()- .unwrap_or(i64::MAX)- };- schedule(ui);- let (ui, bot) = (ui.clone(), bot.to_owned());- client::call(- "history",- json!({"botId": bot, "beforeSeq": before, "limit": 200}),- move |result| {- let adjust = ui.scroller.vadjustment();- let (height, position) = (adjust.upper(), adjust.value());- let mut st = ui.state.borrow_mut();- st.history_busy.remove(&bot);- match result {- Ok(v) => {- let entries = v["entries"].as_array().cloned().unwrap_or_default();- if entries.len() < 200 {- st.history_done.insert(bot.clone());- }- for entry in entries {- upsert(&mut st, entry);- }- }- Err(error) => toast(&ui, &error),- }- let selected = st.current.as_deref() == Some(bot.as_str());- drop(st);- render(&ui);- if selected {- gtk::glib::idle_add_local_once(move || {- if ui.state.borrow().current.as_deref() == Some(bot.as_str()) {- adjust.set_value(position + (adjust.upper() - height).max(0.0));- }- });- }- },- );-}--pub fn clear(b: >k::Box) {- while let Some(c) = b.first_child() {- b.remove(&c);- }-}--fn near_bottom(s: >k::ScrolledWindow) -> bool {- let adj = s.vadjustment();- adj.upper() - adj.value() - adj.page_size() < 120.0-}--fn scroll_to_end(s: >k::ScrolledWindow) {- // Labels finish wrapping (and the height settles) over the next frames: follow the- // bottom for a moment.- let start = std::time::Instant::now();- s.add_tick_callback(move |s, _| {- let adj = s.vadjustment();- adj.set_value(adj.upper() - adj.page_size());- if start.elapsed() < std::time::Duration::from_millis(800) {- gtk::glib::ControlFlow::Continue- } else {- gtk::glib::ControlFlow::Break- }- });-}--/// The start of an empty chat: who it is and how it works (IntroCard / GroupIntroCard).-fn intro(st: &State, bot: &Value) -> gtk::Box {- let col = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(12)- .margin_top(40)- .margin_start(24)- .margin_end(24)- .build();- col.append(&avatar::of(&st.bots, bot, 72, true));- let centered = |text: &str, classes: &[&str]| {- let l = label(text, classes);- l.set_xalign(0.5);- l.set_wrap(true);- l.set_justify(gtk::Justification::Center);- l- };- col.append(¢ered(bot["name"].as_str().unwrap_or(""), &["title2"]));- let desc = bot["description"].as_str().unwrap_or("");- if is_group(bot) {- col.append(¢ered(&member_names(st, bot), &["small", "secondary"]));- if !desc.is_empty() {- col.append(¢ered(desc, &["small", "secondary"]));- }- let tip = centered(- "Everyone answers in turn. @mention a bot to ask just that one. Each bot works in its own folder.",- &["footnote", "tertiary"],- );- tip.set_margin_top(4);- col.append(&tip);- } else {- col.append(¢ered(- &format!(- "{} in {}",- backend_name(st, bot["backend"].as_str().unwrap_or("")),- if bot["managedWorkspace"] == true {- "its personal workspace"- } else {- bot["cwd"].as_str().unwrap_or("")- }- ),- &["footnote", "mono", "tertiary"],- ));- if !desc.is_empty() {- col.append(¢ered(desc, &["small", "secondary"]));- }- let tip = centered(- "Tell it what you need. You'll get a notification when it's done or needs you.",- &["footnote", "tertiary"],- );- tip.set_margin_top(4);- col.append(&tip);- }- col-}--fn render_chat(ui: &App) {- let st = ui.state.borrow();- let Some(bot) = st.current.as_ref().and_then(|id| st.bots.get(id)) else {- ui.content_stack.set_visible_child_name("empty");- return;- };- let id = bot["id"].as_str().unwrap_or_default();- ui.content_stack.set_visible_child_name("chat");- let switched = *ui.shown_bot.replace(id.to_owned()) != *id;- let stick = switched || near_bottom(&ui.scroller);- ui.head_name.set_label(bot["name"].as_str().unwrap_or(""));- clear(&ui.head_avatar);- ui.head_avatar.append(&avatar::of(&st.bots, bot, 22, true));-- clear(&ui.chat_list);- let entries: Vec<&Value> = st- .entries- .get(id)- .map(|l| l.iter().filter(|e| e["threadId"].is_null()).collect())- .unwrap_or_default();- if !st.history_done.contains(id)- && entries- .iter()- .any(|e| e["seq"].as_i64().is_some_and(|n| n > 1 && n < i64::MAX))- {- let earlier = gtk::Button::with_label(if st.history_busy.contains(id) {- "Loading…"- } else {- "Load earlier messages"- });- earlier.set_sensitive(!st.history_busy.contains(id));- let (ui2, id) = (ui.clone(), id.to_owned());- earlier.connect_clicked(move |_| load_older(&ui2, &id));- ui.chat_list.append(&earlier);- }- if !entries.iter().any(|e| is_chat(e)) {- ui.chat_list.append(&intro(&st, bot));- }- append_entries(ui, &st, &ui.chat_list, bot, &entries, true);- if working_in(bot, id, None) && st.online {- ui.chat_list.append(&rows::working(ui, bot));- }- update_composer_for(ui, &st, bot, false);- if stick {- scroll_to_end(&ui.scroller);- }- if switched {- ui.compose.view.grab_focus();- }-}--/// The right side of a chat: an open thread, else the details panel (unless closed).-fn render_side(ui: &App) {- let st = ui.state.borrow();- let Some(bot) = st.current.as_ref().and_then(|id| st.bots.get(id)) else {- ui.shown_thread.replace(String::new());- return;- };- let thread = st.open_thread.clone();- let details = !st.hide_details && thread.is_none();- ui.details_btn.set_visible(st.hide_details);- let open = thread.is_some() || details;- // The window's own buttons move into whatever is rightmost.- ui.chat_header.set_show_end_title_buttons(!open);- layout_side(ui, thread.is_some());- ui.side.set_reveal_child(open);- if details {- ui.side_stack.set_visible_child_name("details");- render_details(ui, &st, bot);- }- match thread {- Some(root) => {- ui.side_stack.set_visible_child_name("thread");- render_thread(ui, &st, bot, &root);- }- None => {- ui.shown_thread.replace(String::new());- }- }-}--fn render_details(ui: &App, st: &State, bot: &Value) {- let c = &ui.details_content;- clear(c);- let group = is_group(bot);- ui.details_gear- .set_tooltip_text(Some(if group { "Edit group" } else { "Bot settings" }));- if group {- let list = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(2)- .build();- let ms = members(st, bot);- let title = label(&format!("{} bots", ms.len()), &["body13", "semibold"]);- title.set_margin_bottom(6);- list.append(&title);- for m in ms {- let row = gtk::Box::builder()- .spacing(10)- .margin_top(6)- .margin_bottom(6)- .build();- row.append(&avatar::of(&st.bots, m, 26, true));- let text = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(1)- .build();- text.append(&label(m["name"].as_str().unwrap_or(""), &["body13"]));- let sub = if working(m) {- m["activity"]- .as_str()- .filter(|s| !s.is_empty())- .unwrap_or("Working…")- .to_owned()- } else {- folder(m)- };- let s = label(&sub, &["small", "tertiary"]);- s.set_ellipsize(gtk::pango::EllipsizeMode::End);- text.append(&s);- row.append(&text);- let name = m["name"].as_str().unwrap_or("");- let btn = gtk::Button::builder()- .child(&row)- .css_classes(["plain"])- .tooltip_text(format!("Open {name}'s own chat"))- .build();- let (ui2, mid) = (ui.clone(), m["id"].as_str().unwrap_or_default().to_owned());- btn.connect_clicked(move |_| select(&ui2, &mid));- list.append(&btn);- }- c.append(&list);- return;- }- let id = bot["id"].as_str().unwrap_or_default();- let screen = &st.screen;- let status = if !st.online {- "Computer is offline"- } else if screen["enabled"] != true {- "Remote screen is off"- } else if screen["connected"] != true {- "Connecting to computer…"- } else if screen["agentBot"] == id {- "This bot is using your computer"- } else {- "Ready · View this computer from your iPhone"- };- let computer = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(12)- .css_classes(["details-box"])- .height_request(164)- .build();- let icon = gtk::Image::from_icon_name("computer-symbolic");- icon.set_pixel_size(32);- let s = label(status, &["small", "secondary"]);- s.set_xalign(0.5);- s.set_wrap(true);- s.set_justify(gtk::Justification::Center);- // Centered in the 164 pt box.- computer.append(>k::Box::builder().vexpand(true).build());- computer.append(&icon);- computer.append(&s);- computer.append(>k::Box::builder().vexpand(true).build());- let top = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(12)- .build();- top.append(&computer);- let host = label(- st.hello["name"].as_str().unwrap_or(""),- &["footnote", "tertiary"],- );- host.set_xalign(0.5);- top.append(&host);- c.append(&top);- let agent = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(8)- .build();- agent.append(&label("Agent", &["body13", "semibold"]));- agent.append(&label(- &backend_name(st, bot["backend"].as_str().unwrap_or("")),- &["body13", "secondary"],- ));- let cwd = label(bot["cwd"].as_str().unwrap_or(""), &["secondary"]);- cwd.set_selectable(true);- cwd.set_wrap(true);- cwd.set_wrap_mode(gtk::pango::WrapMode::WordChar);- agent.append(&cwd);- if let Some(d) = bot["description"].as_str().filter(|d| !d.is_empty()) {- let l = label(d, &["body13", "secondary"]);- l.set_wrap(true);- agent.append(&l);- }- c.append(&agent);-}--/// The thread open beside the chat: its root, the replies and a composer that replies there.-fn render_thread(ui: &App, st: &State, bot: &Value, root_id: &str) {- let id = bot["id"].as_str().unwrap_or_default();- ui.pane_sub.set_label(bot["name"].as_str().unwrap_or(""));- let switched = *ui.shown_thread.replace(root_id.to_owned()) != *root_id;- let stick = switched || near_bottom(&ui.pane_scroller);- clear(&ui.pane_list);- let all = st.entries.get(id).map(Vec::as_slice).unwrap_or_default();- let replies: Vec<&Value> = all.iter().filter(|e| e["threadId"] == root_id).collect();- if let Some(root) = all.iter().find(|e| e["id"] == root_id) {- append_entries(ui, st, &ui.pane_list, bot, &[root], false);- let n = replies.iter().filter(|e| is_chat(e)).count();- let div = gtk::Box::builder()- .spacing(10)- .margin_top(12)- .margin_bottom(12)- .build();- div.append(&label(- &match n {- 0 => "No replies yet".to_owned(),- 1 => "1 reply".to_owned(),- _ => format!("{n} replies"),- },- &["footnote", "tertiary"],- ));- let line = hline();- line.set_hexpand(true);- line.set_valign(gtk::Align::Center);- div.append(&line);- ui.pane_list.append(&div);- }- append_entries(ui, st, &ui.pane_list, bot, &replies, false);- if working_in(bot, id, Some(root_id)) && st.online {- ui.pane_list.append(&rows::working(ui, bot));- }- update_composer_for(ui, st, bot, true);- if stick {- scroll_to_end(&ui.pane_scroller);- }- if switched {- ui.reply.view.grab_focus();- }-}--/// Wide windows keep the thread in a side pane; narrow ones let it cover the chat,-/// with a back button in place of close.-fn layout_side(ui: &App, thread: bool) {- let cover = thread && ui.narrow.get();- ui.convo.set_visible(!cover);- ui.side.set_hexpand(cover);- ui.pane_box.set_hexpand(cover);- ui.pane_box.set_width_request(if cover { -1 } else { 420 });- ui.thread_back.set_visible(cover);- ui.close_thread.set_visible(!cover);-}--/// Chat-visible entries with time separators (gaps > 1 h, main chat) and author grouping.-/// `main`: the main chat, where messages can start threads and show their summary.-fn append_entries(- ui: &App,- st: &State,- list: >k::Box,- chat: &Value,- entries: &[&Value],- main: bool,-) {- let group = is_group(chat);- let mut last_author = String::new();- let mut last_time: Option<i64> = None;- let thread = if main {- None- } else {- st.open_thread.as_deref()- };- let streaming = st.online && working_in(chat, chat["id"].as_str().unwrap_or_default(), thread);- for e in visible_entries(entries, streaming) {- let at = e["createdAt"].as_i64().unwrap_or(0);- if main && last_time.is_none_or(|t| at - t > 3_600_000) {- let sep = label(&rows::separator(at), &["footnote", "tertiary"]);- sep.set_xalign(0.5);- sep.set_margin_top(18);- sep.set_margin_bottom(6);- list.append(&sep);- last_author.clear();- }- last_time = Some(at);- let kind = e["kind"].as_str().unwrap_or_default();- // In a group each bot is its own author.- let author = match kind {- "agent" => format!("agent:{}", e["data"]["author"].as_str().unwrap_or("")),- k => k.to_owned(),- };- let start = author != last_author;- last_author = if kind == "user" || kind == "agent" {- author- } else {- String::new()- };- let entry_id = e["id"].as_str().unwrap_or_default();- // Local echoes have no id on the host yet.- let r = Reply {- ui,- root: (main && !entry_id.starts_with("local-")).then_some(entry_id),- };- match kind {- "user" => list.append(&user_bubble(&r, e, working(chat), start)),- "agent" => list.append(&agent_bubble(&r, st, e, group, start)),- "permission" => list.append(&permission_card(ui, st, e, group)),- _ if e["data"]["connectionRequest"].is_object() => {- list.append(&crate::connections::card(ui, e))- }- _ => list.append(¬ice(e)),- }- let indent = if group && kind == "agent" { 34 } else { 0 };- if main && let Some(chip) = thread_chip(ui, st, e, kind == "user", indent) {- list.append(&chip);- }- }-}--/// Starts (or opens) the thread on a main-chat message and pages in its replies.-pub fn open_thread(ui: &App, root: &str) {- let Some(bot) = ui.state.borrow().current.clone() else {- return;- };- ui.state.borrow_mut().open_thread = Some(root.to_owned());- schedule(ui);- mark_read(ui);- let ui2 = ui.clone();- client::call(- "thread",- json!({"botId": bot, "rootId": root}),- move |r| match r {- Ok(v) => {- let mut st = ui2.state.borrow_mut();- for e in v["entries"].as_array().into_iter().flatten() {- upsert(&mut st, e.clone());- }- drop(st);- schedule(&ui2);- }- Err(e) => toast(&ui2, &e),- },- );-}--fn update_composer(ui: &App, in_thread: bool) {- let st = ui.state.borrow();- if let Some(bot) = st.current.as_ref().and_then(|id| st.bots.get(id)) {- update_composer_for(ui, &st, bot, in_thread);- }-}--fn update_composer_for(ui: &App, st: &State, chat: &Value, in_thread: bool) {- let c = ui.composer(in_thread);- let buf = c.view.buffer();- let text = buf- .text(&buf.start_iter(), &buf.end_iter(), false)- .to_string();- let has_text = !text.trim().is_empty() || !c.files.borrow().is_empty();- let lane = if in_thread {- st.open_thread.as_deref()- } else {- None- };- let busy = working_in(chat, chat["id"].as_str().unwrap_or_default(), lane);- let name = chat["name"].as_str().unwrap_or("");- c.placeholder.set_label(&if in_thread {- "Reply…".to_owned()- } else if is_group(chat) {- format!("Message {name} · @ to ask one bot")- } else if busy {- format!("Queue a message for {name}")- } else {- format!("Message {name}")- });- c.placeholder.set_visible(text.is_empty());- c.attach_btn.set_visible(!is_group(chat));- c.stop_btn.set_visible(busy && !has_text);- c.send_btn.set_visible(!busy || has_text);- c.send_btn.set_sensitive(has_text);-- // `@` suggests the group's bots.- clear(&c.mentions);- let mut any = false;- if is_group(chat)- && let Some(q) = mention_query(&text)- {- let q = q.to_lowercase();- for m in members(st, chat) {- let name = m["name"].as_str().unwrap_or_default().to_owned();- if !name.to_lowercase().contains(&q) {- continue;- }- let inner = gtk::Box::builder().spacing(6).build();- inner.append(&avatar::of(&st.bots, m, 18, false));- inner.append(&label(&name, &["small"]));- let chip = gtk::Button::builder()- .child(&inner)- .tooltip_text(format!("Ask {name}"))- .css_classes(["mention-chip"])- .build();- let (buf2, view, text2) = (buf.clone(), c.view.clone(), text.clone());- chip.connect_clicked(move |_| {- if let Some(at) = text2.rfind('@') {- buf2.set_text(&format!("{}@{name} ", &text2[..at]));- buf2.place_cursor(&buf2.end_iter());- view.grab_focus();- }- });- c.mentions.append(&chip);- any = true;- }- }- c.mentions_rev.set_reveal_child(any);-}--/// Puts text in the chat's message box (after what's already typed) and focuses it.-pub fn insert_draft(ui: &App, text: &str) {- let view = &ui.composer(false).view;- let buf = view.buffer();- if buf.char_count() > 0 {- buf.insert(&mut buf.end_iter(), "\n");- }- buf.insert(&mut buf.end_iter(), text);- view.grab_focus();-}--fn send(ui: &App, in_thread: bool) {- let buf = ui.composer(in_thread).view.buffer();- let text = buf- .text(&buf.start_iter(), &buf.end_iter(), false)- .trim()- .to_owned();- let (bot, thread) = {- let st = ui.state.borrow();- let thread = if in_thread {- st.open_thread.clone()- } else {- None- };- (st.current.clone(), thread)- };- let Some(bot) = bot else {- return;- };- let c = ui.composer(in_thread);- if (text.is_empty() && c.files.borrow().is_empty()) || (in_thread && thread.is_none()) {- return;- }- if blocked_by_update(ui) {- // The draft stays; it sends once the update is done.- return;- }- let files = c.files.take();- buf.set_text("");- show_files(ui, in_thread);- send_text(ui, &bot, &text, thread, files);-}--/// Sends a message with a local echo that the host's copy replaces.-pub fn send_text(- ui: &App,- bot: &str,- text: &str,- thread: Option<String>,- files: Vec<std::path::PathBuf>,-) {- send_outgoing(- ui,- Outgoing {- bot: bot.to_owned(),- text: text.to_owned(),- thread,- files,- },- uuid::Uuid::new_v4().to_string(),- );-}--pub fn retry(ui: &App, nonce: &str) {- let outgoing = ui.state.borrow().outbox.get(nonce).cloned();- if let Some(outgoing) = outgoing {- send_outgoing(ui, outgoing, nonce.to_owned());- }-}--pub fn discard(ui: &App, nonce: &str) {- let mut st = ui.state.borrow_mut();- if let Some(outgoing) = st.outbox.remove(nonce)- && let Some(entries) = st.entries.get_mut(&outgoing.bot)- {- entries.retain(|e| e["id"] != format!("local-{nonce}"));- }- drop(st);- schedule(ui);-}--fn send_outgoing(ui: &App, outgoing: Outgoing, nonce: String) {- ui.state- .borrow_mut()- .outbox- .insert(nonce.clone(), outgoing.clone());- let Outgoing {- bot,- text,- thread,- files,- } = outgoing;-- let attachments: Vec<Value> = files- .iter()- .map(|p| {- let size = std::fs::metadata(p).map_or(0, |m| m.len());- json!({"name": p.file_name().map(|n| n.to_string_lossy()), "size": size})- })- .collect();- upsert(- &mut ui.state.borrow_mut(),- json!({"id": format!("local-{nonce}"), "seq": i64::MAX, "botId": bot, "threadId": thread, "rev": 0, "kind": "user", "turn": 0,- "data": {"text": text, "status": "sending", "clientNonce": nonce, "attachments": attachments},- "createdAt": now_ms(), "updatedAt": 0}),- );- schedule(ui);- let mut body = json!({"botId": bot, "text": text, "clientNonce": nonce});- if let Some(t) = thread {- body["threadId"] = t.into();- }- let (ui2, bot) = (ui.clone(), bot.to_owned());- let done = move |r: Result<Value, String>| {- if let Err(err) = &r {- toast(&ui2, err);- }- let mut st = ui2.state.borrow_mut();- match r {- Ok(v) => upsert(&mut st, v["entry"].clone()),- 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);- };- if files.is_empty() {- client::call("send", body, done);- } else {- client::send_files(body, files, done);- }-}--pub fn now_ms() -> i64 {- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))-}--pub fn mark_read(ui: &App) {- let st = ui.state.borrow();- if let Some(bot) = st.current.as_ref().and_then(|id| st.bots.get(id))- && bot["unread"].as_i64().unwrap_or(0) > 0- {- client::call(- "markRead",- json!({"botId": bot["id"], "threadId": st.open_thread}),- |_| {},- );- }-}--pub fn toast(ui: &App, text: &str) {- ui.toasts.add_toast(adw::Toast::new(text));-}--// MARK: menus--/// One row of a floating menu panel.-pub struct MenuItem {- icon: &'static str,- title: String,- chevron: bool,- destructive: bool,- divider: bool,- action: Box<dyn Fn()>,-}--impl MenuItem {- pub fn new(icon: &'static str, title: &str, action: Box<dyn Fn()>) -> Self {- Self {- icon,- title: title.to_owned(),- chevron: false,- destructive: false,- divider: false,- action,- }- }- pub fn chevron(mut self) -> Self {- self.chevron = true;- self- }- pub fn destructive(mut self) -> Self {- self.destructive = true;- self- }- /// A line above this row.- pub fn divider(mut self) -> Self {- self.divider = true;- self- }-}--/// A floating panel of rows (DesktopActionMenu): at `point` inside `parent`, or under it.-pub fn popup_menu(parent: &impl IsA<gtk::Widget>, point: Option<(f64, f64)>, items: Vec<MenuItem>) {- let pop = gtk::Popover::builder()- .has_arrow(false)- .css_classes(["panel"])- .build();- if let Some((x, y)) = point {- pop.set_pointing_to(Some(>k::gdk::Rectangle::new(x as i32, y as i32, 1, 1)));- pop.set_position(gtk::PositionType::Bottom);- }- let col = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(2)- .width_request(246)- .build();- for item in items {- if item.divider {- col.append(>k::Box::builder().css_classes(["menu-divider"]).build());- }- let row = gtk::Box::builder().spacing(8).build();- let icon = gtk::Image::from_icon_name(item.icon);- icon.set_pixel_size(14);- icon.set_width_request(20);- row.append(&icon);- let t = label(&item.title, &[]);- t.set_hexpand(true);- row.append(&t);- if item.chevron {- let c = gtk::Image::from_icon_name("go-next-symbolic");- c.set_pixel_size(11);- c.add_css_class("secondary");- row.append(&c);- }- let btn = gtk::Button::builder()- .child(&row)- .css_classes(["menu-row"])- .build();- if item.destructive {- btn.add_css_class("danger-text");- }- let pop2 = pop.clone();- let action = item.action;- btn.connect_clicked(move |_| {- pop2.popdown();- action();- });- col.append(&btn);- }- pop.set_child(Some(&col));- // Rows re-render often; the popover lives only while shown.- pop.connect_closed(|p| {- let p = p.clone();- gtk::glib::idle_add_local_once(move || p.unparent());- });- pop.set_parent(parent);- pop.popup();-}--#[cfg(test)]-mod tests {- use super::mention_query;-- #[test]- fn streaming_shows_only_the_active_last_segment() {- use super::*;- let old = json!({"id":"old","kind":"agent","data":{"text":"thinking","final":false}});- let final_reply = json!({"id":"final","kind":"agent","data":{"text":"done","final":true}});- let live = json!({"id":"live","kind":"agent","data":{"text":"new reply","final":false}});- let tool = json!({"id":"tool","kind":"tool"});- assert_eq!(- visible_entries(&[&old, &final_reply, &live], true),- [&final_reply, &live]- );- assert_eq!(- visible_entries(&[&old, &final_reply, &live], false),- [&final_reply]- );- assert_eq!(- visible_entries(&[&old, &final_reply, &live, &tool], true),- [&final_reply]- );- let pass = json!({"id":"pass","kind":"agent","data":{"text":"(pass)","final":false}});- assert!(visible_entries(&[&pass], true).is_empty());- }-- #[test]- fn loading_history_retains_old_pages_and_newer_revisions() {- use super::*;- let mut state = State::default();- for seq in (1..=600).rev() {- upsert(- &mut state,- json!({"botId":"b","id":format!("e{seq}"),"seq":seq,"rev":10}),- );- }- upsert(&mut state, json!({"botId":"b","id":"e1","seq":1,"rev":1}));- assert_eq!(state.entries["b"].len(), 600);- assert_eq!(state.entries["b"][0]["rev"], 10);- }-- #[test]- fn host_acknowledgement_replaces_failed_echo_and_releases_outbox() {- use super::*;- let mut state = State::default();- state.outbox.insert(- "nonce".into(),- Outgoing {- bot: "b".into(),- text: "hi".into(),- thread: None,- files: vec![],- },- );- upsert(- &mut state,- json!({"botId":"b","id":"local-nonce","seq":i64::MAX,"kind":"user","data":{"clientNonce":"nonce","status":"failed"}}),- );- upsert(- &mut state,- json!({"botId":"b","id":"server","seq":1,"kind":"user","data":{"clientNonce":"nonce"}}),- );- assert_eq!(state.entries["b"].len(), 1);- assert_eq!(state.entries["b"][0]["id"], "server");- assert!(state.outbox.is_empty());- }-- #[test]- fn mentions() {- assert_eq!(mention_query("hi @al"), Some("al"));- assert_eq!(mention_query("@"), Some(""));- assert_eq!(mention_query("mail me@home"), None);- assert_eq!(mention_query("no at"), None);- assert_eq!(mention_query("@al\nnext"), None);- }-}--#[cfg(test)]-#[path = "ui_tests.rs"]-mod ui_tests;diff --git a/apps/linux/src/ui_tests.rs b/apps/linux/src/ui_tests.rsdeleted file mode 100644index c948ef00..00000000--- a/apps/linux/src/ui_tests.rs+++ /dev/null@@ -1,325 +0,0 @@-//! Native widget integration tests, run under Xvfb with tests/ui_fixture.py.-use super::*;-use std::time::{Duration, Instant};--#[track_caller]-fn wait(mut ready: impl FnMut() -> bool) {- let deadline = Instant::now() + Duration::from_secs(10);- loop {- while gtk::glib::MainContext::default().pending() {- gtk::glib::MainContext::default().iteration(false);- }- if ready() {- return;- }- if Instant::now() >= deadline {- if let Ok(dir) = std::env::var("CODYNC_UI_ARTIFACTS") {- let _ = std::fs::create_dir_all(&dir);- let _ = std::process::Command::new("import")- .args(["-window", "root", &format!("{dir}/failure.png")])- .status();- }- panic!("native UI did not reach the expected state");- }- std::thread::sleep(Duration::from_millis(10));- }-}-fn widgets(root: &impl IsA<gtk::Widget>) -> Vec<gtk::Widget> {- let root = root.as_ref();- let mut result = vec![root.clone()];- let mut child = root.first_child();- while let Some(widget) = child {- result.extend(widgets(&widget));- child = widget.next_sibling();- }- result-}-fn button(root: &impl IsA<gtk::Widget>, name: &str) -> Option<gtk::Button> {- widgets(root)- .into_iter()- .filter_map(|w| w.downcast::<gtk::Button>().ok())- .find(|b| b.label().as_deref() == Some(name) || b.tooltip_text().as_deref() == Some(name))-}-fn text(root: &impl IsA<gtk::Widget>, value: &str) -> bool {- widgets(root)- .into_iter()- .filter_map(|w| w.downcast::<gtk::Label>().ok())- .any(|l| l.text().contains(value))-}-#[track_caller]-fn click(root: &impl IsA<gtk::Widget>, name: &str) {- wait(|| button(root, name).is_some_and(|b| b.is_sensitive()));- let button = button(root, name).unwrap();- wait(|| button.is_mapped());- // libadwaita 1.5 opens a newly mapped dialog on its second frame.- // Emitting clicks before that can save and close a dialog before it opens.- let frames = Rc::new(std::cell::Cell::new(0));- let frames2 = frames.clone();- button.add_tick_callback(move |_, _| {- frames2.set(frames2.get() + 1);- if frames2.get() >= 3 {- gtk::glib::ControlFlow::Break- } else {- gtk::glib::ControlFlow::Continue- }- });- wait(|| frames.get() >= 3);- button.emit_clicked();-}-fn close(ui: &App) {- if let Some(dialog) = ui.window.visible_dialog() {- dialog.force_close();- wait(|| ui.window.visible_dialog().as_ref() != Some(&dialog));- }-}-fn screenshot(name: &str) {- if let Ok(dir) = std::env::var("CODYNC_UI_ARTIFACTS") {- let deadline = Instant::now() + Duration::from_millis(400);- wait(|| Instant::now() > deadline);- std::fs::create_dir_all(&dir).unwrap();- assert!(- std::process::Command::new("import")- .args(["-window", "root", &format!("{dir}/{name}.png")])- .status()- .unwrap()- .success()- );- }-}-fn requests() -> Value {- let result = Rc::new(RefCell::new(None));- let result2 = result.clone();- client::call("_testState", json!({}), move |r| {- *result2.borrow_mut() = Some(r.unwrap());- });- wait(|| result.borrow().is_some());- result.borrow_mut().take().unwrap()-}--#[test]-#[ignore = "run under Xvfb using tests/ui_fixture.py"]-fn native_ui_flows() {- assert_eq!(std::env::var("CODYNC_UI_TEST").as_deref(), Ok("1"));- adw::init().unwrap();- // Exercise actions after their dialog is ready, without racing presentation animations.- gtk::Settings::default()- .unwrap()- .set_gtk_enable_animations(false);- let app = adw::Application::builder()- .application_id("com.pokai.Codync.ParityTest")- .build();- app.register(None::<>k::gio::Cancellable>).unwrap();- let display = gtk::gdk::Display::default().unwrap();- let css = gtk::CssProvider::new();- css.load_from_string(&format!("{}\n{}", crate::colors(&crate::DARK), crate::CSS));- gtk::style_context_add_provider_for_display(- &display,- &css,- gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,- );- adw::StyleManager::default().set_color_scheme(adw::ColorScheme::ForceDark);- let ui = build(&app);- wait(|| {- ui.state- .borrow()- .entries- .get("bot")- .is_some_and(|e| e.len() == 2)- });- select(&ui, "bot");- wait(|| text(&ui.chat_list, "Streaming fixture answer"));- click(&ui.chat_list, "Load earlier messages");- wait(|| text(&ui.chat_list, "Older fixture message"));- assert!(text(&ui.chat_list, "Streaming fixture answer"));- screenshot("linux-chat-streaming");-- send_text(&ui, "bot", "Retry this message", None, vec![]);- wait(|| text(&ui.chat_list, "Failed to send"));- click(&ui.chat_list, "Resend");- wait(|| ui.state.borrow().outbox.is_empty());- assert_eq!(- ui.state.borrow().entries["bot"]- .iter()- .filter(|e| e["data"]["text"] == "Retry this message")- .count(),- 1- );- let sent: Vec<_> = requests()["requests"]- .as_array()- .unwrap()- .iter()- .filter(|r| r[0] == "send")- .cloned()- .collect();- assert_eq!(sent.len(), 2);- assert_eq!(sent[0][1]["clientNonce"], sent[1][1]["clientNonce"]);-- click(&ui.chat_list, "Remove reaction");- wait(|| {- requests()["requests"]- .as_array()- .unwrap()- .iter()- .any(|r| r[0] == "react")- });- click(&ui.chat_list, "Save attachment");- wait(|| {- requests()["requests"]- .as_array()- .unwrap()- .iter()- .any(|r| r[0] == "readUpload")- });-- let downloads = std::path::PathBuf::from(std::env::var("CODYNC_UI_DOWNLOADS").unwrap());- wait(|| std::fs::read(downloads.join("parity.txt")).ok().as_deref() == Some(b"fixture"));- click(&ui.chat_list, "Save attachment");- wait(|| {- std::fs::read(downloads.join("1-parity.txt"))- .ok()- .as_deref()- == Some(b"fixture")- });- assert_eq!(- std::fs::read(downloads.join("parity.txt")).unwrap(),- b"fixture"- );- send_text(&ui, "bot", "Discard this message", None, vec![]);- wait(|| text(&ui.chat_list, "Failed to send"));- click(&ui.chat_list, "Delete");- wait(|| !text(&ui.chat_list, "Discard this message"));-- crate::manage::memory(&ui, "bot");- let memory = ui.window.visible_dialog().unwrap();- wait(|| text(&memory, "Prefers native interfaces"));- screenshot("linux-memory");- click(&memory, "Forget");- wait(|| text(&memory, "Nothing yet"));- close(&ui);-- crate::manage::routines(&ui, "bot");- let routines = ui.window.visible_dialog().unwrap();- wait(|| text(&routines, "No routines yet"));- click(&routines, "Ask the bot for a routine");- wait(|| ui.window.visible_dialog().is_none());- let buf = ui.compose.view.buffer();- assert!(- buf.text(&buf.start_iter(), &buf.end_iter(), false)- .contains("I want a routine that")- );- buf.set_text("");-- crate::manage::routines(&ui, "bot");- let routines = ui.window.visible_dialog().unwrap();- click(&routines, "Set up a routine");- let editor = ui.window.visible_dialog().unwrap();- let entries: Vec<_> = widgets(&editor)- .into_iter()- .filter_map(|w| w.downcast::<gtk::Entry>().ok())- .collect();- entries[0].set_text("Morning review");- let instruction = widgets(&editor)- .into_iter()- .find_map(|w| w.downcast::<gtk::TextView>().ok())- .unwrap();- instruction.buffer().set_text("Review the latest changes");- click(&editor, "Preview schedule");- wait(|| text(&editor, "Daily at 09:00 UTC"));- screenshot("linux-routine-editor");- click(&editor, "Save");- wait(|| text(&routines, "Morning review"));- let switch = widgets(&routines)- .into_iter()- .find_map(|w| w.downcast::<gtk::Switch>().ok())- .unwrap();- switch.set_active(false);- wait(|| {- widgets(&routines)- .into_iter()- .filter_map(|w| w.downcast::<gtk::Switch>().ok())- .any(|s| !s.is_active())- });- screenshot("linux-routines");-- // A new webhook routine reopens on its public URL and key.- click(&routines, "Set up a routine");- let editor = ui.window.visible_dialog().unwrap();- let entries: Vec<_> = widgets(&editor)- .into_iter()- .filter_map(|w| w.downcast::<gtk::Entry>().ok())- .collect();- entries[0].set_text("Deploy hook");- widgets(&editor)- .into_iter()- .find_map(|w| w.downcast::<gtk::TextView>().ok())- .unwrap()- .buffer()- .set_text("Summarize the deploy");- widgets(&editor)- .into_iter()- .find_map(|w| w.downcast::<gtk::DropDown>().ok())- .unwrap()- .set_selected(1);- click(&editor, "Save");- wait(|| {- ui.window.visible_dialog().is_some_and(|d| {- d != editor && d != routines && text(&d, "https://cloud.example/v1/hooks/c/hook")- })- });- let hook = ui.window.visible_dialog().unwrap();- assert!(!text(&hook, "fixture-key"), "the key starts hidden");- click(&hook, "Show key");- wait(|| text(&hook, "fixture-key-0123456789abcdef0123456789"));- screenshot("linux-routine-webhook");- close(&ui);- close(&ui);-- crate::market::open(&ui);- let market = ui.window.visible_dialog().unwrap();- wait(|| button(&market, "Add").is_some());- screenshot("linux-marketplace");- click(&market, "Add");- wait(|| button(&market, "Remove skill").is_some());- click(&market, "Fixture Agent");- let agent = ui.window.visible_dialog().unwrap();- click(&agent, "API key");- let credentials = ui.window.visible_dialog().unwrap();- let entry = widgets(&credentials)- .into_iter()- .find_map(|w| w.downcast::<gtk::Entry>().ok())- .unwrap();- assert!(!gtk::prelude::EntryExt::is_visible(&entry)); // GtkEditable visibility masks the credential.- entry.set_text("fixture-key");- click(&credentials, "Save and sign in");- wait(|| ui.window.visible_dialog().as_ref() == Some(&agent));- click(&agent, "Sign in in terminal");- let terminal = ui.window.visible_dialog().unwrap();- wait(|| text(&terminal, "Running on your computer"));- screenshot("linux-agent-terminal");- close(&ui);- close(&ui);- close(&ui);- let log = requests();- for method in [- "history",- "react",- "readUpload",- "forgetMemory",- "saveRoutine",- "setRoutineEnabled",- "installSkill",- "setAgentEnv",- "agentSetup",- "termClose",- ] {- assert!(- log["requests"]- .as_array()- .unwrap()- .iter()- .any(|r| r[0] == method),- "missing {method}"- );- }- ui.window.close();-}diff --git a/apps/linux/tests/ui_fixture.py b/apps/linux/tests/ui_fixture.pydeleted file mode 100644index 8a7e3029..00000000--- a/apps/linux/tests/ui_fixture.py+++ /dev/null@@ -1,141 +0,0 @@-#!/usr/bin/env python3-"""Run the native GTK regression test against a deterministic, isolated host API."""-import base64-import json-import os-import pathlib-import subprocess-import sys-import tempfile-import threading-import time-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer--BOT = dict(id="bot", name="Parity bot", backend="fixture", description="UI regression fixture", cwd="/tmp/project", status="working", workingChat=None, workingThread=None, avatarColor="blue", avatarShape="blob", permission="ask", notify=True, unread=0, lastAt=1, lastMessage="Fixture", kind="bot", computer=True)-BACKEND = dict(id="fixture", name="Fixture Agent", installed=True, available=True, curated=True, canInstall=True)-ENTRIES = [dict(id="user", botId="bot", seq=201, rev=201, turn=1, kind="user", createdAt=1720000000000, threadId=None, data=dict(text="Read this attachment", attachments=[dict(id="file", name="parity.txt", size=7)], reactions=["👍"])), dict(id="live", botId="bot", seq=202, rev=202, turn=1, kind="agent", createdAt=1720000000001, threadId=None, data=dict(text="Streaming fixture answer", final=False))]--class Host(BaseHTTPRequestHandler):- requests = []- facts = [dict(id="fact", content="Prefers native interfaces", kind="profile")]- routines = []- skills = []- attempts = {}- lock = threading.Lock()-- def log_message(self, *_):- pass-- def send_json(self, value, status=200):- body = json.dumps(value).encode()- self.send_response(status)- self.send_header("Content-Type", "application/json")- self.send_header("Content-Length", str(len(body)))- self.end_headers()- self.wfile.write(body)-- def do_POST(self):- body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")- method = self.path.rsplit("/", 1)[-1]- cls = type(self)- with cls.lock:- cls.requests.append([method, body])- if method == "_testState":- return self.send_json(dict(requests=cls.requests))- if method == "hello":- return self.send_json(dict(name="Fixture computer", home="/tmp", version="test", backends=[BACKEND]))- if method == "refreshBackends":- return self.send_json(dict(backends=[BACKEND]))- if method == "screenStatus":- return self.send_json(dict(enabled=True, connected=True))- if method == "history":- return self.send_json(dict(entries=[dict(id="older", botId="bot", seq=1, rev=1, turn=0, kind="user", createdAt=1710000000000, data=dict(text="Older fixture message"))]))- if method == "send":- nonce = body["clientNonce"]- cls.attempts[nonce] = cls.attempts.get(nonce, 0) + 1- if cls.attempts[nonce] == 1:- return self.send_json(dict(error="Fixture connection interrupted"), 503)- return self.send_json(dict(entry=dict(id="sent", botId=body["botId"], threadId=body.get("threadId"), seq=300, rev=300, turn=2, kind="user", createdAt=1720000000002, data=dict(text=body["text"], clientNonce=nonce, status="queued"))))- if method == "readUpload":- return self.send_json(dict(data=base64.b64encode(b"fixture").decode(), size=7))- if method == "memory":- return self.send_json(dict(facts=cls.facts, location="fixture"))- if method in ("forgetMemory", "clearMemory"):- cls.facts = []- if method == "routines":- return self.send_json(dict(routines=cls.routines, runs=[]))- if method == "saveRoutine":- kind = body["schedule"]["kind"]- assert kind in ("cron", "webhook")- assert body["timeoutSeconds"] == 3600- if kind == "cron":- routine = dict(id="routine", name=body["name"], instruction=body["instruction"], enabled=True, triggers=[dict(type="cron", expression="0 9 * * *", timeZone="UTC")], triggerDescriptions=["Daily at 09:00 UTC"], nextRunAt=1820000000000)- else:- routine = dict(id="hook", name=body["name"], instruction=body["instruction"], enabled=True, triggers=[dict(type="webhook")], triggerDescriptions=["When a webhook fires"], nextRunAt=None)- cls.routines = [r for r in cls.routines if r["id"] != routine["id"]] + [routine]- return self.send_json(dict(routine=routine))- if method == "routineWebhook":- key = "rotated-key-0123456789abcdef0123456789" if body.get("rotate") else "fixture-key-0123456789abcdef0123456789"- return self.send_json(dict(url="https://cloud.example/v1/hooks/c/" + body["id"], localUrl="http://127.0.0.1:19222/hooks/routines/" + body["id"], key=key, connected=True))- if method == "routineSchedule":- return self.send_json(dict(summary="Daily at 09:00 UTC", nextRunAt=1820000000000))- if method == "setRoutineEnabled":- for r in cls.routines:- if r["id"] == body["id"]:- r["enabled"] = body["enabled"]- r["nextRunAt"] = 1820000000000 if body["enabled"] and r["id"] == "routine" else None- if method == "deleteRoutine":- cls.routines = []- if method == "skills":- return self.send_json(dict(items=cls.skills))- if method == "marketSkills":- return self.send_json(dict(items=[dict(name="Review code", source="fixture/review", description="Review native UI changes")]))- if method == "installSkill":- cls.skills = [dict(id="skill", name="Review code", source=body["source"])]- if method == "removeSkill":- cls.skills = []- if method == "agentAuth":- return self.send_json(dict(signedIn=False, login=True, methods=[dict(id="env", name="API key", kind="envVar", vars=[dict(name="FIXTURE_KEY", label="API key", secret=True, optional=False)])]))- if method == "agentSetup":- return self.send_json(dict(term="fixture-terminal"))- if method == "setAgentEnv":- return self.send_json(dict(signedIn=True))- if method in ("connectors", "marketConnectors"):- return self.send_json(dict(items=[]))- self.send_json({})-- def do_GET(self):- self.send_response(200)- self.send_header("Content-Type", "text/event-stream")- self.end_headers()- try:- if self.path.startswith("/term/"):- events = [dict(type="output", data=base64.b64encode(b"\x1b[32mFixture terminal ready\x1b[0m\r\n").decode())]- else:- events = [dict(type="bot", rev=1, bot=BOT), dict(type="bot", rev=2, bot={**BOT, "id":"other", "name":"Other bot", "status":"idle"})] + [dict(type="entry", rev=e["rev"], entry=e) for e in ENTRIES]- for event in events:- self.wfile.write(("data: " + json.dumps(event) + "\n\n").encode())- self.wfile.flush()- while True:- time.sleep(0.5)- self.wfile.write(b": keepalive\n\n")- self.wfile.flush()- except (BrokenPipeError, ConnectionResetError):- pass--if __name__ == "__main__":- server = ThreadingHTTPServer(("127.0.0.1", 0), Host)- threading.Thread(target=server.serve_forever, daemon=True).start()- with tempfile.TemporaryDirectory(prefix="codync-ui-fixture-") as directory:- pathlib.Path(directory, "token").write_text("fixture-token")- downloads = pathlib.Path(directory, "downloads")- downloads.mkdir()- config = pathlib.Path(directory, "config")- config.mkdir()- (config / "user-dirs.dirs").write_text(f'XDG_DOWNLOAD_DIR="{downloads}"\n')- env = {**os.environ, "XDG_CONFIG_HOME":str(config), "CODYNC_UI_DOWNLOADS":str(downloads), "CODYNC_HOME":directory, "CODYNC_URL":f"http://127.0.0.1:{server.server_port}", "CODYNC_UI_TEST":"1", "CODYNC_UI_ARTIFACTS":os.environ.get("CODYNC_UI_ARTIFACTS", directory)}- try:- result = subprocess.run(sys.argv[1:] or ["cargo", "test", "native_ui_flows", "--", "--ignored", "--test-threads=1", "--nocapture"], env=env)- finally:- server.shutdown()- sys.exit(result.returncode)diff --git a/apps/macos/App/CodyncMacApp.swift b/apps/macos/App/CodyncMacApp.swiftdeleted file mode 100644index 72a1bb48..00000000--- a/apps/macos/App/CodyncMacApp.swift+++ /dev/null@@ -1,478 +0,0 @@-import CodyncKit-import CodyncUI-import CoreImage.CIFilterBuiltins-import SwiftUI--@main-struct CodyncMacApp: App {- @NSApplicationDelegateAdaptor(CodyncAppDelegate.self) private var appDelegate- @State private var updates = UpdatesManager()- @State private var host: HostController- @State private var account: AccountSession- @Environment(\.openWindow) private var openWindow- @AppStorage(ConversationTypography.preferenceKey)- private var conversationFontSize = ConversationTypography.defaultSize-- init() {- let account = AccountSession()- _account = State(initialValue: account)- _host = State(initialValue: HostController(account: account))- }-- /// From both the window and the menu bar icon: macOS can hide the icon (no room, or not allowed in- /// the menu bar), and its view then never appears. Both starts are no-ops after the first.- private func launch() {- host.start()- appDelegate.updates = updates- updates.start(host: host)- }-- var body: some Scene {- // First scene: the one SwiftUI opens at launch and when the Dock icon is clicked.- Window("Codync", id: "chat") {- ChatWindow()- .environment(\.conversationTypography, ConversationTypography(pointSize: conversationFontSize))- .task { launch() }- .modalHost()- // No scroll bars anywhere in the app (sheets and panels sit inside the modal host).- .scrollIndicators(.never)- .appFont(.body)- .environment(\.appFontScale, ConversationTypography(pointSize: conversationFontSize).scale)- .environment(host)- .environment(account)- .environment(updates)- }- .defaultSize(width: 1100, height: 760)- .windowStyle(.hiddenTitleBar)- .commands {- CommandGroup(after: .toolbar) {- Button("Bigger") { conversationFontSize = ConversationTypography.step(conversationFontSize, up: true) }- .keyboardShortcut("+")- Button("Smaller") { conversationFontSize = ConversationTypography.step(conversationFontSize, up: false) }- .keyboardShortcut("-")- Button("Actual Size") { conversationFontSize = ConversationTypography.defaultSize }- .keyboardShortcut("0")- }- }-- MenuBarExtra {- MenuView()- // The macOS 27 SDK drops menu item images unless the label asks for them.- .labelStyle(.titleAndIcon)- .environment(host)- .environment(account)- .environment(updates)- } label: {- // The Codync mark; a dot joins it when a bot needs you.- Image(host.needsAttention ? "MenuBarIconAlert" : "MenuBarIcon")- .task { launch() }- .onChange(of: account.userID) { _, userID in host.switchAccount(to: userID) }- // A device asking for access: bring up the window that holds the approval sheet.- .onChange(of: host.currentApproval?.id) { _, id in- guard id != nil else { return }- openWindow(id: "chat")- NSApp.activate()- }- }- .menuBarExtraStyle(.menu)-- Window("Pair iPhone", id: "pairing") {- Group {- if let store = host.store {- PairingPanel(store: store)- .id(store.computer.id)- } else {- Text("Connect to this Mac's host before pairing your iPhone.")- .padding()- }- }- .frame(width: 340)- .appFont(.body)- .scrollIndicators(.never)- .environment(\.appFontScale, ConversationTypography(pointSize: conversationFontSize).scale)- .environment(host)- }- .windowResizability(.contentSize)- }-}--/// A system menu: macOS owns layout, selection, keyboard navigation and submenus.-struct MenuView: View {- @Environment(UpdatesManager.self) private var updates- @Environment(HostController.self) private var host- @Environment(\.openWindow) private var openWindow- @AppStorage(SharedStore.usageIconStyleKey, store: UserDefaults(suiteName: SharedStore.appGroup))- private var usageIconStyle = UsageIconStyle.character.rawValue- @AppStorage(ConversationTypography.preferenceKey)- private var conversationFontSize = ConversationTypography.defaultSize-- var body: some View {- Text(status)- Button("Open Codync") { open("chat") }- .keyboardShortcut("o")- if host.state == .running {- Button("Pair iPhone…") {- host.requestPairing()- open("pairing")- }- .disabled(host.store == nil)- }- Divider()- hostItems- Divider()- Menu("Settings") {- Picker("Usage icons", selection: $usageIconStyle) {- Text("Character").tag(UsageIconStyle.character.rawValue)- Text("Original").tag(UsageIconStyle.original.rawValue)- }- Picker("Text Size", selection: $conversationFontSize) {- ForEach(ConversationTypography.sizes, id: \.self) { size in- Text(size == ConversationTypography.defaultSize ? "\(Int(size)) pt (Default)" : "\(Int(size)) pt")- .tag(size)- }- }- Toggle("Open at login", isOn: Binding(- get: { host.launchAtLogin },- set: { host.setLaunchAtLogin($0) }- ))- Divider()- Menu("Updates") {- Button(updates.availableVersion.map { "Update to \($0)…" } ?? "Check for Updates…") {- updates.checkForUpdates()- }- .disabled(!updates.canCheckForUpdates && !updates.hasStagedUpdate)- if let app = updates.waitingForApp {- // The release waits until paired iPhones can get the app it needs.- Text("Waiting for iPhone app \(app) to pass App Store review")- }- Toggle("Automatically check for updates", isOn: Binding(- get: { updates.automaticallyChecksForUpdates },- set: { updates.automaticallyChecksForUpdates = $0 }- ))- .disabled(!updates.isSupported)- Toggle("Automatically download and install", isOn: Binding(- get: { updates.automaticallyDownloadsUpdates },- set: { updates.automaticallyDownloadsUpdates = $0 }- ))- .disabled(!updates.isSupported)- if !updates.isSupported { Text("Updates are available in release builds.") }- if let date = updates.lastUpdateCheckDate { Text("Last checked: \(date.formatted())") }- if let error = updates.errorMessage {- Text(error)- Button("Retry installing update") { updates.retryInstallation() }- .disabled(updates.preparingInstallation)- }- }- Divider()- Button("Restart host") { host.restart() }- Button("Open log") { NSWorkspace.shared.open(host.logURL) }- Divider()- Button("Uninstall host service") { host.uninstall() }- Divider()- Button("Reset all data…") {- host.confirmsReset = true- open("chat")- }- }- if let version = host.version { Text("Version \(version)") }- Button("Quit Codync") { NSApp.terminate(nil) }- .keyboardShortcut("q")- }-- private var status: String {- switch host.state {- case .missingBinary: "Host not found"- case .notInstalled: "Host not installed"- case .starting: "Connecting…"- case .failed: "Host problem"- case .running:- if !host.approvals.isEmpty {- "A device asks for access"- } else if host.needsAttention {- "A bot needs you"- } else if host.working > 0 {- "\(host.working) bot\(host.working == 1 ? "" : "s") working"- } else {- "Connected"- }- }- }-- @ViewBuilder private var hostItems: some View {- switch host.state {- case .missingBinary:- Text("Reinstall Codync or install the host with Homebrew.")- Button("Copy host install command") {- NSPasteboard.general.clearContents()- NSPasteboard.general.setString("brew install leepokai/codync/codync-host", forType: .string)- }- case .notInstalled:- Button("Install host") { host.install() }- case .starting:- Text("Starting the host…")- case let .failed(message):- Text(message)- Button("Restart host") { host.restart() }- Button("Open log") { NSWorkspace.shared.open(host.logURL) }- case .running:- if let approval = host.approvals.first {- Button("Review access request from \(approval.request.deviceName)…") {- host.reviewApprovals()- open("chat")- }- Divider()- }- bots- if host.screen != nil {- Divider()- RemoteScreenMenu()- }- if !host.usage.providers.isEmpty {- Divider()- ForEach(host.usage.providers) { provider in- // Buttons, not text: the menu dims a disabled item's image. They open the app.- Button { open("chat") } label: {- Label {- Text(provider.name)- } icon: {- menuIcon(ProviderMascot(provider, size: 16, style: UsageIconStyle(rawValue: usageIconStyle) ?? .character),- key: "provider|\(provider.id)|\(usageIconStyle)|\((provider.tightest?.percent ?? 0) >= 90)")- }- }- // A bar per limit, with its numbers as the item's title (what VoiceOver reads too).- ForEach(provider.windows) { window in- Button { open("chat") } label: {- Label {- Text(usageLine(window))- } icon: {- menuIcon(UsageBar(window: window, tint: provider.tint),- key: "bar|\(provider.id)|\(Int(window.percent.rounded()))")- }- }- }- }- }- }- }-- @ViewBuilder private var bots: some View {- let roster = host.roster.filter { !$0.bot.isGroup }- if roster.isEmpty {- Text("No bots yet")- } else {- ForEach(roster) { item in- Menu {- Text(item.bot.needsInput ? "Needs your response" : item.bot.isWorking- ? (item.bot.activity.isEmpty ? "Working…" : item.bot.activity)- : (item.bot.lastMessage ?? item.bot.folderName))- Button("Open conversation") {- host.accounts.selection = item.ref- open("chat")- }- if item.bot.isWorking {- Button("Stop task") { host.stop(item) }- }- } label: {- Label {- Text(host.accounts.computers.count > 1 ? "\(item.bot.name) · \(item.computer.name)" : item.bot.name)- } icon: {- menuIcon(AvatarWithStatus(bot: item.bot, size: 20), key: avatarKey(item.bot))- }- }- }- }- }-- private func open(_ id: String) {- openWindow(id: id)- NSApp.activate()- }-- private func usageLine(_ window: UsageWindow) -> String {- let reset = window.resetDate.map { " · resets in \(RelativeTime.until($0))" } ?? ""- return "\(window.title) · \(Int(window.percent.rounded()))%\(reset)"- }-- /// Everything the avatar image shows; the activity text changes often and isn't drawn.- private func avatarKey(_ bot: Bot) -> String {- "bot|\(bot.id)|\(bot.avatarShape)|\(bot.avatarColor)|\(bot.status)|\(bot.needsInput)|\(bot.unread > 0)"- }-- /// Rendered icons by what they show and the appearance: a bot's status change redraws one image,- /// not the whole menu, and nothing is drawn again while the menu is closed and nothing changed.- @MainActor private static let iconCache = NSCache<NSString, NSImage>()-- /// NSMenu items only take text and an image, so custom drawing goes in as a rendered image.- private func menuIcon(_ view: some View, key: String) -> Image {- // The menu follows the system appearance; this view's environment doesn't. Reading- // `host.menuIsDark` here redraws the menu when the system switches.- let dark = host.menuIsDark- let cacheKey = "\(key)|\(dark)" as NSString- if let cached = Self.iconCache.object(forKey: cacheKey) { return Image(nsImage: cached) }- let appearance = NSAppearance(named: dark ? .darkAqua : .aqua) ?? NSApp.effectiveAppearance- let renderer = ImageRenderer(content: view.environment(\.colorScheme, dark ? .dark : .light))- renderer.scale = NSScreen.main?.backingScaleFactor ?? 2- var image: NSImage?- appearance.performAsCurrentDrawingAppearance { image = renderer.nsImage }- guard let image else { return Image(systemName: "circle") }- Self.iconCache.setObject(image, forKey: cacheKey)- return Image(nsImage: image)- }-}--/// One usage limit's bar in the provider's color: amber from 70%, red from 90%.-private struct UsageBar: View {- let window: UsageWindow- let tint: Color-- var body: some View {- let color = window.percent >= 90 ? Palette.danger : window.percent >= 70 ? Palette.warning : tint- ZStack(alignment: .leading) {- Capsule().fill(Color.primary.opacity(0.12))- if window.percent > 0 {- Capsule().fill(color).frame(width: max(5, 60 * min(1, window.percent / 100)))- }- }- .frame(width: 60, height: 5)- .frame(height: 16)- }-}--private struct RemoteScreenMenu: View {- @Environment(HostController.self) private var host-- var body: some View {- let screen = host.screen ?? ScreenState()- Menu("Remote screen") {- Toggle("Enable remote screen", isOn: Binding(- get: { host.screen?.enabled == true },- set: { host.setRemoteScreen($0) }- ))- Text(subtitle(screen))- if screen.enabled {- if host.screenAgentNeedsApproval {- Button("Allow Codync Screen in Login Items…") { host.openLoginItemsSettings() }- } else if screen.connected {- if !screen.capture {- Button("Allow Screen Recording…") {- open("x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")- }- }- if !screen.input {- Button("Allow Accessibility…") {- open("x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")- }- }- }- }- if let error = host.screenError { Text(error) }- }- }-- private func subtitle(_ screen: ScreenState) -> String {- guard screen.enabled else { return "Control this Mac from your iPhone" }- if host.screenAgentNeedsApproval { return "Needs approval in System Settings" }- if !screen.connected { return "Starting Codync Screen…" }- if !screen.capture || !screen.input { return "Needs permission" }- if screen.viewers > 0 { return screen.viewers == 1 ? "Your iPhone is viewing" : "\(screen.viewers) viewers" }- if let bot = screen.agentBot, let name = host.store?.bots[bot]?.name { return "\(name) is using it" }- let display = screen.displays.first(where: \.main)?.name ?? screen.displays.first?.name- return display.map { "Ready · \($0)" } ?? "Ready"- }-- private func open(_ url: String) {- if let url = URL(string: url) { NSWorkspace.shared.open(url) }- }-}--/// A one-time pairing QR (v3) from a computer this Mac manages: its keys, a code, and how to reach it.-struct PairingPanel: View {- let store: BotStore- @Environment(HostController.self) private var host- @State private var info: PairingInfo?- @State private var error: String?- @Environment(\.accessibilityReduceMotion) private var reduceMotion-- var body: some View {- VStack(spacing: 12) {- if let info {- if let image = qr(info.pairingUrl) {- Image(nsImage: image)- .interpolation(.none)- .resizable()- .frame(width: 200, height: 200)- .padding(10)- .background(.white, in: RoundedRectangle(cornerRadius: 12))- .accessibilityLabel("Pairing code for \(store.hostName)")- }- Text("Scan with the Codync app or the iPhone Camera. No Tailscale or open ports needed: your iPhone connects directly on the same Wi-Fi, and through the encrypted relay anywhere else.")- .appFont(.caption)- .foregroundStyle(Palette.secondary)- .multilineTextAlignment(.center)- .fixedSize(horizontal: false, vertical: true)- if store.cloud?.enabled != true {- Text(info.urls.isEmpty- ? "No network address found and “Reach from anywhere” is off. Connect to Wi-Fi or turn it on."- : "“Reach from anywhere” is off, so the iPhone only reaches \(store.hostName) on the same network.")- .appFont(.caption)- .foregroundStyle(Palette.warning)- .multilineTextAlignment(.center)- .fixedSize(horizontal: false, vertical: true)- }- HStack(spacing: 4) {- if let expires = info.expiresAt {- Text("Works once, until \(Date(milliseconds: expires).formatted(date: .omitted, time: .shortened))")- .appFont(.caption2).foregroundStyle(Palette.tertiary)- }- IconButton("New code", systemImage: "arrow.clockwise") { Task { await load() } }- IconButton("Copy pairing link", systemImage: "doc.on.doc") {- NSPasteboard.general.clearContents()- NSPasteboard.general.setString(info.pairingUrl, forType: .string)- }- }- } else if let error {- Text(error).appFont(.caption).foregroundStyle(Palette.danger).multilineTextAlignment(.center)- IconButton("Try again", systemImage: "arrow.clockwise") { Task { await load() } }- } else {- Spinner(size: 20)- }- }- .frame(maxWidth: .infinity)- .padding(16)- .animation(Motion.reduced(Motion.layout, reduceMotion), value: info?.pairingUrl)- .animation(Motion.reduced(Motion.layout, reduceMotion), value: error)- // A new code each time "Pair iPhone…" is chosen (the window stays open between uses).- .task(id: "\(store.computer.id)#\(host.pairingRequest)") { await load() }- // And a fresh one when this code expires while it's on screen.- .task(id: info?.expiresAt) {- guard let expires = info?.expiresAt else { return }- let wait = Date(milliseconds: expires).timeIntervalSinceNow- try? await Task.sleep(for: .seconds(max(1, wait)))- if !Task.isCancelled { await load() }- }- }-- private func load() async {- guard let client = store.client else {- error = "\(store.hostName) isn't connected."- return- }- do {- info = try await client.pairing()- error = nil- } catch {- self.error = error.localizedDescription- }- }-- private func qr(_ string: String) -> NSImage? {- let filter = CIFilter.qrCodeGenerator()- filter.message = Data(string.utf8)- filter.correctionLevel = "M"- guard let output = filter.outputImage else { return nil }- let rep = NSCIImageRep(ciImage: output)- let image = NSImage(size: rep.size)- image.addRepresentation(rep)- return image- }-}diff --git a/apps/macos/App/HostController.swift b/apps/macos/App/HostController.swiftdeleted file mode 100644index 2e0a9f54..00000000--- a/apps/macos/App/HostController.swift+++ /dev/null@@ -1,664 +0,0 @@-import AppKit-import CodyncKit-import CodyncUI-import CryptoKit-import Foundation-import Observation-import os-import ServiceManagement--/// A device asking a computer this Mac manages (itself or over SSH) for access.-@MainActor-struct Approval: Identifiable {- let store: BotStore- let request: AccessRequest- let id: String-- init(store: BotStore, request: AccessRequest) {- self.store = store- self.request = request- id = "\(store.computer.id)/\(request.requestId)"- }-}--private let log = Logger(subsystem: "com.pokai.Codync", category: "Host")--/// Manages the local codync-host (binary, background service) and owns the `AccountStore`-/// the menu and the chat window share: this Mac over loopback, SSH computers through their-/// tunnels, and the account's other computers over the encrypted channel.-@MainActor-@Observable-final class HostController {- enum State: Equatable {- case missingBinary- case notInstalled- case starting- case running- case failed(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- static let dataDir = ProcessInfo.processInfo.environment["CODYNC_HOME"].map { URL(filePath: $0) }- ?? FileManager.default.homeDirectoryForCurrentUser.appending(path: ".codync")- static let baseURL = URL(string: "http://127.0.0.1:\(port)")!-- let account: AccountSession- let ssh = SSHComputers()- /// One per account context; switching accounts retires it.- private(set) var accounts: AccountStore- /// The signed-in account's cloud; nil when signed out or the build has no cloud.- private(set) var cloud: CloudClient?- private(set) var contextID: String- /// This Mac's own host, once it answered.- private(set) var local: Computer?- private var localToken: String?-- private(set) var state: State = .starting- var launchAtLogin: Bool = SMAppService.mainApp.status == .enabled- /// Codync Screen (capture + input for Remote screen), a launchd agent inside this app.- private let screenAgent = SMAppService.agent(plistName: "com.pokai.Codync.screen.plist")- private(set) var screenAgentNeedsApproval = false- private(set) var screenError: String?- /// Approvals closed with "later"; they come back when the request changes (e.g. its code arrives).- private var deferred: Set<String> = []-- private var streamTask: Task<Void, Never>?- /// Set once the service was moved onto this app's host because it ran another version.- private var replacedStaleHost = false- private var expectedBinaryHash: String?- private var installingHost = false- private var preparingForUpdate = false-- init(account: AccountSession) {- #if DEBUG- SSH.selfCheck()- #endif- self.account = account- let storage = SharedStore.Context(accountID: account.userID)- SharedStore.activeAccountID = account.userID- contextID = storage.id- (accounts, cloud) = Self.makeAccounts(storage, session: account)- ssh.onAttach = { [weak self] attachment in- self?.accounts.attach(attachment.computer, route: .loopback(baseURL: attachment.baseURL, token: attachment.token))- }- ssh.onDetach = { [weak self] id in self?.accounts.detach(id) }- // ssh children outlive the app unless stopped.- NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: .main) { [weak self] _ in- MainActor.assumeIsolated { self?.ssh.disconnectAll() }- }- }-- /// The Mac's own host store.- var store: BotStore? { local.flatMap { accounts.store(for: $0.id) } }-- /// Computers this Mac manages over loopback (itself and SSH tunnels): they take approvals, pairing and claims.- var managedStores: [BotStore] {- accounts.computers.compactMap { accounts.store(for: $0.id) }.filter(\.isLoopback)- }-- var approvals: [Approval] {- managedStores.flatMap { store in store.accessRequests.map { Approval(store: store, request: $0) } }- }-- /// The approval to show now: the first one not put off, or put off before its code arrived.- var currentApproval: Approval? {- approvals.first { !deferred.contains(deferKey($0)) }- }-- func deferApproval(_ approval: Approval) { deferred.insert(deferKey(approval)) }-- /// Brings every waiting request back (the menu's Review).- func reviewApprovals() { deferred = [] }-- private func deferKey(_ a: Approval) -> String { "\(a.id)/\(a.request.code ?? "")" }-- var roster: [RosterItem] { accounts.roster }- var usage: Usage { store?.usage ?? Usage() }- var screen: ScreenState? { store?.screen }- var version: String? { store?.hello?.version }- var needsAttention: Bool { roster.contains(where: \.bot.needsInput) || !approvals.isEmpty }- var working: Int { roster.filter(\.bot.isWorking).count }-- func isSSH(_ id: ComputerID) -> Bool { ssh.attachments.values.contains { $0.computer.id == id } }-- /// Bundled next to the app executable, else a Homebrew / cargo install.- var binaryURL: URL? {- let candidates = [- Bundle.main.bundleURL.appending(path: "Contents/MacOS/codync-host"),- URL(filePath: "/opt/homebrew/bin/codync-host"),- URL(filePath: "/usr/local/bin/codync-host"),- FileManager.default.homeDirectoryForCurrentUser.appending(path: ".cargo/bin/codync-host"),- ]- return candidates.first { FileManager.default.isExecutableFile(atPath: $0.path) }- }-- private var plistURL: URL {- FileManager.default.homeDirectoryForCurrentUser.appending(path: "Library/LaunchAgents/com.pokai.codync.host.plist")- }-- private var tokenURL: URL { Self.dataDir.appending(path: "token") }-- var logURL: URL { Self.dataDir.appending(path: "host.log") }-- /// The menu's images are drawn for one appearance; this follows the system's so they're redrawn.- private(set) var menuIsDark = false- @ObservationIgnored private var appearanceObservation: NSKeyValueObservation?- /// Bumped by "Pair iPhone…": the pairing window stays open between uses, so it fetches a fresh code.- private(set) var pairingRequest = 0-- func requestPairing() { pairingRequest += 1 }-- func start() {- guard appearanceObservation == nil else { return }- menuIsDark = NSApp.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua- appearanceObservation = NSApp.observe(\.effectiveAppearance) { [weak self] app, _ in- let dark = app.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua- Task { @MainActor in self?.menuIsDark = dark }- }- refresh()- ssh.connectAll()- watchAutoClaim()- watchCloudDefault()- }-- /// Cloudflare is on by default, so a Mac without Tailscale is reachable away from home. It's turned on- /// once per host identity, the first time it's seen off; after that, off stays off, whoever turned it- /// off (this app's switch, `codync-host cloud --disable`), and it's never undone behind the user's back.- private func watchCloudDefault() {- let target = withObservationTracking {- cloudDefaultTarget- } onChange: { [weak self] in- Task { @MainActor in self?.watchCloudDefault() }- }- guard let target, let client = target.client, !enablingCloud else { return }- enablingCloud = true- Self.markCloudDefaultApplied(target.computer.id)- Task {- do {- _ = try await enableCloud(client, store: target)- } catch {- log.error("turning Cloudflare on by default failed: \(error.localizedDescription, privacy: .public)")- }- enablingCloud = false- }- }-- private var enablingCloud = false- /// Host identities whose Cloudflare default has been applied (or found already on).- private static let cloudDefaultKey = "cloudDefaultApplied"-- private static func cloudDefaultApplied(_ id: ComputerID) -> Bool {- UserDefaults.standard.stringArray(forKey: cloudDefaultKey)?.contains(id) ?? false- }-- private static func markCloudDefaultApplied(_ id: ComputerID) {- let ids = UserDefaults.standard.stringArray(forKey: cloudDefaultKey) ?? []- if !ids.contains(id) { UserDefaults.standard.set(ids + [id], forKey: cloudDefaultKey) }- }-- private var cloudDefaultTarget: BotStore? {- guard account.cloudURL != nil, let store, store.connection == .online, let status = store.cloud,- !Self.cloudDefaultApplied(store.computer.id) else { return nil }- // Already on: nothing to apply, and a later "off" is the user's.- if status.enabled {- Self.markCloudDefaultApplied(store.computer.id)- return nil- }- return store- }-- func refresh() {- guard !preparingForUpdate else { return }- guard binaryURL != nil else {- state = .missingBinary- return- }- if Self.devPort == nil, UserDefaults.standard.bool(forKey: Self.updateRestartKey),- FileManager.default.fileExists(atPath: plistURL.path) {- install()- return- }- guard Self.devPort != nil || FileManager.default.fileExists(atPath: plistURL.path) else {- // The app is the way to run the host on a Mac: set it up right away, unless the user took it out.- if UserDefaults.standard.bool(forKey: Self.uninstalledKey) { state = .notInstalled } else { install() }- return- }- connect()- }-- /// Set by "Uninstall host service", so the next launch doesn't put the host back.- private static let uninstalledKey = "hostUninstalled"- private static let updateRestartKey = "hostRestartAfterAppUpdate"-- /// `codync-host install` also routes Claude Code's status line through the host.- func install() {- guard !preparingForUpdate, !installingHost, let bin = binaryURL else { return }- installingHost = true- streamTask?.cancel()- UserDefaults.standard.set(false, forKey: Self.uninstalledKey)- state = .starting- Task {- defer { installingHost = false }- let result = await Self.run(bin, ["install", "--port", "\(Self.port)"])- if result.status != 0 {- state = .failed(result.output.isEmpty ? "Install failed" : result.output)- } else {- try? await Task.sleep(for: .seconds(1))- connect()- }- }- }-- func restart() {- guard Self.devPort == nil else {- state = .failed("Restart the manually started development host in its terminal.")- return- }- // Reinstall also updates the executable path and waits for the old host- // to release its data lock. A kickstart could restart another app's copy.- replacedStaleHost = false- install()- }-- func uninstall() {- guard let bin = binaryURL else { return }- streamTask?.cancel()- UserDefaults.standard.set(true, forKey: Self.uninstalledKey)- Task {- _ = await Self.run(bin, ["uninstall"])- if let local { accounts.detach(local.id) }- local = nil- localToken = nil- state = .notInstalled- }- }-- /// The menu asks the chat window to confirm a full reset.- var confirmsReset = false-- /// Back to a first launch. Removes this computer from the account and revokes its- /// paired devices, signs out every account, stops the host, deletes its data folder (bots,- /// transcripts, keys) and this app's settings, then relaunches.- func resetAllData() async {- // Tell paired devices first: connected ones see "No access" at once, and the account drops this- // computer instead of keeping an unreachable older copy of it.- if let client = store?.client {- try? await client.unclaim()- for device in (try? await client.devices()) ?? [] { try? await client.revokeDevice(device.key) }- }- let accountIDs = account.accounts.map(\.id)- await account.signOutAll()- for id in accountIDs + [nil] { SharedStore.Context(accountID: id).erase() }- streamTask?.cancel()- if let bin = binaryURL { _ = await Self.run(bin, ["uninstall"]) }- try? FileManager.default.removeItem(at: Self.dataDir)- UserDefaults(suiteName: SharedStore.appGroup)?.removePersistentDomain(forName: SharedStore.appGroup)- if let bundleID = Bundle.main.bundleIdentifier { UserDefaults.standard.removePersistentDomain(forName: bundleID) }- let relaunch = Process()- relaunch.executableURL = URL(filePath: "/bin/sh")- relaunch.arguments = ["-c", "sleep 1; /usr/bin/open -n \"$0\"", Bundle.main.bundlePath]- try? relaunch.run()- NSApp.terminate(nil)- }-- func setLaunchAtLogin(_ on: Bool) {- do {- if on { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() }- } catch {}- launchAtLogin = SMAppService.mainApp.status == .enabled- }-- /// Remote screen: starts/stops Codync Screen and tells the host (which only accepts this from the Mac itself).- func setRemoteScreen(_ on: Bool) {- guard !preparingForUpdate else { return }- Task {- do {- if on { try screenAgent.register() } else { try await screenAgent.unregister() }- UserDefaults.standard.set(on ? Self.helperStamp : nil, forKey: Self.helperStampKey)- try await store?.setScreenEnabled(on)- screenError = nil- } catch {- screenError = error.localizedDescription- }- screenAgentNeedsApproval = screenAgent.status == .requiresApproval- }- }-- func openLoginItemsSettings() {- SMAppService.openSystemSettingsLoginItems()- }-- /// Keeps Codync Screen registered while the host has Remote screen on (e.g. after the app moved),- /// and registers it again when this app ships a different helper binary (an update or a rebuild):- /// launchd keeps running the old helper, and a new binary under the old registration fails to start.- private func syncScreenAgent() async {- guard !preparingForUpdate else { return }- guard screen?.enabled == true else {- screenAgentNeedsApproval = false- return- }- let stamp = Self.helperStamp- let stale = UserDefaults.standard.string(forKey: Self.helperStampKey) != stamp- guard stale || screenAgent.status != .enabled else {- screenAgentNeedsApproval = false- return- }- if stale, screenAgent.status == .enabled {- log.info("Codync Screen changed; registering it again")- // Stops the old helper along with its job.- try? await screenAgent.unregister()- }- try? screenAgent.register()- if screenAgent.status == .enabled { UserDefaults.standard.set(stamp, forKey: Self.helperStampKey) }- screenAgentNeedsApproval = screenAgent.status == .requiresApproval- }-- private static let helperStampKey = "screenHelperStamp"-- /// Identifies the helper binary inside this app: its path and modification date.- private static var helperStamp: String {- let url = Bundle.main.bundleURL.appending(path: "Contents/Library/LoginItems/CodyncScreen.app/Contents/MacOS/CodyncScreen")- let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate- return "\(url.path)@\(modified?.timeIntervalSince1970 ?? 0)"- }-- func isIdleForUpdate() async -> Bool {- guard !installingHost, !preparingForUpdate, Self.devPort == nil else { return false }- if !FileManager.default.fileExists(atPath: plistURL.path) { return true }- guard let health = await HostHealth.fetch(Self.baseURL) else { return false }- return health.busy == false- }-- func prepareForUpdate() async throws {- guard Self.devPort == nil else { return }- guard !installingHost else {- throw NSError(domain: "Codync.Update", code: 1,- userInfo: [NSLocalizedDescriptionKey: "The host is being installed. Try again when it finishes."])- }- preparingForUpdate = true- // Persist before stopping: Sparkle can install on Quit and relaunch later.- if FileManager.default.fileExists(atPath: plistURL.path) {- UserDefaults.standard.set(true, forKey: Self.updateRestartKey)- }- streamTask?.cancel()- if screenAgent.status == .enabled {- try await screenAgent.unregister()- UserDefaults.standard.removeObject(forKey: Self.helperStampKey)- }- guard let bin = binaryURL else {- throw NSError(domain: "Codync.Update", code: 2,- userInfo: [NSLocalizedDescriptionKey: "The bundled host is missing."])- }- let result = await Self.run(bin, ["stop"])- guard result.status == 0 else {- throw NSError(domain: "Codync.Update", code: 3,- userInfo: [NSLocalizedDescriptionKey: result.output.isEmpty ? "The old host could not be stopped." : result.output])- }- }-- func resumeAfterCancelledUpdate() {- guard preparingForUpdate else { return }- preparingForUpdate = false- if FileManager.default.fileExists(atPath: plistURL.path) { install() } else { refresh() }- }-- func stop(_ item: RosterItem) {- accounts.store(for: item.ref.computerId)?.stop(item.bot.id)- }-- // MARK: account-- func switchAccount(to userID: String?) {- let storage = SharedStore.Context(accountID: userID)- guard storage.id != contextID else { return }- accounts.retire()- SharedStore.activeAccountID = userID- contextID = storage.id- deferred = []- (accounts, cloud) = Self.makeAccounts(storage, session: account)- // This Mac and the SSH tunnels belong to the Mac, not to an account: they follow into the new context.- if let local, let localToken { accounts.attach(local, route: .loopback(baseURL: Self.baseURL, token: localToken)) }- for attachment in ssh.attachments.values {- accounts.attach(attachment.computer, route: .loopback(baseURL: attachment.baseURL, token: attachment.token))- }- }-- /// Signing out forgets the account on this Mac: its device keys, computers and caches (spec §3.2).- func signOut() async {- guard let userID = account.userID else { return }- await account.signOut()- guard account.userID != userID, !account.accounts.contains(where: { $0.id == userID }) else { return }- switchAccount(to: account.userID)- SharedStore.Context(accountID: userID).erase()- }-- /// §4.2 A: makes a computer this Mac manages part of the signed-in account. Its relay is turned on first,- /// since joining the account is about reaching it from anywhere.- /// `quiet`: the automatic join, which logs a failure and retries instead of showing it.- @discardableResult- func claim(_ store: BotStore, quiet: Bool = false) async -> Bool {- guard let cloud, let userID = account.userID, let client = store.client else {- if !quiet { accounts.lastError = "Sign in first." }- return false- }- Self.setKeptOut(store.computer.id, false, userID: userID)- do {- if store.cloud?.enabled != true { _ = try await enableCloud(client, store: store) }- let challenge = try await cloud.createClaim()- let signed = try await client.claimSign(claimId: challenge.claimId, nonce: challenge.nonce, userId: userID)- _ = try await cloud.completeClaim(challenge.claimId, signed: signed)- await accounts.refreshCloud()- if store.computer.id == self.store?.computer.id { await forgetEarlierIdentities(of: store.computer.id) }- return true- } catch {- if quiet {- log.error("joining the account failed: \(error.localizedDescription, privacy: .public)")- } else {- accounts.lastError = error.localizedDescription- }- return false- }- }-- /// Signed in, this Mac joins the account on its own, unless the user took it out of that account.- private func watchAutoClaim() {- let pending = withObservationTracking {- autoClaimTarget- } onChange: { [weak self] in- Task { @MainActor in self?.watchAutoClaim() }- }- // Remember which identity is this Mac while it's in the account, so a later key reset can clean it up.- if let store, let userID = account.userID, store.cloud?.owner?.userId == userID {- UserDefaults.standard.set([store.computer.id], forKey: "claimedComputerIds")- }- guard let pending, !autoClaiming else { return }- autoClaiming = true- Task {- // A failed join (network hiccup) is retried with backoff for as long as it's still wanted.- var delay = 30.0- while await !claim(pending, quiet: true) {- try? await Task.sleep(for: .seconds(delay))- delay = min(delay * 2, 600)- guard autoClaimTarget?.computer.id == pending.computer.id else { break }- }- autoClaiming = false- }- }-- private var autoClaiming = false-- /// This Mac's host, online, in no account yet, for a signed-in user who hasn't removed it.- private var autoClaimTarget: BotStore? {- // Only with Cloudflare on: joining needs it, and turning it back on is never done silently.- guard let userID = account.userID, let store, store.connection == .online,- let status = store.cloud, status.enabled, status.owner == nil,- !Self.keptOut(userID).contains(store.computer.id) else { return nil }- return store- }-- /// Computers the user removed from an account on this Mac; auto-join leaves them out.- private static func keptOut(_ userID: String) -> Set<String> {- Set(UserDefaults.standard.stringArray(forKey: "keptOutOfAccount.\(userID)") ?? [])- }-- private static func setKeptOut(_ id: String, _ out: Bool, userID: String) {- var ids = keptOut(userID)- if out { ids.insert(id) } else { ids.remove(id) }- UserDefaults.standard.set(Array(ids), forKey: "keptOutOfAccount.\(userID)")- }-- /// This Mac's host got new keys (a reset `~/.codync`, a reinstall): the identities this Mac claimed- /// before are dead copies of it, so they leave the account instead of showing up as a second Mac.- private func forgetEarlierIdentities(of current: ComputerID) async {- let key = "claimedComputerIds"- let earlier = Set(UserDefaults.standard.stringArray(forKey: key) ?? []).subtracting([current])- for computer in accounts.cloudComputers where earlier.contains(computer.computerId) && !computer.isOnline {- await accounts.removeFromAccount(computer.computerId)- }- UserDefaults.standard.set([current], forKey: key)- }-- func unclaim(_ store: BotStore) async {- if let userID = account.userID { Self.setKeptOut(store.computer.id, true, userID: userID) }- do {- try await store.client?.unclaim()- await accounts.refreshCloud()- } catch {- accounts.lastError = error.localizedDescription- }- }-- func setCloud(_ store: BotStore, enabled: Bool) async {- guard let client = store.client else { return }- Self.markCloudDefaultApplied(store.computer.id)- do {- _ = enabled ? try await enableCloud(client, store: store) : try await client.setCloud(enabled: false)- } catch {- accounts.lastError = error.localizedDescription- }- }-- /// A host without a cloud URL of its own gets this app's.- private func enableCloud(_ client: HostClient, store: BotStore) async throws -> CloudStatus {- let url = store.cloud?.url == nil ? account.cloudURL : nil- guard store.cloud?.url != nil || url != nil else {- throw CloudError(status: 400, code: "badRequest", message: "This build of Codync has no cloud to connect to.")- }- return try await client.setCloud(enabled: true, url: url)- }-- func decide(_ approval: Approval, approve: Bool) async throws {- guard let client = approval.store.client else { throw HostError.unreachable }- try await client.decideAccessRequest(approval.request.requestId, approve: approve)- }-- private static func makeAccounts(_ storage: SharedStore.Context, session: AccountSession) -> (AccountStore, CloudClient?) {- let identity = storage.accountID == nil ? nil : try? DeviceIdentity.load(context: storage)- let cloud = session.cloudClient(for: storage.accountID, identity: identity)- let accounts = AccountStore(storage: storage, clientKind: "mac", cloud: cloud)- if let cloud {- // Signed in: make this Mac known to the account, then list its computers.- Task { [weak accounts] in- do {- try await cloud.registerDevice(name: Host.current().localizedName ?? "Mac", platform: "macos")- } catch let error as CloudError where !error.isTransient {- accounts?.lastError = error.localizedDescription- } catch {- // Transient (network, busy cloud, token not ready): the next launch registers again.- }- await accounts?.refreshCloud()- }- }- return (accounts, cloud)- }-- // MARK: local host-- private func readToken() -> String? {- (try? String(contentsOf: tokenURL, encoding: .utf8)).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }- }-- /// Watches the host's health; the BotStore handles the event stream itself.- private func connect() {- guard !preparingForUpdate else { return }- streamTask?.cancel()- streamTask = Task { [weak self] in- if let bin = self?.binaryURL {- let hash = await Task.detached {- (try? Data(contentsOf: bin)).map { data in- SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()- }- }.value- guard !Task.isCancelled else { return }- self?.expectedBinaryHash = hash- }- var failures = 0- while !Task.isCancelled {- guard let self else { return }- if await self.attachLocal() {- failures = 0- self.state = .running- if Self.devPort == nil {- UserDefaults.standard.removeObject(forKey: Self.updateRestartKey)- }- await self.syncScreenAgent()- } else {- failures += 1- if failures > 5 { self.state = .failed("The host isn't responding. See the log for details.") }- else if self.state != .running { self.state = .starting }- }- try? await Task.sleep(for: .seconds(5))- }- }- }-- /// Attaches the local host once it answers, and again when its token or identity changed.- private func attachLocal() async -> Bool {- guard let token = readToken(), let health = await HostHealth.fetch(Self.baseURL), let id = health.computerId else {- return false- }- // A rebuild can change the host without changing the release version.- // Legacy hosts have no fingerprint and are replaced once as well.- if Self.devPort == nil {- guard let expectedBinaryHash, let bin = binaryURL else { return false }- let matches = health.binaryHash == expectedBinaryHash- && health.binaryPath == bin.resolvingSymlinksInPath().path- if !matches {- if !replacedStaleHost {- log.info("Host binary differs from this app's; reinstalling the service")- replacedStaleHost = true- install()- }- return false- }- }- if Task.isCancelled {- return false- }- if local?.id == id, localToken == token, store != nil { return true }- guard let hello = try? await HostClient(baseURL: Self.baseURL, token: token).hello(),- hello.computerId == id, let signKey = hello.signKey else { return false }- let computer = Computer(id: id, name: hello.name, signKey: signKey, boxKey: hello.boxKey, urls: hello.urls ?? [],- cloud: hello.cloud.flatMap(URL.init(string:)), device: hello.device,- color: store?.computer.color)- if let old = local, old.id != id { accounts.detach(old.id) }- local = computer- localToken = token- accounts.attach(computer, route: .loopback(baseURL: Self.baseURL, token: token))- return true- }-- nonisolated static func run(_ bin: URL, _ args: [String]) async -> (status: Int32, output: String) {- // The host rebuilds PATH from the login shell itself (backends::hydrate_path).- let result = await ProcessRunner.run(bin, args)- return (result.status, (result.text + result.stderr).trimmingCharacters(in: .whitespacesAndNewlines))- }-}--extension BotStore {- var isLoopback: Bool {- if case .loopback = route { true } else { false }- }-}diff --git a/apps/macos/App/SSHTunnel.swift b/apps/macos/App/SSHTunnel.swiftdeleted file mode 100644index ab27eb26..00000000--- a/apps/macos/App/SSHTunnel.swift+++ /dev/null@@ -1,660 +0,0 @@-import CodyncKit-import Darwin-import Foundation-import Observation-import OSLog-import os--private let log = Logger(subsystem: "com.pokai.Codync", category: "ssh")--/// A computer reached over SSH (spec §11.4). Nothing secret: keys stay in ssh-agent or on disk.-struct SSHProfile: Codable, Hashable, Identifiable, Sendable {- var id = UUID()- /// An `~/.ssh/config` alias or a hostname.- var host: String- var port: Int?- var user: String?- var identityFile: String?- var remotePort = 19222- /// Remembered after the first connection; a different computer behind the same address is refused.- var computerId: ComputerID?- var name: String-}--/// Everything that turns a profile into OpenSSH argv, and reads OpenSSH's output back.-/// Pure functions: arguments are always an argv array, never a shell string.-enum SSH {- static let ssh = URL(filePath: "/usr/bin/ssh")- static let keygen = URL(filePath: "/usr/bin/ssh-keygen")- static let keyscan = URL(filePath: "/usr/bin/ssh-keyscan")- static let lsof = URL(filePath: "/usr/sbin/lsof")- static let installCommand = "brew install leepokai/codync/codync-host && codync-host install"-- static var home: String { FileManager.default.homeDirectoryForCurrentUser.path }-- /// A reason the profile can't be used, or nil.- static func validate(_ p: SSHProfile) -> String? {- if p.host.hasPrefix("-") || !matches(p.host, #"^[A-Za-z0-9._-]+$"#) {- return "Use an SSH alias or a hostname: letters, digits, dots, dashes and underscores."- }- if let user = p.user, !matches(user, #"^[A-Za-z_][A-Za-z0-9._-]*$"#) { return "That user name isn't valid." }- if let port = p.port, !(1...65535).contains(port) { return "The SSH port must be between 1 and 65535." }- if !(1...65535).contains(p.remotePort) { return "The Codync port must be between 1 and 65535." }- if let file = p.identityFile {- var isDir: ObjCBool = false- guard file.hasPrefix("/"), FileManager.default.fileExists(atPath: file, isDirectory: &isDir), !isDir.boolValue else {- return "The key file doesn't exist."- }- }- return nil- }-- static func knownHostsFiles(home: String) -> [String] {- ["\(home)/.ssh/known_hosts", "\(home)/.codync/ssh_known_hosts"]- }-- /// ssh's config tokenizer splits `UserKnownHostsFile` on spaces, so each path carries literal quotes.- static func hostKeyOptions(home: String) -> [String] {- ["-o", "UserKnownHostsFile=" + knownHostsFiles(home: home).map { "\"\($0)\"" }.joined(separator: " "),- "-o", "StrictHostKeyChecking=yes"]- }-- static func targetOptions(_ p: SSHProfile) -> [String] {- var args: [String] = []- if let port = p.port { args += ["-p", "\(port)"] }- if let key = p.identityFile { args += ["-i", key] }- if let user = p.user { args += ["-l", user] }- return args- }-- static func resolveArguments(_ p: SSHProfile) -> [String] {- var args = ["-G"]- if let port = p.port { args += ["-p", "\(port)"] }- if let user = p.user { args += ["-l", user] }- return args + ["--", p.host]- }-- /// Where `codync-host` lives when `sh -l` doesn't see it: Homebrew on Apple Silicon is only on PATH- /// through `~/.zprofile`, install.sh uses `~/.local/bin`, and the Mac app keeps the host in its bundle.- static let remotePath = "$PATH:/opt/homebrew/bin:/usr/local/bin:/home/linuxbrew/.linuxbrew/bin:$HOME/.local/bin:/Applications/Codync.app/Contents/MacOS"-- /// The remote command is fixed; only the validated port number goes into it.- static func infoArguments(_ p: SSHProfile, home: String) -> [String] {- ["-T", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "ForwardAgent=no", "-o", "ForwardX11=no"]- + hostKeyOptions(home: home) + targetOptions(p)- + ["--", p.host, "sh -lc 'PATH=\"\(remotePath)\" codync-host info --json --port \(p.remotePort)'"]- }-- /// The far side rejected our key (BatchMode never prompts, so a password or passphrase can't help).- static func authRefused(_ stderr: String) -> Bool {- stderr.contains("Permission denied") || stderr.contains("Too many authentication failures")- }-- /// Tunnels a crashed or force-quit Codync left running: only Codync's tunnels carry this known_hosts file.- static func killOrphanTunnels() async {- _ = await ProcessRunner.run(URL(filePath: "/usr/bin/pkill"), ["-f", "--", #"^/usr/bin/ssh -N .*\.codync/ssh_known_hosts"#])- }-- static func tunnelArguments(_ p: SSHProfile, localPort: Int, home: String) -> [String] {- ["-N", "-T", "-o", "ExitOnForwardFailure=yes", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3",- "-o", "ForwardAgent=no", "-o", "ForwardX11=no", "-o", "BatchMode=yes"]- + hostKeyOptions(home: home)- + ["-L", "127.0.0.1:\(localPort):127.0.0.1:\(p.remotePort)"]- + targetOptions(p) + ["--", p.host]- }-- /// What `ssh -G` resolved the destination to.- struct Resolved: Equatable, Sendable {- var hostname: String- var port: Int- var hostKeyAlias: String?- var proxyJump: String?- var proxyCommand: String?-- var usesProxy: Bool { proxyJump != nil || proxyCommand != nil }- /// The name ssh looks up in known_hosts.- var knownHostsName: String {- let name = hostKeyAlias ?? hostname- return port == 22 ? name : "[\(name)]:\(port)"- }- }-- static func parseConfig(_ text: String) -> Resolved? {- var values: [String: String] = [:]- for line in text.split(whereSeparator: \.isNewline) {- let parts = line.split(separator: " ", maxSplits: 1)- guard parts.count == 2 else { continue }- let key = parts[0].lowercased()- if values[key] == nil { values[key] = String(parts[1]).trimmingCharacters(in: .whitespaces) }- }- func set(_ key: String) -> String? { values[key].flatMap { $0.isEmpty || $0 == "none" ? nil : $0 } }- guard let hostname = set("hostname"), let port = values["port"].flatMap(Int.init) else { return nil }- return Resolved(hostname: hostname, port: port, hostKeyAlias: set("hostkeyalias"),- proxyJump: set("proxyjump"), proxyCommand: set("proxycommand"))- }-- static func keyscanArguments(_ r: Resolved) -> [String] {- ["-T", "5", "-p", "\(r.port)", "--", r.hostname]- }-- /// `type key` of each host key line (known_hosts or ssh-keyscan output); comments and revoked keys skipped.- static func hostKeys(_ text: String, certAuthorities: Bool = true) -> Set<String> {- Set(text.split(whereSeparator: \.isNewline).compactMap { line in- var fields = line.split(whereSeparator: \.isWhitespace)- guard let first = fields.first, !first.hasPrefix("#") else { return nil }- if first.hasPrefix("@") {- guard certAuthorities, first == "@cert-authority" else { return nil }- fields.removeFirst()- }- return fields.count >= 3 ? "\(fields[1]) \(fields[2])" : nil- })- }-- /// ssh-keyscan's lines, filed under the name ssh will look up.- static func knownHostsLines(scan: String, name: String) -> [String] {- hostKeys(scan).sorted().map { "\(name) \($0)" }- }-- private static func matches(_ s: String, _ pattern: String) -> Bool {- s.range(of: pattern, options: .regularExpression) != nil- }-- #if DEBUG- /// Runs at launch in debug builds (spec §11.5).- static func selfCheck() {- let home = "/Users/k"- let p = SSHProfile(host: "box", port: 2222, user: "kevin", name: "Box")- assert(hostKeyOptions(home: home) == [- "-o", #"UserKnownHostsFile="/Users/k/.ssh/known_hosts" "/Users/k/.codync/ssh_known_hosts""#,- "-o", "StrictHostKeyChecking=yes",- ])- assert(resolveArguments(p) == ["-G", "-p", "2222", "-l", "kevin", "--", "box"])- assert(Array(tunnelArguments(p, localPort: 50000, home: home).suffix(8))- == ["-L", "127.0.0.1:50000:127.0.0.1:19222", "-p", "2222", "-l", "kevin", "--", "box"])- assert(infoArguments(p, home: home).last?.hasSuffix(" codync-host info --json --port 19222'") == true)- assert(authRefused("kevin@box: Permission denied (publickey)."))- assert(!authRefused("ssh: connect to host box port 22: Connection refused"))- assert(tunnelArguments(p, localPort: 1, home: home).contains("ExitOnForwardFailure=yes"))- assert(validate(p) == nil)- assert(validate(SSHProfile(host: "-oProxyCommand=x", name: "")) != nil)- assert(validate(SSHProfile(host: "a b", name: "")) != nil)- assert(validate(SSHProfile(host: "box;rm", name: "")) != nil)- assert(validate(SSHProfile(host: "box", user: "1x", name: "")) != nil)- assert(validate(SSHProfile(host: "box", port: 0, name: "")) != nil)- assert(validate(SSHProfile(host: "box", identityFile: "/nonexistent/key", name: "")) != nil)- let config = "user kevin\nhostname 10.0.0.5\nport 2222\nhostkeyalias devbox\nproxycommand none\n"- let r = parseConfig(config)- assert(r == Resolved(hostname: "10.0.0.5", port: 2222, hostKeyAlias: "devbox", proxyJump: nil, proxyCommand: nil))- assert(r?.knownHostsName == "[devbox]:2222")- assert(parseConfig("hostname box\nport 22\nproxyjump gw\n")?.knownHostsName == "box")- assert(parseConfig("hostname box\nport 22\nproxyjump gw\n")?.usesProxy == true)- let scan = "# box:22 SSH-2.0\nbox ssh-ed25519 AAAA1\n[box]:22 ecdsa-sha2-nistp256 BBBB\n"- assert(hostKeys(scan) == ["ssh-ed25519 AAAA1", "ecdsa-sha2-nistp256 BBBB"])- assert(hostKeys("@revoked box ssh-ed25519 AAAA1\n").isEmpty)- assert(knownHostsLines(scan: scan, name: "[devbox]:2222")- == ["[devbox]:2222 ecdsa-sha2-nistp256 BBBB", "[devbox]:2222 ssh-ed25519 AAAA1"])- }- #endif-}--struct ProcessResult: Sendable {- var status: Int32- var stdout: Data- var stderr: String- var text: String { String(decoding: stdout, as: UTF8.self) }- /// The last thing the tool said, for showing next to an error.- var detail: String {- stderr.split(whereSeparator: \.isNewline).last.map(String.init) ?? ""- }-}--enum ProcessRunner {- /// Runs a tool to completion; both pipes are drained while it runs.- static func run(_ executable: URL, _ args: [String], input: Data? = nil) async -> ProcessResult {- let process = Process()- process.executableURL = executable- process.arguments = args- let out = Pipe()- let err = Pipe()- let inPipe = Pipe()- process.standardOutput = out- process.standardError = err- process.standardInput = input == nil ? FileHandle.nullDevice : inPipe- let outHandle = out.fileHandleForReading- let errHandle = err.fileHandleForReading- async let stdout = Task.detached { outHandle.readDataToEndOfFile() }.value- async let stderr = Task.detached { errHandle.readDataToEndOfFile() }.value- let status: Int32 = await withCheckedContinuation { cont in- process.terminationHandler = { cont.resume(returning: $0.terminationStatus) }- do {- try process.run()- } catch {- process.terminationHandler = nil- try? out.fileHandleForWriting.close()- try? err.fileHandleForWriting.close()- cont.resume(returning: -1)- return- }- if let input {- inPipe.fileHandleForWriting.write(input)- try? inPipe.fileHandleForWriting.close()- }- }- return await ProcessResult(status: status, stdout: stdout, stderr: String(decoding: stderr, as: UTF8.self))- }-}--/// ssh's stderr, read as it arrives. Left unread, the pipe fills at 64 KB and ssh blocks mid-write,-/// freezing the tunnel for good; each connection the far side refuses adds a line.-final class StderrTail: Sendable {- let pipe = Pipe()- /// The newest output (bounded) and whether ssh closed it.- private let state = OSAllocatedUnfairLock(initialState: (text: "", done: false))-- init() {- pipe.fileHandleForReading.readabilityHandler = { [state] handle in- let data = handle.availableData- if data.isEmpty { handle.readabilityHandler = nil }- let chunk = String(decoding: data, as: UTF8.self)- state.withLock { $0 = (String(($0.text + chunk).suffix(4096)), data.isEmpty) }- }- }-- /// ssh's last line, once it exited (waits briefly for the pipe to reach its end).- func lastLine() async -> String {- for _ in 0..<40 where !state.withLock({ $0.done }) {- try? await Task.sleep(for: .milliseconds(25))- }- return state.withLock { $0.text }.split(whereSeparator: \.isNewline).last.map(String.init) ?? ""- }-}--/// What `codync-host info --json` prints.-private struct RemoteInfo: Decodable {- var name: String- var computerId: ComputerID- var signKey: String- var boxKey: String?- var version: String?- var token: String- var running: Bool-}--/// `GET /health` on a loopback host.-struct HostHealth: Decodable {- var hostId: String?- var computerId: ComputerID?- var version: String?- var binaryPath: String?- var binaryHash: String?- var busy: Bool?-- static func fetch(_ baseURL: URL, timeout: TimeInterval = 2) async -> HostHealth? {- var request = URLRequest(url: baseURL.appending(path: "health"))- request.timeoutInterval = timeout- guard let (data, response) = try? await URLSession.shared.data(for: request),- (response as? HTTPURLResponse)?.statusCode == 200 else { return nil }- return try? JSONDecoder().decode(HostHealth.self, from: data)- }-}--/// SSH computers: profiles (UserDefaults), host key checks and one OpenSSH tunnel per connected profile.-/// Connected ones are handed to the account as loopback computers.-@MainActor-@Observable-final class SSHComputers {- enum Status: Equatable {- case idle- case connecting(String)- /// First time: the user compares these fingerprints before anything connects.- case confirmHostKey(name: String, fingerprints: [String], lines: [String])- case connected(localPort: Int)- /// A retry is scheduled.- case retrying(String)- /// Needs the user (settings, the remote side, or a security problem); nothing retries.- case failed(String)- case notInstalled- }-- struct Attachment {- var computer: Computer- var baseURL: URL- var token: String- }-- private static let defaultsKey = "sshProfiles"-- private(set) var profiles: [SSHProfile] = []- private(set) var status: [UUID: Status] = [:]- private(set) var attachments: [UUID: Attachment] = [:]-- var onAttach: ((Attachment) -> Void)?- var onDetach: ((ComputerID) -> Void)?-- private var tunnels: [UUID: Process] = [:]- private var tasks: [UUID: Task<Void, Never>] = [:]- private var backoff: [UUID: Double] = [:]- private var connectedAt: [UUID: Date] = [:]- /// Where `.ssh/known_hosts` and `.codync/ssh_known_hosts` live; tests point it elsewhere.- private let home: String-- init(home: String = SSH.home) {- self.home = home- profiles = UserDefaults.standard.data(forKey: Self.defaultsKey)- .flatMap { try? JSONDecoder().decode([SSHProfile].self, from: $0) } ?? []- }-- func status(of id: UUID) -> Status { status[id] ?? .idle }-- func connectAll() {- Task { [weak self] in- // Before this copy has tunnels of its own, so only leftovers from an earlier copy match.- if self?.tunnels.isEmpty == true, self?.tasks.isEmpty == true { await SSH.killOrphanTunnels() }- guard let self else { return }- for p in profiles where tasks[p.id] == nil && tunnels[p.id] == nil { connect(p.id) }- }- }-- func add(_ profile: SSHProfile) {- profiles.append(profile)- persist()- connect(profile.id)- }-- func update(_ profile: SSHProfile) {- guard let i = profiles.firstIndex(where: { $0.id == profile.id }) else { return }- disconnect(profile.id)- profiles[i] = profile- persist()- connect(profile.id)- }-- func remove(_ id: UUID) {- disconnect(id)- profiles.removeAll { $0.id == id }- status[id] = nil- backoff[id] = nil- persist()- }-- func connect(_ id: UUID) {- tasks[id]?.cancel()- tasks[id] = Task { [weak self] in await self?.run(id) }- }-- /// Ends the tunnel for this session (bots on it go away until the next connect).- func disconnect(_ id: UUID) {- tasks.removeValue(forKey: id)?.cancel()- stopTunnel(id)- status[id] = .idle- }-- func disconnectAll() {- for id in Array(tunnels.keys) + Array(tasks.keys) { disconnect(id) }- }-- /// The user compared the fingerprints: remember the key in Codync's known_hosts and go on.- func trustHostKey(_ id: UUID) {- guard case let .confirmHostKey(_, _, lines) = status(of: id) else { return }- do {- let dir = URL(filePath: home).appending(path: ".codync")- try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])- let file = dir.appending(path: "ssh_known_hosts")- if !FileManager.default.fileExists(atPath: file.path) {- FileManager.default.createFile(atPath: file.path, contents: nil, attributes: [.posixPermissions: 0o600])- }- let handle = try FileHandle(forWritingTo: file)- defer { try? handle.close() }- try handle.seekToEnd()- try handle.write(contentsOf: Data((lines.joined(separator: "\n") + "\n").utf8))- } catch {- status[id] = .failed("Couldn't save the host key: \(error.localizedDescription)")- return- }- connect(id)- }-- // MARK: connecting-- private enum Outcome {- case attached- case stop(Status)- case retry(String)- }-- private func run(_ id: UUID) async {- while !Task.isCancelled {- guard let profile = profiles.first(where: { $0.id == id }) else { return }- let outcome = await attach(profile)- // Disconnected or replaced meanwhile: the newer task owns the state now.- guard !Task.isCancelled else { return }- switch outcome {- case .attached:- backoff[id] = nil- tasks[id] = nil- return- case let .stop(final):- status[id] = final- tasks[id] = nil- return- case let .retry(message):- let delay = backoff[id] ?? 1- backoff[id] = min(delay * 2, 30)- status[id] = .retrying(message)- // Full jitter, like the device relay backoff.- try? await Task.sleep(for: .seconds(Double.random(in: 0.5...max(0.5, delay))))- }- }- }-- private func attach(_ profile: SSHProfile) async -> Outcome {- let id = profile.id- if let problem = SSH.validate(profile) { return .stop(.failed(problem)) }- status[id] = .connecting("Reading SSH settings…")- let config = await ProcessRunner.run(SSH.ssh, SSH.resolveArguments(profile))- guard !Task.isCancelled else { return .stop(.idle) }- guard config.status == 0, let resolved = SSH.parseConfig(config.text) else {- return .stop(.failed("SSH couldn't read the settings for \(profile.host). \(config.detail)"))- }-- // Host key (never by reading ssh's error text).- let recorded = await recordedKeys(resolved.knownHostsName)- if recorded.isEmpty {- if resolved.usesProxy {- return .stop(.failed("\(profile.host) goes through a jump host. Connect once with ssh in Terminal to confirm its host key, then try again."))- }- status[id] = .connecting("Reading the host key…")- let scan = await ProcessRunner.run(SSH.keyscan, SSH.keyscanArguments(resolved))- let lines = SSH.knownHostsLines(scan: scan.text, name: resolved.knownHostsName)- guard !lines.isEmpty else { return .retry("Can't reach \(resolved.hostname):\(resolved.port).") }- let prints = await ProcessRunner.run(SSH.keygen, ["-l", "-f", "-"], input: Data((lines.joined(separator: "\n") + "\n").utf8))- let fingerprints = prints.text.split(whereSeparator: \.isNewline).map(String.init)- guard prints.status == 0, !fingerprints.isEmpty else { return .stop(.failed("Couldn't read the host key of \(profile.host).")) }- return .stop(.confirmHostKey(name: resolved.knownHostsName, fingerprints: fingerprints, lines: lines))- }-- status[id] = .connecting("Signing in…")- let result = await ProcessRunner.run(SSH.ssh, SSH.infoArguments(profile, home: home))- guard !Task.isCancelled else { return .stop(.idle) }- if result.status == 255 {- if SSH.authRefused(result.stderr) { return .stop(.failed(Self.signInRefused(profile))) }- if !resolved.usesProxy {- let scan = await ProcessRunner.run(SSH.keyscan, SSH.keyscanArguments(resolved))- let current = SSH.hostKeys(scan.text)- // Only plain host keys can be compared: a `@cert-authority` key is never what keyscan returns.- let pinned = await recordedKeys(resolved.knownHostsName, certAuthorities: false)- if !current.isEmpty, !pinned.isEmpty, current.isDisjoint(with: pinned) {- return .stop(.failed("The host key of \(profile.host) changed. This can mean someone is intercepting the connection. Codync won't connect until the old key is removed from known_hosts."))- }- }- return .retry("SSH couldn't connect to \(profile.host). \(result.detail)")- }- if result.status == 127 { return .stop(.notInstalled) }- guard let info = try? JSONDecoder().decode(RemoteInfo.self, from: result.stdout) else {- if result.status == 0 { return .stop(.notInstalled) }- return .stop(.failed("codync-host on \(profile.host) couldn't report its identity. Run `codync-host install` there. \(result.detail)"))- }- let computer = Computer(id: info.computerId, name: info.name, signKey: info.signKey, boxKey: info.boxKey)- guard computer.isConsistent else { return .stop(.failed("\(profile.host) reported an invalid identity.")) }- if let known = profile.computerId, known != info.computerId {- return .stop(.failed("\(profile.host) is now a different computer than the one saved. If it was reinstalled, remove it and add it again."))- }- if profile.computerId == nil { remember(info.computerId, name: info.name, for: id) }- guard info.running else {- return .retry("codync-host is installed on \(info.name) but not running. Run `codync-host install` there.")- }-- // Tunnel: a free loopback port each attempt; a port taken in between just makes ssh exit (ExitOnForwardFailure).- var lastProblem = ""- for _ in 0..<3 {- guard let port = Self.freeLocalPort() else { return .retry("No free local port for the tunnel.") }- status[id] = .connecting("Opening the tunnel…")- let process: Process- let stderr = StderrTail()- do {- process = try startTunnel(profile, localPort: port, stderr: stderr.pipe)- } catch {- return .stop(.failed("Couldn't start ssh: \(error.localizedDescription)"))- }- let baseURL = URL(string: "http://127.0.0.1:\(port)")!- var health: HostHealth?- for _ in 0..<60 where process.isRunning && !Task.isCancelled {- if let h = await HostHealth.fetch(baseURL, timeout: 1) {- health = h- break- }- try? await Task.sleep(for: .milliseconds(250))- }- guard !Task.isCancelled else {- process.terminate()- return .stop(.idle)- }- guard let health else {- if process.isRunning {- process.terminate()- } else {- lastProblem = await stderr.lastLine()- }- continue- }- guard health.computerId == info.computerId else {- process.terminate()- return .stop(.failed("The tunnel to \(profile.host) reached a different computer than expected."))- }- // /health is public, so the answer alone doesn't prove it came through ssh: another- // local user could have taken the port. Only a listener ssh owns gets the token.- let listens = await Self.sshListens(pid: process.processIdentifier, port: port)- // Disconnected, removed or edited meanwhile: this attempt must not register its tunnel.- guard !Task.isCancelled else {- process.terminate()- return .stop(.idle)- }- guard listens, process.isRunning else {- log.error("tunnel port \(port) answered by something other than ssh")- process.terminate()- lastProblem = "Another program answered on the tunnel's local port."- continue- }- watch(process, id: id, stderr: stderr)- tunnels[id] = process- connectedAt[id] = .now- status[id] = .connected(localPort: port)- let attachment = Attachment(computer: computer, baseURL: baseURL, token: info.token)- attachments[id] = attachment- onAttach?(attachment)- return .attached- }- if SSH.authRefused(lastProblem) { return .stop(.failed(Self.signInRefused(profile))) }- return .retry("Couldn't open the tunnel to \(profile.host). \(lastProblem)")- }-- private static func signInRefused(_ profile: SSHProfile) -> String {- "\(profile.host) refused the key. Codync signs in with an SSH key (ssh-agent or the key file) and can't type a password or passphrase; make `ssh \(profile.host)` work in Terminal without prompting, then connect again."- }-- private func recordedKeys(_ name: String, certAuthorities: Bool = true) async -> Set<String> {- var keys = Set<String>()- for file in SSH.knownHostsFiles(home: home) where FileManager.default.fileExists(atPath: file) {- let found = await ProcessRunner.run(SSH.keygen, ["-F", name, "-f", file])- if found.status == 0 { keys.formUnion(SSH.hostKeys(found.text, certAuthorities: certAuthorities)) }- }- return keys- }-- private func startTunnel(_ profile: SSHProfile, localPort: Int, stderr: Pipe) throws -> Process {- let process = Process()- process.executableURL = SSH.ssh- process.arguments = SSH.tunnelArguments(profile, localPort: localPort, home: home)- process.standardInput = FileHandle.nullDevice- process.standardOutput = FileHandle.nullDevice- process.standardError = stderr- try process.run()- return process- }-- /// A tunnel that drops is reopened with backoff (reset once it stayed up a minute).- private func watch(_ process: Process, id: UUID, stderr: StderrTail) {- process.terminationHandler = { [weak self] ended in- Task { @MainActor [weak self] in- let detail = await stderr.lastLine()- self?.tunnelEnded(id, process: ended, detail: detail)- }- }- }-- private func tunnelEnded(_ id: UUID, process: Process, detail: String) {- // Only the current tunnel: a replaced or disconnected one ends without effect.- guard tunnels[id] === process else { return }- log.info("ssh tunnel ended: \(detail, privacy: .public)")- if let since = connectedAt[id], Date.now.timeIntervalSince(since) >= 60 { backoff[id] = nil }- stopTunnel(id)- status[id] = .retrying("The SSH connection dropped. \(detail)")- connect(id)- }-- private func stopTunnel(_ id: UUID) {- if let process = tunnels.removeValue(forKey: id) {- process.terminationHandler = nil- process.terminate()- }- connectedAt[id] = nil- if let attachment = attachments.removeValue(forKey: id) { onDetach?(attachment.computer.id) }- }-- private func remember(_ computerId: ComputerID, name: String, for id: UUID) {- guard let i = profiles.firstIndex(where: { $0.id == id }) else { return }- profiles[i].computerId = computerId- if profiles[i].name.isEmpty { profiles[i].name = name }- persist()- }-- private func persist() {- if let data = try? JSONEncoder().encode(profiles) { UserDefaults.standard.set(data, forKey: Self.defaultsKey) }- }-- /// Whether process `pid` holds the listening socket on 127.0.0.1:`port`.- nonisolated static func sshListens(pid: Int32, port: Int) async -> Bool {- let found = await ProcessRunner.run(SSH.lsof, ["-a", "-n", "-P", "-p", String(pid), "[email protected]:\(port)", "-sTCP:LISTEN", "-t"])- return found.status == 0 && found.text.split(whereSeparator: \.isNewline).contains(Substring(String(pid)))- }-- /// Binds port 0 on loopback to learn a free port.- nonisolated static func freeLocalPort() -> Int? {- let fd = socket(AF_INET, SOCK_STREAM, 0)- guard fd >= 0 else { return nil }- defer { close(fd) }- var addr = sockaddr_in()- addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)- addr.sin_family = sa_family_t(AF_INET)- addr.sin_port = 0- addr.sin_addr.s_addr = inet_addr("127.0.0.1")- var len = socklen_t(MemoryLayout<sockaddr_in>.size)- let bound = withUnsafeMutablePointer(to: &addr) { ptr in- ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sa in- bind(fd, sa, len) == 0 && getsockname(fd, sa, &len) == 0- }- }- guard bound else { return nil }- return Int(UInt16(bigEndian: addr.sin_port))- }-}diff --git a/apps/macos/App/UpdatesManager.swift b/apps/macos/App/UpdatesManager.swiftdeleted file mode 100644index e39c0d2f..00000000--- a/apps/macos/App/UpdatesManager.swift+++ /dev/null@@ -1,275 +0,0 @@-import AppKit-import CodyncKit-import Observation-import Sparkle--/// Sparkle owns download, signature verification and app replacement. Codync-/// coordinates its background services before letting the installer proceed.-@MainActor-@Observable-final class UpdatesManager: NSObject, SPUUpdaterDelegate, @preconcurrency SPUStandardUserDriverDelegate {- private(set) var canCheckForUpdates = false- private(set) var availableVersion: String?- private(set) var lastUpdateCheckDate: Date?- private(set) var errorMessage: String?- private(set) var hasStagedUpdate = false- private(set) var preparingInstallation = false- /// The iPhone app the available release needs while the App Store doesn't have it yet.- private(set) var waitingForApp: String?-- var automaticallyChecksForUpdates = true {- didSet { controller?.updater.automaticallyChecksForUpdates = automaticallyChecksForUpdates }- }- var automaticallyDownloadsUpdates = false {- didSet { controller?.updater.automaticallyDownloadsUpdates = automaticallyDownloadsUpdates }- }-- #if DEBUG- let isSupported = false- #else- let isSupported = true- #endif-- @ObservationIgnored private weak var host: HostController?- @ObservationIgnored private var controller: SPUStandardUpdaterController?- @ObservationIgnored private var observations: [NSKeyValueObservation] = []- @ObservationIgnored private var idleTask: Task<Void, Never>?- @ObservationIgnored private var pendingInstall: (() -> Void)?- @ObservationIgnored private var automaticInstall: (() -> Void)?- @ObservationIgnored private var servicesPrepared = false- @ObservationIgnored private var preparationTask: Task<Bool, Never>?- /// For the App Store gate, refreshed before manual checks and every few hours: Sparkle asks- /// its delegate synchronously (docs/reference/compatibility.md).- @ObservationIgnored private var appStoreVersion: String?- @ObservationIgnored private var iphonesPaired: Bool?- @ObservationIgnored private var gateTask: Task<Void, Never>?-- func start(host: HostController) {- guard controller == nil, isSupported else { return }- self.host = host- let controller = SPUStandardUpdaterController(startingUpdater: false, updaterDelegate: self, userDriverDelegate: self)- self.controller = controller- let updater = controller.updater- observations = [- updater.observe(\.canCheckForUpdates, options: [.initial, .new]) { [weak self] _, _ in- Task { @MainActor in self?.readSettings() }- },- updater.observe(\.lastUpdateCheckDate, options: [.initial, .new]) { [weak self] _, _ in- Task { @MainActor in self?.readSettings() }- },- updater.observe(\.automaticallyChecksForUpdates, options: [.new]) { [weak self] _, _ in- Task { @MainActor in self?.readSettings() }- },- updater.observe(\.automaticallyDownloadsUpdates, options: [.new]) { [weak self] _, _ in- Task { @MainActor in self?.readSettings() }- },- ]- do {- try updater.start()- readSettings()- } catch {- errorMessage = error.localizedDescription- }- gateTask = Task { [weak self] in- while !Task.isCancelled, let interval = await self?.gateTick() {- try? await Task.sleep(for: interval)- }- }- }-- /// Refreshes the gate; while waiting for the iPhone app it looks hourly and checks for the- /// update as soon as the App Store has it, instead of at the next daily check.- private func gateTick() async -> Duration {- await refreshGate()- if let required = waitingForApp, let store = appStoreVersion,- AppVersion.parse(store) != nil, !AppVersion.isBelow(store, required) {- controller?.updater.checkForUpdatesInBackground()- }- return .seconds(waitingForApp == nil ? 6 * 3600 : 3600)- }-- private func refreshGate() async {- if let version = try? await AppStoreRelease.latestVersion() { appStoreVersion = version }- if let devices = try? await host?.store?.client?.devices() {- iphonesPaired = devices.contains { $0.platform == "ios" }- }- }-- private func readSettings() {- guard let updater = controller?.updater else { return }- canCheckForUpdates = updater.canCheckForUpdates- lastUpdateCheckDate = updater.lastUpdateCheckDate- if automaticallyChecksForUpdates != updater.automaticallyChecksForUpdates {- automaticallyChecksForUpdates = updater.automaticallyChecksForUpdates- }- if automaticallyDownloadsUpdates != updater.automaticallyDownloadsUpdates {- automaticallyDownloadsUpdates = updater.automaticallyDownloadsUpdates- }- }-- func checkForUpdates() {- if let pendingInstall {- prepareAndContinue(pendingInstall)- return- }- if let install = automaticInstall {- automaticInstall = nil- idleTask?.cancel()- prepareAndContinue(install)- return- }- guard canCheckForUpdates else { return }- errorMessage = nil- NSApp.activate()- Task {- await refreshGate()- controller?.checkForUpdates(nil)- }- }-- func retryInstallation() {- guard let pendingInstall else { return }- prepareAndContinue(pendingInstall)- }-- private func prepareAndContinue(_ install: @escaping () -> Void) {- guard !preparingInstallation else { return }- pendingInstall = install- preparingInstallation = true- Task {- defer { preparingInstallation = false }- if await prepareServices() {- pendingInstall = nil- install()- }- }- }-- /// Also used on Quit: Sparkle may install a staged update without relaunching,- /// in which case its postpone-relaunch delegate is not guaranteed to run.- func prepareServices() async -> Bool {- if servicesPrepared { return true }- if let preparationTask { return await preparationTask.value }- let task = Task { await self.stopServices() }- preparationTask = task- let ready = await task.value- preparationTask = nil- return ready- }-- private func stopServices() async -> Bool {- guard let host else { return false }- do {- try await host.prepareForUpdate()- guard !Task.isCancelled else {- host.resumeAfterCancelledUpdate()- return false- }- servicesPrepared = true- errorMessage = nil- return true- } catch {- errorMessage = "Update paused: \(error.localizedDescription)"- host.resumeAfterCancelledUpdate()- return false- }- }-- /// A release that needs a newer iPhone app than the App Store has (still in review) waits,- /// so paired iPhones aren't asked for an update they can't get yet. Without an answer from- /// the App Store, background checks wait and a check the person started goes ahead.- func updater(_ updater: SPUUpdater, shouldProceedWithUpdate item: SUAppcastItem, updateCheck: SPUUpdateCheck) throws {- waitingForApp = nil- guard let required = item.propertiesDictionary["codync:minApp"] as? String,- AppVersion.isBelow(host?.store?.hostVersion?.minApp ?? "0", required),- iphonesPaired != false else { return }- if let appStoreVersion, AppVersion.parse(appStoreVersion) != nil, !AppVersion.isBelow(appStoreVersion, required) {- return- }- if appStoreVersion == nil && updateCheck == .updates { return }- waitingForApp = required- throw NSError(domain: "Codync", code: 1, userInfo: [NSLocalizedDescriptionKey:- "Codync \(item.displayVersionString) needs the iPhone app \(required), which isn't in the App Store yet. "- + "It installs once that version passes review."])- }-- func updater(_ updater: SPUUpdater, shouldPostponeRelaunchForUpdate item: SUAppcastItem,- untilInvokingBlock installHandler: @escaping () -> Void) -> Bool {- hasStagedUpdate = true- prepareAndContinue(installHandler)- return true- }-- func updater(_ updater: SPUUpdater, willInstallUpdate item: SUAppcastItem) {- hasStagedUpdate = true- }-- func updater(_ updater: SPUUpdater, willInstallUpdateOnQuit item: SUAppcastItem,- immediateInstallationBlock installHandler: @escaping () -> Void) -> Bool {- hasStagedUpdate = true- availableVersion = item.displayVersionString- automaticInstall = installHandler- idleTask?.cancel()- idleTask = Task { [weak self] in- while !Task.isCancelled {- try? await Task.sleep(for: .seconds(30))- guard !Task.isCancelled, let self else { return }- guard self.automaticallyDownloadsUpdates, !NSApp.isActive,- CGEventSource.secondsSinceLastEventType(.combinedSessionState, eventType: .null) >= 600,- await self.host?.isIdleForUpdate() == true,- let install = self.automaticInstall else { continue }- self.automaticInstall = nil- self.prepareAndContinue(install)- return- }- }- return true- }-- func updater(_ updater: SPUUpdater, didAbortWithError error: Error) {- idleTask?.cancel()- preparationTask?.cancel()- pendingInstall = nil- automaticInstall = nil- hasStagedUpdate = false- servicesPrepared = false- availableVersion = nil- // No-update and user cancellation are ordinary outcomes; Sparkle shows- // actionable errors in its standard interface for a manual update check.- let failure = error as NSError- let ordinary = failure.domain == SUSparkleErrorDomain &&- [Int(SUError.noUpdateError.rawValue), Int(SUError.installationCanceledError.rawValue)].contains(failure.code)- errorMessage = ordinary ? nil : error.localizedDescription- host?.resumeAfterCancelledUpdate()- readSettings()- }-- var supportsGentleScheduledUpdateReminders: Bool { true }-- func standardUserDriverShouldHandleShowingScheduledUpdate(_ update: SUAppcastItem,- andInImmediateFocus immediateFocus: Bool) -> Bool {- NSApp.isActive && immediateFocus- }-- func standardUserDriverWillHandleShowingUpdate(_ handleShowingUpdate: Bool,- forUpdate update: SUAppcastItem, state: SPUUserUpdateState) {- availableVersion = update.displayVersionString- if state.userInitiated { NSApp.activate() }- }-}--/// Normal Quit leaves the daemon running. If Sparkle has staged an update,-/// termination waits until the background services have actually stopped.-@MainActor-final class CodyncAppDelegate: NSObject, NSApplicationDelegate {- weak var updates: UpdatesManager?-- func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {- guard let updates, updates.hasStagedUpdate else { return .terminateNow }- Task {- let ready = await updates.prepareServices()- sender.reply(toApplicationShouldTerminate: ready)- }- return .terminateLater- }-}diff --git a/apps/macos/Resources/AppIcon.icon/Assets/image 9.png b/apps/macos/Resources/AppIcon.icon/Assets/image 9.pngdeleted file mode 100644index bdcad6b1..00000000Binary files a/apps/macos/Resources/AppIcon.icon/Assets/image 9.png and /dev/null differdiff --git a/apps/macos/Resources/AppIcon.icon/icon.json b/apps/macos/Resources/AppIcon.icon/icon.jsondeleted file mode 100644index c1bf43c2..00000000--- a/apps/macos/Resources/AppIcon.icon/icon.json+++ /dev/null@@ -1,30 +0,0 @@-{- "fill" : {- "automatic-gradient" : "extended-srgb:0.00000,0.53333,1.00000,1.00000"- },- "groups" : [- {- "layers" : [- {- "glass" : false,- "image-name" : "image 9.png",- "name" : "image 9"- }- ],- "shadow" : {- "kind" : "neutral",- "opacity" : 0.5- },- "translucency" : {- "enabled" : true,- "value" : 0.3- }- }- ],- "supported-platforms" : {- "circles" : [- "watchOS"- ],- "squares" : "shared"- }-}\ No newline at end of filediff --git a/apps/macos/Resources/Assets.xcassets/AccentColor.colorset/Contents.json b/apps/macos/Resources/Assets.xcassets/AccentColor.colorset/Contents.jsondeleted file mode 100644index c5c8730a..00000000--- a/apps/macos/Resources/Assets.xcassets/AccentColor.colorset/Contents.json+++ /dev/null@@ -1,8 +0,0 @@-{- "colors" : [- { "color" : { "color-space" : "srgb", "components" : { "alpha" : "1.000", "blue" : "0.000", "green" : "0.000", "red" : "0.000" } }, "idiom" : "universal" },- { "appearances" : [ { "appearance" : "luminosity", "value" : "dark" } ],- "color" : { "color-space" : "srgb", "components" : { "alpha" : "1.000", "blue" : "1.000", "green" : "1.000", "red" : "1.000" } }, "idiom" : "universal" }- ],- "info" : { "author" : "xcode", "version" : 1 }-}diff --git a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json b/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/Contents.jsondeleted file mode 100644index a8374815..00000000--- a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json+++ /dev/null@@ -1,68 +0,0 @@-{- "images" : [- {- "filename" : "image.png",- "idiom" : "mac",- "scale" : "1x",- "size" : "16x16"- },- {- "filename" : "image 1.png",- "idiom" : "mac",- "scale" : "2x",- "size" : "16x16"- },- {- "filename" : "image 2.png",- "idiom" : "mac",- "scale" : "1x",- "size" : "32x32"- },- {- "filename" : "image 3.png",- "idiom" : "mac",- "scale" : "2x",- "size" : "32x32"- },- {- "filename" : "image 4.png",- "idiom" : "mac",- "scale" : "1x",- "size" : "128x128"- },- {- "filename" : "image 5.png",- "idiom" : "mac",- "scale" : "2x",- "size" : "128x128"- },- {- "filename" : "image 7.png",- "idiom" : "mac",- "scale" : "1x",- "size" : "256x256"- },- {- "filename" : "image 6.png",- "idiom" : "mac",- "scale" : "2x",- "size" : "256x256"- },- {- "filename" : "image 8.png",- "idiom" : "mac",- "scale" : "1x",- "size" : "512x512"- },- {- "filename" : "image 9.png",- "idiom" : "mac",- "scale" : "2x",- "size" : "512x512"- }- ],- "info" : {- "author" : "xcode",- "version" : 1- }-}diff --git a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 1.png b/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 1.pngdeleted file mode 100644index 0db82964..00000000Binary files a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 1.png and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 2.png b/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 2.pngdeleted file mode 100644index 0db82964..00000000Binary files a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 2.png and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 3.png b/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 3.pngdeleted file mode 100644index fd310efd..00000000Binary files a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 3.png and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 4.png b/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 4.pngdeleted file mode 100644index d6d0f941..00000000Binary files a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 4.png and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 5.png b/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 5.pngdeleted file mode 100644index 2484c79a..00000000Binary files a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 5.png and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 6.png b/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 6.pngdeleted file mode 100644index 13f0c03d..00000000Binary files a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 6.png and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 7.png b/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 7.pngdeleted file mode 100644index 2484c79a..00000000Binary files a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 7.png and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 8.png b/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 8.pngdeleted file mode 100644index 13f0c03d..00000000Binary files a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 8.png and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 9.png b/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 9.pngdeleted file mode 100644index bdcad6b1..00000000Binary files a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image 9.png and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image.png b/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image.pngdeleted file mode 100644index fa848e1c..00000000Binary files a/apps/macos/Resources/Assets.xcassets/AppIcon.appiconset/image.png and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/MenuBarIcon.imageset/Contents.json b/apps/macos/Resources/Assets.xcassets/MenuBarIcon.imageset/Contents.jsondeleted file mode 100644index 1d16ad4e..00000000--- a/apps/macos/Resources/Assets.xcassets/MenuBarIcon.imageset/Contents.json+++ /dev/null@@ -1,8 +0,0 @@-{- "images" : [- { "filename" : "[email protected]", "idiom" : "universal", "scale" : "1x" },- { "filename" : "[email protected]", "idiom" : "universal", "scale" : "2x" }- ],- "info" : { "author" : "xcode", "version" : 1 },- "properties" : { "template-rendering-intent" : "template" }-}diff --git a/apps/macos/Resources/Assets.xcassets/MenuBarIcon.imageset/[email protected] b/apps/macos/Resources/Assets.xcassets/MenuBarIcon.imageset/[email protected]deleted file mode 100644index af50cc7b..00000000Binary files a/apps/macos/Resources/Assets.xcassets/MenuBarIcon.imageset/[email protected] and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/MenuBarIcon.imageset/[email protected] b/apps/macos/Resources/Assets.xcassets/MenuBarIcon.imageset/[email protected]deleted file mode 100644index d62e2825..00000000Binary files a/apps/macos/Resources/Assets.xcassets/MenuBarIcon.imageset/[email protected] and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/MenuBarIconAlert.imageset/Contents.json b/apps/macos/Resources/Assets.xcassets/MenuBarIconAlert.imageset/Contents.jsondeleted file mode 100644index 6b5e3083..00000000--- a/apps/macos/Resources/Assets.xcassets/MenuBarIconAlert.imageset/Contents.json+++ /dev/null@@ -1,8 +0,0 @@-{- "images" : [- { "filename" : "[email protected]", "idiom" : "universal", "scale" : "1x" },- { "filename" : "[email protected]", "idiom" : "universal", "scale" : "2x" }- ],- "info" : { "author" : "xcode", "version" : 1 },- "properties" : { "template-rendering-intent" : "template" }-}diff --git a/apps/macos/Resources/Assets.xcassets/MenuBarIconAlert.imageset/[email protected] b/apps/macos/Resources/Assets.xcassets/MenuBarIconAlert.imageset/[email protected]deleted file mode 100644index 985c934b..00000000Binary files a/apps/macos/Resources/Assets.xcassets/MenuBarIconAlert.imageset/[email protected] and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/MenuBarIconAlert.imageset/[email protected] b/apps/macos/Resources/Assets.xcassets/MenuBarIconAlert.imageset/[email protected]deleted file mode 100644index 6f013241..00000000Binary files a/apps/macos/Resources/Assets.xcassets/MenuBarIconAlert.imageset/[email protected] and /dev/null differdiff --git a/apps/macos/Resources/Assets.xcassets/google.imageset/Contents.json b/apps/macos/Resources/Assets.xcassets/google.imageset/Contents.jsondeleted file mode 100644index 56369403..00000000--- a/apps/macos/Resources/Assets.xcassets/google.imageset/Contents.json+++ /dev/null@@ -1,5 +0,0 @@-{- "images" : [ { "filename" : "google.svg", "idiom" : "universal" } ],- "info" : { "author" : "xcode", "version" : 1 },- "properties" : { "preserves-vector-representation" : true, "template-rendering-intent" : "original" }-}diff --git a/apps/macos/Resources/Assets.xcassets/google.imageset/google.svg b/apps/macos/Resources/Assets.xcassets/google.imageset/google.svgdeleted file mode 100644index afd6b4f6..00000000--- a/apps/macos/Resources/Assets.xcassets/google.imageset/google.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/><path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/><path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/><path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/></svg>diff --git a/apps/macos/Resources/Info.plist b/apps/macos/Resources/Info.plistdeleted file mode 100644index 3616103c..00000000--- a/apps/macos/Resources/Info.plist+++ /dev/null@@ -1,20 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>SUFeedURL</key>- <string>https://github.com/leepokai/Codync/releases/latest/download/appcast.xml</string>- <key>SUPublicEDKey</key>- <string>/WvuKYw0ghkj3ExQbCejTquAcozuP1Llo2k8TIvx0Mc=</string>- <key>SUEnableAutomaticChecks</key>- <true/>- <key>SUAutomaticallyUpdate</key>- <false/>- <key>SUAllowsAutomaticUpdates</key>- <true/>- <key>SUScheduledCheckInterval</key>- <integer>86400</integer>- <key>SUVerifyUpdateBeforeExtraction</key>- <true/>-</dict>-</plist>diff --git a/apps/macos/Resources/macOS.entitlements b/apps/macos/Resources/macOS.entitlementsdeleted file mode 100644index d6f09afc..00000000--- a/apps/macos/Resources/macOS.entitlements+++ /dev/null@@ -1,8 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyLists-1.0.dtd">-<plist version="1.0">-<dict>- <key>com.apple.security.device.audio-input</key>- <true/>-</dict>-</plist>diff --git a/apps/macos/Views/ChatWindow.swift b/apps/macos/Views/ChatWindow.swiftdeleted file mode 100644index 25845f82..00000000--- a/apps/macos/Views/ChatWindow.swift+++ /dev/null@@ -1,1252 +0,0 @@-import CodyncKit-import CodyncUI-import SwiftUI--/// Native desktop chat: roster on the left, the conversation on the right-/// (Grok Bot's desktop layout), sharing its views with the iPhone app.-struct ChatWindow: View {- @Environment(HostController.self) private var host- @Environment(AccountSession.self) private var account- @Environment(\.accessibilityReduceMotion) private var reduceMotion- @AppStorage("macAccountOnboardingCompleted") private var accountOnboardingCompleted = false-- private var showsChat: Bool { host.state == .running || !host.accounts.computers.isEmpty }-- var body: some View {- ZStack {- if account.isSignedIn || accountOnboardingCompleted {- if showsChat {- ChatSplitView().id(host.contextID)- .transition(.opacity)- } else {- hostState- .transition(.opacity.combined(with: .scale(scale: 0.97)))- }- } else if !account.isReady {- AccountRestoreView(onContinue: { accountOnboardingCompleted = true })- .transition(.opacity)- } else {- AccountWelcomeView(- isConfigured: account.isConfigured,- isBusy: account.isBusy,- errorMessage: account.errorMessage,- onContinue: { accountOnboardingCompleted = true },- onSignIn: { provider in- Task { await account.signIn(provider: provider) }- }- )- .transition(.opacity)- }- }- .animation(Motion.reduced(Motion.layout, reduceMotion), value: showsChat)- .animation(Motion.reduced(Motion.layout, reduceMotion), value: host.state)- .animation(Motion.reduced(Motion.fade, reduceMotion), value: accountOnboardingCompleted)- .onChange(of: account.isSignedIn) { _, signedIn in- if signedIn { accountOnboardingCompleted = true }- }- .task {- if account.isSignedIn { accountOnboardingCompleted = true }- }- .frame(minWidth: 760, minHeight: 500)- .frame(maxWidth: .infinity, maxHeight: .infinity)- .background(Palette.background)- .tint(Palette.accent)- .ignoresSafeArea(.container, edges: .top)- .codyncDialog("Reset all data?", isPresented: Bindable(host).confirmsReset,- message: "Signs out every account and deletes this Mac's bots, conversations, keys and settings. Codync then starts over from the welcome screen.") {- [DialogAction("Reset everything", destructive: true) { Task { await host.resetAllData() } }]- }- // Approving a device: the code the device shows must match (spec §4.2 B).- // It closes when the request is decided or put off (both change `currentApproval`);- // closing it puts the request off.- .codyncSheet(isPresented: Binding(- get: { host.currentApproval != nil },- set: { if !$0, let approval = host.currentApproval { host.deferApproval(approval) } }- )) {- CurrentApprovalSheet()- }- }-}--/// Keep first-run sign-in choices behind Clerk's persisted-session restoration on launch.-private struct AccountRestoreView: View {- let onContinue: () -> Void-- var body: some View {- VStack(spacing: 14) {- Spinner(size: 24)- Text("Checking for a saved account…")- .appFont(.callout)- .foregroundStyle(Palette.secondary)- Button("Continue on this Mac", action: onContinue)- .buttonStyle(.plain)- .foregroundStyle(Palette.secondary)- }- .frame(maxWidth: .infinity, maxHeight: .infinity)- }-}--/// First-run account choice. Existing Clerk sessions skip this screen as soon as Clerk restores them.-private struct AccountWelcomeView: View {- let isConfigured: Bool- let isBusy: Bool- let errorMessage: String?- let onContinue: () -> Void- let onSignIn: (AccountSession.SignInProvider) -> Void- @Environment(\.accessibilityReduceMotion) private var reduceMotion- @State private var beat = 0-- var body: some View {- GeometryReader { geometry in- ScrollView {- content- .frame(minHeight: geometry.size.height)- .frame(maxWidth: 480)- .frame(maxWidth: .infinity)- }- .scrollBounceBehavior(.basedOnSize)- }- .background(Palette.background)- .task {- if reduceMotion { beat = 4; return }- for next in 1...4 {- try? await Task.sleep(for: .milliseconds(next == 1 ? 150 : 280))- withAnimation(.spring(duration: 0.6, bounce: 0.25)) { beat = next }- }- }- }-- private var content: some View {- VStack(alignment: .leading, spacing: 0) {- Spacer(minLength: 24)-- WelcomeCrew(shown: beat >= 1)- .frame(maxWidth: .infinity)-- Spacer(minLength: 24)-- WelcomeChatGlimpse(shown: beat >= 2)- .padding(.bottom, 24)-- VStack(alignment: .leading, spacing: 10) {- Text("Your coding agents,\nas teammates.")- .appFont(.system(size: 34, weight: .semibold))- .tracking(-0.6)- .foregroundStyle(Palette.text)- .fixedSize(horizontal: false, vertical: true)- Text("Give each one a name and a project. They work on your computer while you're away.")- .appFont(.body)- .foregroundStyle(Palette.secondary)- }- .opacity(beat >= 3 ? 1 : 0)- .offset(y: beat >= 3 ? 0 : 14)-- Spacer(minLength: 32)-- VStack(spacing: 10) {- Button(action: onContinue) {- Text("Continue on this Mac")- .appFont(.headline)- .frame(maxWidth: .infinity, minHeight: 50)- }- .buttonStyle(.primary)-- Button { onSignIn(.apple) } label: {- ZStack {- HStack(spacing: 10) {- Image(systemName: "apple.logo").appFont(.system(size: 20))- Text("Continue with Apple")- }- .opacity(isBusy ? 0 : 1)- if isBusy { Spinner(size: 18) }- }- .appFont(.headline)- .frame(maxWidth: .infinity, minHeight: 50)- }- .buttonStyle(.primary)- .disabled(!isConfigured || isBusy)-- Button { onSignIn(.google) } label: {- ZStack {- HStack(spacing: 10) {- Image("google")- .resizable()- .scaledToFit()- .frame(width: 20, height: 20)- Text("Continue with Google")- }- .opacity(isBusy ? 0 : 1)- if isBusy { Spinner(size: 18) }- }- .appFont(.headline)- .frame(maxWidth: .infinity, minHeight: 50)- }- .buttonStyle(.secondary)- .disabled(!isConfigured || isBusy)-- if !isConfigured {- Text("Sign-in isn't configured in this build. You can still use Codync on this Mac.")- .appFont(.footnote)- .foregroundStyle(Palette.tertiary)- .fixedSize(horizontal: false, vertical: true)- }- if let errorMessage {- Text(errorMessage)- .appFont(.footnote)- .foregroundStyle(Palette.warning)- .fixedSize(horizontal: false, vertical: true)- }- }- .opacity(beat >= 4 ? 1 : 0)- .offset(y: beat >= 4 ? 0 : 14)- }- .padding(.horizontal, 24)- .padding(.bottom, 12)- }-}--/// The animated bot group from the first iPhone onboarding screen.-private struct WelcomeCrew: View {- let shown: Bool- @Environment(\.accessibilityReduceMotion) private var reduceMotion-- private let members: [(shape: String, color: String, size: CGFloat, x: CGFloat, y: CGFloat, mood: CharacterAvatar.Mood)] = [- ("blob", "blue", 92, 0, 0, .working),- ("squircle", "orange", 64, -104, -34, .idle),- ("teardrop", "violet", 58, 100, -46, .working),- ("hex", "green", 48, -76, 64, .idle),- ("cloud", "magenta", 52, 84, 58, .needsInput),- ]-- var body: some View {- TimelineView(.animation(paused: reduceMotion || !shown)) { context in- let time = context.date.timeIntervalSinceReferenceDate- ZStack {- ForEach(members.indices, id: \.self) { index in- let member = members[index]- CharacterAvatar(shape: member.shape, color: member.color, size: member.size, mood: member.mood)- .offset(x: member.x, y: member.y + (reduceMotion ? 0 : sin(time * 1.3 + Double(index) * 1.7) * 5))- .scaleEffect(shown ? 1 : 0.3)- .opacity(shown ? 1 : 0)- .animation(.spring(duration: 0.7, bounce: 0.4).delay(Double(index) * 0.07), value: shown)- }- }- }- .frame(height: 170)- .accessibilityHidden(true)- }-}--/// A short animated user and bot exchange, matching the iPhone onboarding preview.-private struct WelcomeChatGlimpse: View {- let shown: Bool- @Environment(\.accessibilityReduceMotion) private var reduceMotion- @State private var replied = false-- var body: some View {- VStack(alignment: .leading, spacing: 10) {- Text("Fix the flaky login test")- .appFont(.subheadline)- .foregroundStyle(Palette.text)- .padding(.horizontal, 14)- .padding(.vertical, 9)- .background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 18))- .frame(maxWidth: .infinity, alignment: .trailing)- .opacity(shown ? 1 : 0)- .offset(y: shown ? 0 : 14)-- HStack(alignment: .bottom, spacing: 8) {- CharacterAvatar(shape: "blob", color: "blue", size: 28, mood: replied ? .idle : .working)- if replied {- Text("Done. It raced the session refresh; tests pass on fix/login.")- .appFont(.subheadline)- .foregroundStyle(Palette.text)- .padding(.horizontal, 14)- .padding(.vertical, 9)- .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18))- .transition(.opacity.combined(with: .scale(scale: 0.92, anchor: .bottomLeading)))- } else {- Text("Working…")- .appFont(.subheadline)- .foregroundStyle(Palette.tertiary)- .transition(.opacity)- }- }- .opacity(shown ? 1 : 0)- .offset(y: shown ? 0 : 14)- }- .accessibilityElement(children: .combine)- .onChange(of: shown) { _, isShown in- guard isShown else { return }- Task {- try? await Task.sleep(for: .seconds(reduceMotion ? 0 : 1.6))- withAnimation(Motion.reduced(.spring(duration: 0.45, bounce: 0.2), reduceMotion)) { replied = true }- }- }- }-}--/// What stands between this Mac and the chat, with the one action that fixes it.-private extension ChatWindow {- @ViewBuilder var hostState: some View {- switch host.state {- case .notInstalled:- EmptyState(- icon: "desktopcomputer",- title: "Set up this Mac",- message: "Codync runs your coding agents through the host, a small background service on this Mac.",- action: ("Install host", host.install)- )- case .missingBinary:- EmptyState(- icon: "desktopcomputer.trianglebadge.exclamationmark",- title: "The host is missing",- message: "This copy of Codync doesn't include codync-host. Download Codync again from codync.dev or GitHub."- )- case .starting, .running:- EmptyState(icon: "desktopcomputer", title: "Starting the host…", message: "This takes a few seconds.")- case let .failed(message):- EmptyState(- icon: "desktopcomputer.trianglebadge.exclamationmark",- title: "The host isn't running",- message: message,- action: ("Try again", host.restart)- )- }- }-}--/// The request being decided, swapped in place when the next one comes up; keeps the last-/// one on screen while the card animates away.-private struct CurrentApprovalSheet: View {- @Environment(HostController.self) private var host- @State private var last: Approval?-- var body: some View {- if let approval = host.currentApproval ?? last {- ApprovalSheet(approval: approval)- .id(approval.id)- .onAppear { last = approval }- }- }-}--/// A quiet placeholder for an empty screen: icon, title, a line of help and an optional action.-struct EmptyState: View {- let icon: String- let title: String- let message: String- var action: (title: String, run: () -> Void)?-- var body: some View {- VStack(spacing: 10) {- Image(systemName: icon)- .appFont(.system(size: 36, weight: .light))- .foregroundStyle(Palette.tertiary)- .accessibilityHidden(true)- Text(title).appFont(.title3.weight(.semibold)).foregroundStyle(Palette.text)- Text(message)- .appFont(.callout)- .foregroundStyle(Palette.secondary)- .multilineTextAlignment(.center)- .frame(maxWidth: 360)- if let action {- Button(action.title, action: action.run).buttonStyle(.primary).padding(.top, 4)- }- }- .padding(32)- .frame(maxWidth: .infinity, maxHeight: .infinity)- }-}--/// A bot together with the store of the computer it lives on.-@MainActor-private struct BotTarget {- let bot: Bot- let store: BotStore-}--private struct EditTarget: Identifiable {- let request: EditorRequest- let store: BotStore- var id: UUID { request.id }-}--private struct ChatSplitView: View {- @Environment(HostController.self) private var host- @Environment(AccountSession.self) private var account- @Environment(UpdatesManager.self) private var updates- @State private var editing: EditTarget?- @State private var confirmDelete: BotTarget?- @State private var contextBot: BotTarget?- @State private var contextPoint = CGPoint.zero- @State private var newSessionBot: BotTarget?- @State private var composing = false- @State private var newMenu = false- @State private var railNewMenu = false- /// The compose page gathers a group chat ("New group chat") rather than any chat.- @State private var composingGroup = false- /// The computer a new chat goes to.- @State private var composeComputer: ComputerID?- @State private var previousSelection: BotReference?- @State private var hoveredBot: BotReference?- @State private var marketplace: ComputerID?- /// The Settings page open, nil while Settings is closed.- @State private var settings: SettingsPage?- @State private var search = ""- @State private var showAccount = false- @State private var hoveredFooter: String?- @FocusState private var searchFocused: Bool- @FocusState private var profileFocused: Bool- @AppStorage("hiddenComputers") private var hiddenComputers = ""- @AppStorage("sidebarCompact") private var compact = false- @AppStorage("desktopSidebarWidth") private var sidebarWidth = 296.0- @State private var dragStartWidth: Double?- @State private var appUpdates = AppUpdates()- @Environment(\.accessibilityReduceMotion) private var reduceMotion- /// Sheets hang from the window's title bar; sized from it so they never run past its bottom edge.- @State private var windowSize = CGSize(width: 1100, height: 760)-- private var sheetHeight: CGFloat { max(420, windowSize.height - 76) }-- private var accounts: AccountStore { host.accounts }- /// Every computer with a store, in the account's order.- private var stores: [BotStore] { accounts.computers.compactMap { accounts.store(for: $0.id) } }- /// Computers that can take a new chat: shown, online, and on versions that work together.- private var onlineStores: [BotStore] { stores.filter { shownIDs.contains($0.computer.id) && $0.connection == .online && $0.mismatch == nil } }- private var selectedStore: BotStore? { accounts.selection.flatMap { accounts.store(for: $0.computerId) } }- private var composeStore: BotStore? { composeComputer.flatMap { accounts.store(for: $0) } }- private var shownIDs: Set<ComputerID> {- Set(ComputerSelection(all: accounts.computers.map(\.id), hidden: hiddenComputers).shown)- }- private var visibleRoster: [RosterItem] {- let query = search.trimmingCharacters(in: .whitespacesAndNewlines)- return accounts.roster.filter { item in- shownIDs.contains(item.ref.computerId) && (compact || query.isEmpty- || item.bot.name.localizedCaseInsensitiveContains(query)- || (item.bot.lastMessage?.localizedCaseInsensitiveContains(query) ?? false))- }- }-- private func ref(_ bot: Bot, _ store: BotStore) -> BotReference {- BotReference(accountId: accounts.accountId, computerId: store.computer.id, botId: bot.id)- }-- /// Kit views (new chat, bot editor) select a new bot on their own store; that becomes the account's selection.- private var storeSelection: BotReference? {- stores.lazy.compactMap { store in store.selection.map { BotReference(accountId: accounts.accountId, computerId: store.computer.id, botId: $0) } }.first- }-- var body: some View {- HStack(spacing: 0) {- VStack(spacing: 0) {- HStack(spacing: 6) {- Spacer(minLength: 0)- ComputerFilterHeader(accounts: accounts, hidden: $hiddenComputers) { settings = .computers }- IconButton("New", systemImage: "plus") { newMenu.toggle() }- .codyncMenu(isPresented: $newMenu, items: newItems)- .disabled(onlineStores.isEmpty)- }- .padding(.leading, compact ? 0 : 80)- .padding(.trailing, 18)- .frame(height: 44)- .opacity(compact ? 0 : 1)- .allowsHitTesting(!compact)- .accessibilityHidden(compact)- if compact {- ComputerFilterHeader(accounts: accounts, hidden: $hiddenComputers, compact: true) { settings = .computers }- .frame(width: 70)- }- ScrollView {- LazyVStack(spacing: 2) {- if !compact {- ForEach(stores.filter { shownIDs.contains($0.computer.id) }, id: \.computer.id) { store in- if let mismatch = store.mismatch {- UpdateNeededCard(store: store, mismatch: mismatch)- .padding(.bottom, 8)- .transition(.opacity)- }- }- }- ForEach(visibleRoster) { item in- if let store = accounts.store(for: item.ref.computerId) {- row(item.bot, store)- }- }- }- .padding(.horizontal, 12)- .padding(.top, 4)- }- .onMoveCommand { direction in- let refs = visibleRoster.map(\.ref)- guard direction == .up || direction == .down, !refs.isEmpty else { return }- let current = refs.firstIndex { $0 == accounts.selection } ?? -1- let next = direction == .down ? min(current + 1, refs.count - 1) : max(current - 1, 0)- accounts.selection = refs[next]- }- .scrollContentBackground(.hidden)- .background(Palette.surface)- .safeAreaInset(edge: .top, spacing: 0) {- if !compact {- VStack(spacing: 4) {- searchField- }- .frame(width: sidebarWidth)- .transition(.opacity)- }- }- .overlay {- // A computer waiting for an update shows its card instead; its bots aren't known yet.- if visibleRoster.isEmpty && !compact- && !stores.contains(where: { shownIDs.contains($0.computer.id) && $0.mismatch != nil }) {- VStack(spacing: 8) {- Text(search.isEmpty ? "No bots yet" : "No matching bots")- .appFont(.system(size: 13, weight: .medium))- Text(search.isEmpty ? "Use + to start a new chat." : "Try another name or message.")- .appFont(.system(size: 12)).foregroundStyle(Palette.secondary)- }- .allowsHitTesting(false)- }- }- .safeAreaInset(edge: .bottom) {- ZStack(alignment: .bottom) {- if compact {- railActions- .frame(width: 76)- .transition(.opacity)- } else {- sidebarFooter- .frame(width: sidebarWidth)- .transition(.opacity)- }- }- .frame(maxWidth: .infinity)- }- }- .frame(width: compact ? 76 : sidebarWidth)- .frame(maxHeight: .infinity)- .background(Palette.surface)- .clipped()- sidebarDivider- Group {- if composing, let store = composeStore {- VStack(spacing: 0) {- if onlineStores.count > 1 { computerPicker }- // The To: row takes the title bar's place instead of sitting under an empty one.- NewChatView(group: composingGroup) {- composing = false- if accounts.selection == nil { accounts.selection = previousSelection }- }- .environment(store)- .id("\(store.computer.id)-\(composingGroup)")- }- .ignoresSafeArea(.container, edges: .top)-- } else if let ref = accounts.selection, let store = selectedStore, store.bots[ref.botId] != nil {- ThreadView(botId: ref.botId)- .environment(store)- .id(ref)- .transition(.asymmetric(insertion: .opacity, removal: .identity))- } else {- VStack(spacing: 14) {- HStack(spacing: -10) {- CharacterAvatar(shape: "blob", color: "blue", size: 60, mood: .working)- CharacterAvatar(shape: "squircle", color: "orange", size: 60)- CharacterAvatar(shape: "teardrop", color: "violet", size: 60, mood: .working)- }- Text("Your coding agents, as teammates.").appFont(.title2.weight(.semibold))- Text("Pick a bot, or create one for each kind of work and point it at a project.")- .foregroundStyle(Palette.secondary)- .multilineTextAlignment(.center)- .frame(maxWidth: 420)- Button("New Bot") { compose() }- .buttonStyle(.primary)- .disabled(onlineStores.isEmpty)- }- .padding(32)- .frame(maxWidth: .infinity, maxHeight: .infinity)- }- }- .frame(minWidth: 420, maxWidth: .infinity, maxHeight: .infinity)- }- // Animate mode changes from every entry point, while ordinary resizing tracks the pointer.- .animation(Motion.reduced(Motion.layout, reduceMotion), value: compact)- .coordinateSpace(name: "chat-window")- .allowsHitTesting(!showAccount && contextBot == nil)- .accessibilityHidden(showAccount || contextBot != nil)- .overlay(alignment: .bottomLeading) {- if showAccount {- ZStack(alignment: .bottomLeading) {- Color.black.opacity(0.001)- .contentShape(Rectangle())- .onTapGesture { dismissAccountMenu() }- .accessibilityLabel("Dismiss account menu")- .accessibilityAddTraits(.isButton)- SidebarAccountPanel(- name: localProfileName,- signedIn: account.isSignedIn,- email: account.email,- busy: account.isBusy,- errorMessage: account.errorMessage ?? updates.errorMessage,- onSignIn: { provider in dismissAccountMenu(); signIn(provider) },- onSignOut: { dismissAccountMenu(); signOut() },- approvals: host.approvals.count,- onDismiss: dismissAccountMenu,- onUsage: { dismissAccountMenu(); settings = .usage },- onSettings: { dismissAccountMenu(); settings = .general }- )- .frame(width: min(260, windowSize.width - 32))- .padding(.leading, 16)- .padding(.bottom, compact ? 68 : 64)- .transition(.scale(scale: 0.97, anchor: .bottomLeading).combined(with: .opacity))- }- }- }- .overlay(alignment: .topLeading) {- if let bot = contextBot {- ZStack(alignment: .topLeading) {- Color.black.opacity(0.001)- .contentShape(Rectangle())- .onTapGesture { contextBot = nil }- .accessibilityLabel("Dismiss conversation menu")- .accessibilityAddTraits(.isButton)- DesktopActionMenu(items: botActions(bot.bot, bot.store), onDismiss: { contextBot = nil })- .frame(width: 260)- .offset(x: min(max(8, contextPoint.x), windowSize.width - 268),- y: min(max(8, contextPoint.y), max(8, windowSize.height - 344)))- .transition(.opacity)- }- }- }- .animation(Motion.reduced(Motion.fade, reduceMotion), value: showAccount)- .animation(Motion.reduced(Motion.fade, reduceMotion), value: contextBot?.bot.id)- .ignoresSafeArea(.container, edges: .top)- .codyncSheet(item: $editing) { target in- BotEditorView(draft: target.request.draft)- .environment(target.store)- .frame(width: 520, height: min(680, sheetHeight))- }- .codyncSheet(isPresented: Binding(get: { marketplace != nil }, set: { if !$0 { marketplace = nil } })) {- if let store = marketplace.flatMap(accounts.store(for:)) {- MarketplaceView(computers: onlineStores.map { ($0.computer.id, $0.hostName) },- computer: Binding(get: { store.computer.id }, set: { marketplace = $0 }))- .environment(store)- .id(store.computer.id)- .frame(width: min(920, windowSize.width - 80), height: sheetHeight)- }- }- .codyncSheet(isPresented: Binding(get: { settings != nil }, set: { if !$0 { settings = nil } })) {- SettingsView(page: settings ?? .general,- onSignIn: signIn, onSignOut: signOut)- .frame(width: min(800, windowSize.width - 80), height: min(620, sheetHeight))- }- .background {- collapseButton.hidden()- Button("New chat") { compose() }- .keyboardShortcut("n")- .disabled(onlineStores.isEmpty)- .hidden()- Button("Search bots") {- compact = false- searchFocused = true- }- .keyboardShortcut("f")- .hidden()- }- .onGeometryChange(for: CGSize.self) {- $0.size- } action: {- windowSize = $0- sidebarWidth = min(sidebarWidth, max(260, $0.width - 420))- }- .hiddenWindowTitle()- // A computer and this app on versions that don't work together: Sparkle updates the app;- // this Mac's own host is put back on the app's bundled copy.- .environment(\.appUpdate, updates.canCheckForUpdates || updates.hasStagedUpdate- ? AppUpdateAction { [updates] in updates.checkForUpdates() } : nil)- .environment(\.hostUpdate, HostUpdateAction(available: { [host] in $0 === host.store }) { [host] _ in host.restart() })- // No App Store lookup here (Sparkle updates the Mac app); keeps reminder dismissals.- .environment(appUpdates)- .codyncDialog("Start a new session?", isPresented: Binding(- get: { newSessionBot != nil },- set: { if !$0 { newSessionBot = nil } }- ), message: "The conversation stays here, but the agent starts with a fresh context.") {- guard let target = newSessionBot else { return [] }- return [DialogAction("New session") { target.store.newSession(target.bot.id); newSessionBot = nil }]- }- .codyncDialog("Delete \(confirmDelete?.bot.name ?? "bot")?", isPresented: Binding(- get: { confirmDelete != nil },- set: { if !$0 { confirmDelete = nil } }- ), message: "Files it changed on your computer stay as they are.") {- guard let target = confirmDelete else { return [] }- return [DialogAction("Delete bot and its conversation", destructive: true) { target.store.delete(target.bot) }]- }- .codyncDialog("Something went wrong", isPresented: Binding(get: { errorMessage != nil }, set: { if !$0 { clearErrors() } }),- message: errorMessage, cancel: "OK") { [] }- .animation(Motion.reduced(Motion.fade, reduceMotion), value: accounts.selection)- .animation(Motion.reduced(Motion.fade, reduceMotion), value: composing)- .onChange(of: accounts.selection) { _, ref in if ref != nil { composing = false } }- .onChange(of: storeSelection) { _, ref in- guard let ref else { return }- accounts.store(for: ref.computerId)?.selection = nil- accounts.selection = ref- }- #if DEBUG- .onAppear {- // Screenshot/UI checks: CODYNC_DEBUG_OPEN=compose | group | plugins | computers | <bot name>- let target = ProcessInfo.processInfo.environment["CODYNC_DEBUG_OPEN"]- if target == "compose" || target == "group" {- compose(group: target == "group")- } else if target == "plugins" {- marketplace = host.store?.computer.id- } else if target == "computers" {- settings = .computers- } else if let target, let item = accounts.roster.first(where: { $0.bot.name == target }) {- accounts.selection = item.ref- }- }- #endif- }-}--extension ChatSplitView {- fileprivate var sidebarDivider: some View {- Rectangle()- .fill(Palette.border)- .frame(width: 1)- .overlay {- Color.clear.frame(width: 9)- .contentShape(Rectangle())- .gesture(- DragGesture(minimumDistance: 0, coordinateSpace: .named("chat-window"))- .onChanged { value in- if dragStartWidth == nil { dragStartWidth = compact ? 76 : sidebarWidth }- let proposed = (dragStartWidth ?? 296) + value.translation.width- compact = proposed < 180- if !compact {- sidebarWidth = min(max(260, proposed), min(420, windowSize.width - 420))- }- }- .onEnded { _ in dragStartWidth = nil }- )- .onHover { hovering in- if hovering { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() }- }- }- .accessibilityLabel("Resize sidebar")- .accessibilityValue("\(compact ? 76 : Int(sidebarWidth)) points")- .accessibilityAdjustableAction { direction in- switch direction {- case .increment:- if compact { compact = false }- else { sidebarWidth = min(sidebarWidth + 20, min(420, windowSize.width - 420)) }- case .decrement:- if sidebarWidth <= 260 { compact = true }- else { sidebarWidth = max(260, sidebarWidth - 20) }- @unknown default: break- }- }- }-- fileprivate var searchField: some View {- HStack(spacing: 6) {- Image(systemName: "magnifyingglass").foregroundStyle(Palette.secondary)- TextField("Search", text: $search)- .textFieldStyle(.plain)- .focused($searchFocused)- .accessibilityLabel("Search bots")- .onKeyPress(.escape) {- search = ""- searchFocused = false- return .handled- }- if !search.isEmpty {- Button("Clear search", systemImage: "xmark.circle.fill") { search = "" }- .labelStyle(.iconOnly).buttonStyle(.plain)- .foregroundStyle(Palette.secondary)- .transition(.opacity.combined(with: .scale(scale: 0.8)))- }- }- .animation(Motion.reduced(Motion.fade, reduceMotion), value: search.isEmpty)- .appFont(.system(size: 13))- .padding(.horizontal, 9)- .frame(height: 28)- .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 8))- .padding(.horizontal, 12)- .padding(.top, 4)- .padding(.bottom, 8)- .background(Palette.surface)- }-- private var localProfileName: String { "Account" }-- private func row(_ bot: Bot, _ store: BotStore) -> some View {- let ref = ref(bot, store)- return Button {- accounts.selection = ref- } label: {- BotRow(bot: bot, compact: compact)- .environment(store)- .padding(.horizontal, compact ? 0 : 8)- .frame(maxWidth: .infinity, alignment: .leading)- .background(- accounts.selection == ref- ? Palette.bubbleUser : hoveredBot == ref ? Palette.bubbleAgent : Color.clear,- in: RoundedRectangle(cornerRadius: 10)- )- .contentShape(Rectangle())- }- .buttonStyle(.plain)- .accessibilityLabel(stores.count > 1 ? "\(bot.name), on \(store.hostName)" : bot.name)- .accessibilityAddTraits(accounts.selection == ref ? .isSelected : [])- .help(stores.count > 1 ? "\(bot.name) · \(store.hostName)" : bot.name)- .onHover { hoveredBot = $0 ? ref : nil }- .overlay {- GeometryReader { geometry in- SecondaryClickCapture { point in- let frame = geometry.frame(in: .named("chat-window"))- contextPoint = CGPoint(x: frame.minX + point.x, y: frame.minY + point.y)- contextBot = BotTarget(bot: bot, store: store)- }- }- }- .accessibilityAction(named: "Conversation actions") {- contextPoint = CGPoint(x: compact ? 64 : sidebarWidth - 24, y: 100)- contextBot = BotTarget(bot: bot, store: store)- }- }-- /// Which computer a new chat goes to, when more than one is online.- fileprivate var computerPicker: some View {- HStack(spacing: 8) {- Text("On").foregroundStyle(Palette.secondary)- ChoicePicker(selection: Binding(get: { composeComputer ?? "" }, set: { composeComputer = $0 }),- options: onlineStores.map { ($0.computer.id, $0.hostName) })- Spacer()- }- .appFont(.callout)- .padding(.horizontal, 22)- .padding(.top, 12)- }-- private var errorMessage: String? {- accounts.lastError ?? stores.lazy.compactMap(\.lastError).first- }-- private func clearErrors() {- accounts.lastError = nil- for store in stores { store.lastError = nil }- }-- private var profileAvatar: some View {- Group {- if let url = account.avatarURL {- AsyncImage(url: url) { image in image.resizable().scaledToFill() } placeholder: { profilePlaceholder }- } else { profilePlaceholder }- }- .frame(width: 28, height: 28)- .background(Palette.bubbleUser, in: Circle())- .clipShape(Circle())- .overlay { if account.isBusy { Spinner(size: 14) } }- .accessibilityHidden(true)- }-- private var profilePlaceholder: some View {- Image(systemName: "person.fill")- .appFont(.system(size: 15, weight: .medium))- .foregroundStyle(Palette.secondary)- .frame(maxWidth: .infinity, maxHeight: .infinity)- }-- fileprivate var sidebarFooter: some View {- VStack(spacing: 4) {- Button {- marketplace = (selectedStore ?? host.store ?? onlineStores.first)?.computer.id- } label: {- HStack(spacing: 10) {- Image(systemName: "square.grid.2x2")- .appFont(.system(size: 14, weight: .regular))- .frame(width: 30, height: 30)- .background(Palette.text.opacity(0.025), in: Circle())- Text("Marketplace")- Spacer(minLength: 0)- }- .padding(.horizontal, 8)- .frame(height: 36)- .background(hoveredFooter == "marketplace" ? Palette.bubbleAgent : .clear,- in: RoundedRectangle(cornerRadius: 10))- .contentShape(Rectangle())- }- .onHover { hoveredFooter = $0 ? "marketplace" : nil }-- Button {- showAccount.toggle()- } label: {- HStack(spacing: 10) {- profileAvatar- Text(localProfileName)- .lineLimit(1)- .truncationMode(.tail)- Spacer(minLength: 8)-- }- .padding(.horizontal, 8)- .frame(height: 38)- .background(hoveredFooter == "account" || showAccount ? Palette.bubbleAgent : .clear,- in: RoundedRectangle(cornerRadius: 10))- .contentShape(Rectangle())- }- .onHover { hoveredFooter = $0 ? "account" : nil }- .accessibilityLabel("Open account menu for \(localProfileName)")- .help("Account menu")- .focused($profileFocused)- }- .buttonStyle(.plain)- .appFont(.system(size: 13, weight: .medium))- .foregroundStyle(Palette.text)- .padding(.horizontal, 12)- .padding(.top, 6)- .padding(.bottom, 10)- .background(Palette.surface)- }-- /// The "+" menu: a chat with one or more bots, or a group chat. Both use the To: page.- fileprivate func newItems() -> [MenuItem] {- [MenuItem("New chat", icon: "square.and.pencil") { compose() },- MenuItem("New group chat", icon: "person.2") { compose(group: true) }]- }-- fileprivate func compose(group: Bool = false) {- composingGroup = group- // The selected bot's computer if it's online, else this Mac, else any online one.- let target = [selectedStore, host.store].compactMap { $0 }.first { store in onlineStores.contains { $0 === store } } ?? onlineStores.first- guard let target else { return }- if !composing { previousSelection = accounts.selection }- composeComputer = target.computer.id- accounts.selection = nil- composing = true- }-- fileprivate var collapseButton: some View {- Button(compact ? "Expand Sidebar" : "Collapse Sidebar", systemImage: "sidebar.left") {- compact.toggle()- }- .keyboardShortcut("s", modifiers: [.control, .command])- .help(compact ? "Expand sidebar" : "Collapse sidebar")- }-- private func signIn(_ provider: AccountSession.SignInProvider) {- Task {- await account.signIn(provider: provider)- if account.errorMessage != nil && settings == nil {- withAnimation(Motion.fade) { showAccount = true }- }- }- }-- private func signOut() {- Task {- await host.signOut()- if account.errorMessage != nil && settings == nil {- withAnimation(Motion.fade) { showAccount = true }- }- }- }-- private func dismissAccountMenu() {- showAccount = false- profileFocused = true- }-- /// The compact rail keeps the same destinations as the expanded footer.- fileprivate var railActions: some View {- VStack(spacing: 4) {- Button("New", systemImage: "plus") { railNewMenu.toggle() }- .disabled(onlineStores.isEmpty)- .help("New")- .labelStyle(.iconOnly)- .buttonStyle(IconButtonStyle(size: 36))- .codyncMenu(isPresented: $railNewMenu, items: newItems)- Button("Marketplace", systemImage: "square.grid.2x2") {- marketplace = (selectedStore ?? host.store ?? onlineStores.first)?.computer.id- }- .help("Marketplace")- .labelStyle(.iconOnly)- .buttonStyle(IconButtonStyle(size: 36))- Button { showAccount.toggle() } label: {- profileAvatar- .frame(width: 44, height: 44)- .background(showAccount ? Palette.bubbleAgent : .clear, in: RoundedRectangle(cornerRadius: 12))- .contentShape(Rectangle())- }- .buttonStyle(.plain)- .focused($profileFocused)- .accessibilityLabel("Open account menu for \(localProfileName)")- .help(localProfileName)- .padding(.top, 4)- }- .frame(maxWidth: .infinity)- .padding(.top, 8)- .padding(.bottom, 10)- }-- private func botActions(_ bot: Bot, _ model: BotStore) -> [DesktopActionMenu.Item] {- let target = BotTarget(bot: bot, store: model)- return [- .init(title: bot.pinned ? "Unpin" : "Pin", icon: "pin", action: { model.setPinned(bot, !bot.pinned) }),- .init(title: "Mark as Read", icon: "bell.badge", action: { model.markAllRead(bot.id) }),- .init(title: "Edit Profile…", icon: "square.and.pencil", divider: true,- action: { editing = EditTarget(request: EditorRequest(BotDraft(bot)), store: model) }),- .init(title: "Copy conversation ID", icon: "square.on.square", divider: true, action: {- NSPasteboard.general.clearContents()- NSPasteboard.general.setString(bot.id, forType: .string)- }),- .init(title: "New session", icon: "arrow.counterclockwise", action: { newSessionBot = target }),- .init(title: "Hide from sidebar", icon: "eye.slash", divider: true,- action: { model.setHidden(bot, true) }),- .init(title: "Delete", icon: "trash", destructive: true, action: { confirmDelete = target })- ]- }-}--/// Usage per computer, read live from the stores.-extension View {- @ViewBuilder fileprivate func hiddenWindowTitle() -> some View {- if #available(macOS 15.0, *) { toolbar(removing: .title) } else { self }- }-}--/// Window-local floating surface: no NSMenu, NSPopover or system menu styling.-private struct SidebarAccountPanel: View {- let name: String- let signedIn: Bool- let email: String?- let busy: Bool- let errorMessage: String?- let onSignIn: (AccountSession.SignInProvider) -> Void- let onSignOut: () -> Void- let approvals: Int- let onDismiss: () -> Void- let onUsage: () -> Void- let onSettings: () -> Void- @State private var page = "main"- @State private var highlighted = 0- @FocusState private var menuFocused: Bool- @Environment(\.accessibilityReduceMotion) private var reduceMotion-- private struct Item {- let title: String- let icon: String- var assetIcon: String? = nil- var detail: String? = nil- var chevron = false- var disabled = false- let action: () -> Void- }-- private var items: [Item] {- switch page {- case "support":- return [- Item(title: "Support", icon: "chevron.left", action: { navigate("main") }),- Item(title: "Help & documentation", icon: "book", chevron: true,- action: { open("https://github.com/leepokai/codync#readme") }),- Item(title: "Report an issue", icon: "bubble.left", chevron: true,- action: { open("https://github.com/leepokai/codync/issues") })- ]- default:- return [- Item(title: "Usage", icon: "gauge.with.dots.needle.33percent", chevron: true, action: onUsage),- Item(title: "Get Codync for mobile", icon: "iphone", action: { open("https://apps.apple.com/app/id6760984418") }),- Item(title: "Support", icon: "book.closed", chevron: true, action: { navigate("support") }),- Item(title: "Settings", icon: "gearshape", detail: approvals > 0 ? "\(approvals)" : nil, action: onSettings)- ] + authenticationItems- }- }-- private var authenticationItems: [Item] {- if signedIn {- return [Item(title: busy ? "Please wait…" : "Sign out",- icon: "rectangle.portrait.and.arrow.right", disabled: busy, action: onSignOut)]- }- return [- Item(title: "Continue with Apple", icon: "apple.logo", disabled: busy,- action: { onSignIn(.apple) }),- Item(title: "Continue with Google", icon: "person.crop.circle.badge.plus", assetIcon: "google", disabled: busy,- action: { onSignIn(.google) })- ]- }-- var body: some View {- menuContent- .padding(7)- .background(Color(light: 0xFAFAFA, dark: 0x1B1B1B), in: RoundedRectangle(cornerRadius: 18))- .shadow(color: .black.opacity(0.25), radius: 20, x: 0, y: 8)- .accessibilityElement(children: .contain)- .accessibilityLabel("Account menu")- .focusable()- .focused($menuFocused)- .focusEffectDisabled()- .onKeyPress(.escape) { onDismiss(); return .handled }- .onKeyPress(.downArrow) { moveFocus(1); return .handled }- .onKeyPress(.upArrow) { moveFocus(-1); return .handled }- .onKeyPress(.tab, phases: .down) { press in moveFocus(press.modifiers.contains(.shift) ? -1 : 1); return .handled }- .onKeyPress(.return) { activate(); return .handled }- .onKeyPress(.space) { activate(); return .handled }- .task { await Task.yield(); menuFocused = true }- }-- private var menuContent: some View {- VStack(spacing: 2) {- ForEach(items.indices, id: \.self) { index in- menuRow(items[index], index: index)- }- if let errorMessage, page == "main" {- Text(errorMessage).appFont(.system(size: 12)).foregroundStyle(Palette.warning)- .fixedSize(horizontal: false, vertical: true)- .padding(.horizontal, 10).padding(.vertical, 8)- }- }- }-- @ViewBuilder private func menuRow(_ item: Item, index: Int) -> some View {- if index == (page == "main" ? 4 : 1) { divider }- if page == "main" && index == 4 { accountIdentity }- AccountPanelRow(title: item.title, icon: item.icon, assetIcon: item.assetIcon, detail: item.detail,- chevron: item.chevron, keyboardFocused: highlighted == index, action: item.action)- .disabled(item.disabled)- .onHover { if $0 { highlighted = index } }- }-- private var accountIdentity: some View {- HStack(spacing: 8) {- Image(systemName: "person.crop.circle").appFont(.system(size: 15))- Text(email ?? name).appFont(.system(size: 12)).lineLimit(1)- Spacer()- if !signedIn { Text("Not signed in").appFont(.system(size: 11)) }- }- .foregroundStyle(Palette.secondary)- .padding(.horizontal, 10)- .frame(height: 30)- }-- private var divider: some View {- Rectangle().fill(Palette.text.opacity(0.13)).frame(height: 0.5)- .padding(.horizontal, 10).padding(.vertical, 5)- }-- private func navigate(_ destination: String) {- withAnimation(Motion.reduced(Motion.layout, reduceMotion)) {- page = destination- highlighted = 0- }- menuFocused = true- }-- private func moveFocus(_ delta: Int) {- highlighted = (highlighted + delta + items.count) % items.count- }-- private func activate() {- guard items.indices.contains(highlighted), !items[highlighted].disabled else { return }- items[highlighted].action()- }-- private func open(_ string: String) {- guard let url = URL(string: string) else { return }- onDismiss()- NSWorkspace.shared.open(url)- }-}--private struct AccountPanelRow: View {- let title: String- let icon: String- var assetIcon: String? = nil- let detail: String?- let chevron: Bool- let keyboardFocused: Bool- var destructive = false- let action: () -> Void- @State private var hovered = false-- var body: some View {- Button(action: action) {- HStack(spacing: 8) {- if let assetIcon {- Image(assetIcon).resizable().scaledToFit().frame(width: 16, height: 16).frame(width: 20)- } else {- Image(systemName: icon).appFont(.system(size: 14, weight: .regular)).frame(width: 20)- }- Text(title).appFont(.system(size: 12)).lineLimit(1)- Spacer(minLength: 8)- if let detail { Text(detail).appFont(.system(size: 13)).foregroundStyle(Palette.secondary) }- if chevron { Image(systemName: "chevron.right").appFont(.system(size: 11)).foregroundStyle(Palette.secondary) }- }- .foregroundStyle(destructive ? Palette.danger : Palette.text)- .padding(.horizontal, 10)- .frame(height: 30)- .background(hovered || keyboardFocused ? Palette.text.opacity(0.08) : .clear,- in: RoundedRectangle(cornerRadius: 10))- .contentShape(Rectangle())- }- .buttonStyle(.plain)- .focusEffectDisabled()- .onHover { hovered = $0 }- }-}--/// A SwiftUI action surface shared by pointer and accessibility entry points.-private struct DesktopActionMenu: View {- struct Item {- let title: String- let icon: String- var divider = false- var destructive = false- let action: () -> Void- }-- let items: [Item]- let onDismiss: () -> Void- @State private var highlighted = 0- @FocusState private var focused: Bool-- var body: some View {- VStack(spacing: 2) {- ForEach(items.indices, id: \.self) { index in- let item = items[index]- if item.divider {- Rectangle().fill(Palette.text.opacity(0.13)).frame(height: 0.5)- .padding(.horizontal, 10).padding(.vertical, 5)- }- AccountPanelRow(title: item.title, icon: item.icon, detail: nil,- chevron: false, keyboardFocused: highlighted == index,- destructive: item.destructive) { activate(index) }- .onHover { if $0 { highlighted = index } }- }- }- .padding(7)- .background(Color(light: 0xFAFAFA, dark: 0x1B1B1B), in: RoundedRectangle(cornerRadius: 14))- .shadow(color: .black.opacity(0.25), radius: 20, x: 0, y: 8)- .accessibilityElement(children: .contain)- .accessibilityLabel("Conversation actions")- .focusable()- .focused($focused)- .focusEffectDisabled()- .onKeyPress(.escape) { onDismiss(); return .handled }- .onKeyPress(.downArrow) { move(1); return .handled }- .onKeyPress(.upArrow) { move(-1); return .handled }- .onKeyPress(.tab, phases: .down) { press in move(press.modifiers.contains(.shift) ? -1 : 1); return .handled }- .onKeyPress(.return) { activate(highlighted); return .handled }- .onKeyPress(.space) { activate(highlighted); return .handled }- .task { await Task.yield(); focused = true }- }-- private func move(_ delta: Int) { highlighted = (highlighted + delta + items.count) % items.count }-- private func activate(_ index: Int) {- guard items.indices.contains(index) else { return }- onDismiss()- items[index].action()- }-}diff --git a/apps/macos/Views/ComputersView.swift b/apps/macos/Views/ComputersView.swiftdeleted file mode 100644index 91a08279..00000000--- a/apps/macos/Views/ComputersView.swift+++ /dev/null@@ -1,680 +0,0 @@-import AppKit-import CodyncKit-import CodyncUI-import SwiftUI-import UniformTypeIdentifiers--/// How this Mac reaches a computer: itself, an SSH tunnel, direct LAN or the encrypted relay.-struct RouteLabel: View {- let store: BotStore- let ssh: Bool-- var body: some View {- if ssh {- Image(systemName: "terminal").help("Over SSH").accessibilityLabel("Over SSH")- } else if store.connection == .online {- RouteIcon(route: store.hostRoute).help(store.hostRoute == .relay ? "Through Cloudflare (encrypted)" : "Direct: Wi-Fi or Tailscale")- }- }-}--// MARK: - Approval--/// A device asks for access through the account (spec §4.2 B). The code is the only thing-/// that tells a real request from a cloud swapping keys, so it's big and Approve is never the default.-struct ApprovalSheet: View {- let approval: Approval- @Environment(HostController.self) private var host- @State private var busy = false- @State private var error: String?- @Environment(\.accessibilityReduceMotion) private var reduceMotion-- private var request: AccessRequest { approval.request }-- var body: some View {- VStack(spacing: 0) {- // Closing puts the request off (the sheet's binding defers it).- ModalHeader("Access request")- content- }- .frame(width: 420)- .animation(Motion.reduced(Motion.layout, reduceMotion), value: request.code)- .animation(Motion.reduced(Motion.layout, reduceMotion), value: error)- }-- private var content: some View {- VStack(spacing: 16) {- Image(systemName: request.platform == "macos" ? "laptopcomputer" : "iphone")- .appFont(.system(size: 40, weight: .light))- .foregroundStyle(Palette.secondary)- .accessibilityHidden(true)- VStack(spacing: 4) {- Text("\(request.deviceName) wants to use \(approval.store.hostName)")- .appFont(.title3.weight(.semibold))- .multilineTextAlignment(.center)- if let email = request.email {- Text("Signed in as \(email)").appFont(.callout).foregroundStyle(Palette.secondary)- }- }- if let code = request.code {- Text(Self.spaced(code))- .appFont(.system(size: 48, weight: .semibold, design: .monospaced))- .foregroundStyle(Palette.text)- .textSelection(.enabled)- .accessibilityLabel("Code \(code.map(String.init).joined(separator: " "))")- Text("Approve only if \(request.deviceName) shows exactly this code. If it doesn't, deny: someone may be trying to get in.")- .appFont(.callout)- .foregroundStyle(Palette.secondary)- .multilineTextAlignment(.center)- .fixedSize(horizontal: false, vertical: true)- } else {- Spinner()- Text("Waiting for \(request.deviceName) to show its code…")- .appFont(.callout)- .foregroundStyle(Palette.secondary)- }- if let error {- Text(error).appFont(.caption).foregroundStyle(Palette.danger).multilineTextAlignment(.center)- .transition(.opacity.combined(with: .move(edge: .top)))- }- HStack(spacing: 12) {- Button("Deny") { decide(false) }- .buttonStyle(.secondary)- .disabled(busy)- Button("Approve") { decide(true) }- .buttonStyle(.primary)- .disabled(busy || request.code == nil)- }- }- .padding([.horizontal, .bottom], 24)- }-- private func decide(_ approve: Bool) {- busy = true- Task {- defer { busy = false }- do {- try await host.decide(approval, approve: approve)- // The host's accessRequests event removes it; don't wait for that to close.- host.deferApproval(approval)- } catch {- self.error = error.localizedDescription- }- }- }-- private static func spaced(_ code: String) -> String {- code.count == 6 ? "\(code.prefix(3)) \(code.suffix(3))" : code- }-}--// MARK: - Computers & devices--/// Computers this Mac manages (itself and SSH), with their account, relay and authorized devices;-/// SSH profiles; and the account's other computers.-struct ComputersView: View {- /// False inside the Settings window, which titles the page itself.- var showsHeader = true- @Environment(HostController.self) private var host- @Environment(AccountSession.self) private var account- @State private var editingSSH: SSHProfile?- @Environment(\.accessibilityReduceMotion) private var reduceMotion-- var body: some View {- VStack(spacing: 0) {- if showsHeader { ModalHeader("Computers & devices") }- ScrollView {- VStack(alignment: .leading, spacing: 26) {- ForEach(host.managedStores, id: \.computer.id) { store in- ManagedComputerCard(store: store, ssh: host.isSSH(store.computer.id))- }- sshSection- accountSection- }- .padding(.horizontal, showsHeader ? 20 : 14)- .padding(.top, showsHeader ? 4 : 14)- .padding(.bottom, 20)- }- }- .background(Palette.background)- .animation(Motion.reduced(Motion.layout, reduceMotion), value: host.ssh.profiles.map(\.id))- .animation(Motion.reduced(Motion.layout, reduceMotion), value: host.accounts.computers.map(\.id))- .animation(Motion.reduced(Motion.layout, reduceMotion), value: host.accounts.cloudComputers.map(\.id))- .animation(Motion.reduced(Motion.layout, reduceMotion), value: account.isSignedIn)- .codyncSheet(item: $editingSSH) { profile in- SSHProfileEditor(profile: profile, isNew: !host.ssh.profiles.contains { $0.id == profile.id })- }- }-- private var sshSection: some View {- VStack(alignment: .leading, spacing: 0) {- HStack {- SectionTitle("Over SSH")- Spacer()- IconButton("Add SSH computer", systemImage: "plus") {- editingSSH = SSHProfile(host: "", name: "")- }- }- .sectionHeader()- if host.ssh.profiles.isEmpty {- Text("Run bots on another computer you reach with SSH. It needs codync-host installed; your SSH keys stay on this Mac.")- .appFont(.callout)- .foregroundStyle(Palette.secondary)- .fixedSize(horizontal: false, vertical: true)- }- ForEach(host.ssh.profiles) { profile in- SSHRow(profile: profile) { editingSSH = profile }- }- }- }-- @ViewBuilder private var accountSection: some View {- let managed = Set(host.managedStores.map(\.computer.id))- let reached = host.accounts.computers.filter { !managed.contains($0.id) }- let others = host.accounts.cloudComputers.filter { c in !managed.contains(c.id) && !reached.contains { $0.id == c.id } }- VStack(alignment: .leading, spacing: 0) {- HStack {- SectionTitle("In your account")- Spacer()- if account.isSignedIn {- IconButton("Refresh", systemImage: "arrow.clockwise") { Task { await host.accounts.refreshCloud() } }- }- }- .sectionHeader()- Group {- if !account.isSignedIn {- Text("Sign in to reach the other computers in your account from this Mac.")- } else if reached.isEmpty && others.isEmpty {- Text("No other computers in your account yet.")- }- }- .appFont(.callout)- .foregroundStyle(Palette.secondary)- ForEach(reached) { computer in- if let store = host.accounts.store(for: computer.id) {- HStack(spacing: 10) {- ComputerBadge(store.computer, size: 22)- VStack(alignment: .leading, spacing: 1) {- Text(store.hostName).appFont(.callout.weight(.medium))- Text(host.accounts.statusText(store)).appFont(.caption)- .foregroundStyle(host.accounts.isStale(computer.id) ? Palette.warning : Palette.secondary)- }- RouteLabel(store: store, ssh: false).foregroundStyle(Palette.tertiary)- Spacer()- IconButton("Remove from this Mac", systemImage: "minus.circle") { host.accounts.forget(computer.id) }- }- .card()- }- }- ForEach(others) { computer in- AccountComputerRow(computer: computer)- }- }- }-}--private struct SectionTitle: View {- let title: String- init(_ title: String) { self.title = title }- var body: some View {- Text(title).appFont(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.text).accessibilityAddTraits(.isHeader)- }-}--/// An account computer this Mac isn't authorized on: ask, then compare the code shown there.-private struct AccountComputerRow: View {- let computer: CloudComputer- @Environment(HostController.self) private var host- @State private var busy = false- @Environment(\.accessibilityReduceMotion) private var reduceMotion-- var body: some View {- let ticket = host.accounts.pendingAccess[computer.id]- VStack(alignment: .leading, spacing: 8) {- HStack(spacing: 10) {- ComputerBadge(Computer(id: computer.id, name: computer.name, signKey: computer.signKey, device: computer.device), size: 22)- VStack(alignment: .leading, spacing: 1) {- Text(computer.name).appFont(.callout.weight(.medium))- Text(computer.isOnline ? "Online" : "Offline").appFont(.caption).foregroundStyle(Palette.secondary)- }- Spacer()- if ticket == nil {- Button(busy ? "Asking…" : "Ask for access") {- busy = true- Task {- defer { busy = false }- do { _ = try await host.accounts.requestAccess(computer.id) } catch {- host.accounts.lastError = error.localizedDescription- }- }- }- .buttonStyle(.secondary)- .disabled(busy)- .transition(.opacity)- }- }- if let ticket {- HStack(spacing: 12) {- Text(ticket.code.count == 6 ? "\(ticket.code.prefix(3)) \(ticket.code.suffix(3))" : ticket.code)- .appFont(.system(size: 26, weight: .semibold, design: .monospaced))- .accessibilityLabel("Code \(ticket.code.map(String.init).joined(separator: " "))")- Text("Approve on \(computer.name) only if it shows this code.")- .appFont(.callout).foregroundStyle(Palette.secondary)- .fixedSize(horizontal: false, vertical: true)- Spacer()- IconButton("Cancel request", systemImage: "xmark.circle") {- Task { await host.accounts.cancelAccess(computer.id) }- }- }- .transition(.opacity.combined(with: .move(edge: .top)))- }- }- .card()- .animation(Motion.reduced(Motion.layout, reduceMotion), value: ticket?.code)- }-}--/// This Mac or an SSH computer: relay, account membership, pairing and authorized devices.-private struct ManagedComputerCard: View {- let store: BotStore- let ssh: Bool- @Environment(HostController.self) private var host- @Environment(AccountSession.self) private var account- @State private var devices: [AuthorizedDevice]?- @State private var busy = false- @State private var showPairing = false- @State private var showVoice = false- @State private var confirmRevoke: AuthorizedDevice?- @State private var confirmUnclaim = false- @State private var confirmAutoApproval = false- @Environment(\.accessibilityReduceMotion) private var reduceMotion-- private var cloud: CloudStatus? { store.cloud }- private var autoApproval: Bool { cloud?.approval == .auto }-- var body: some View {- VStack(alignment: .leading, spacing: 28) {- CardSection {- HStack(spacing: 10) {- ComputerBadge(store.computer, size: 26)- VStack(alignment: .leading, spacing: 1) {- Text(store.hostName).appFont(.headline)- Text(ssh ? "Over SSH · \(store.statusText)" : "This Mac · \(store.statusText)")- .appFont(.caption).foregroundStyle(Palette.secondary)- }- Spacer()- if ssh {- // This Mac's voice settings are their own Settings page.- IconButton("Voice chat", systemImage: "waveform", selected: showVoice) { showVoice.toggle() }- .disabled(store.connection != .online)- .codyncSheet(isPresented: $showVoice) { VoiceChatSettingsView().environment(store) }- }- IconButton("Pair iPhone", systemImage: "qrcode", selected: showPairing) { showPairing.toggle() }- .disabled(store.connection != .online)- .codyncSheet(isPresented: $showPairing) {- VStack(spacing: 0) {- ModalHeader("Pair iPhone with \(store.hostName)")- PairingPanel(store: store)- }- .frame(width: 340)- }- }-- Toggle(isOn: Binding(get: { cloud?.enabled ?? false }, set: { on in run { await host.setCloud(store, enabled: on) } })) {- VStack(alignment: .leading, spacing: 1) {- Text("Reach from anywhere")- Text(cloudLine).appFont(.caption).foregroundStyle(cloud?.lastError == nil ? Palette.secondary : Palette.warning)- }- }- .toggleStyle(.codync)- .disabled(busy || store.connection != .online)-- accountLine-- if cloud?.owner != nil {- Toggle(isOn: Binding(get: { autoApproval }, set: { on in- if on { confirmAutoApproval = true } else { setApproval(.code) }- })) {- VStack(alignment: .leading, spacing: 1) {- Text("Skip the 6-digit check")- Text(autoApproval ? "Devices on your account get in on their own." : "Each new device shows a code you approve here.")- .appFont(.caption).foregroundStyle(autoApproval ? Palette.warning : Palette.secondary)- }- }- .toggleStyle(.codync)- .disabled(busy || store.connection != .online)- .transition(.opacity)- }- }- CardSection("Devices that can use \(store.hostName)") {- if let devices {- if devices.isEmpty {- Text("None yet. Pair an iPhone, or approve one from your account.").foregroundStyle(Palette.secondary)- }- ForEach(devices) { device in deviceRow(device).transition(.opacity.combined(with: .move(edge: .top))) }- } else {- Spinner()- }- }- }- .animation(Motion.reduced(Motion.layout, reduceMotion), value: devices?.map(\.key))- .animation(Motion.reduced(Motion.layout, reduceMotion), value: cloud?.owner == nil)- .task(id: "\(store.computer.id)/\(store.connection == .online)/\(store.accessRequests.count)") { await loadDevices() }- .codyncDialog("Revoke \(confirmRevoke?.name ?? "device")?", isPresented: Binding(- get: { confirmRevoke != nil }, set: { if !$0 { confirmRevoke = nil } }- ), message: "It disconnects right away and has to pair or ask again.") {- guard let device = confirmRevoke else { return [] }- return [DialogAction("Revoke access", destructive: true) {- run {- do { try await store.client?.revokeDevice(device.key) } catch { host.accounts.lastError = error.localizedDescription }- await loadDevices()- }- }]- }- .codyncDialog("Let account devices in without a code?", isPresented: $confirmAutoApproval,- message: "Any device signed in to your account gets full control of \(store.hostName): its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.") {- [DialogAction("Skip the check", destructive: true) { setApproval(.auto) }]- }- .codyncDialog("Remove \(store.hostName) from the account?", isPresented: $confirmUnclaim,- message: "Devices that were approved through the account lose access. Devices paired with a QR code keep it.") {- [DialogAction("Remove from account", destructive: true) { run { await host.unclaim(store) } }]- }- }-- private var cloudLine: String {- guard let cloud, cloud.enabled else { return "Off: only Wi-Fi and Tailscale reach it, nothing goes through Cloudflare." }- if let error = cloud.lastError { return error }- return cloud.connected == true ? "Reachable from anywhere through Cloudflare (encrypted)." : "Connecting to Cloudflare…"- }-- private func setApproval(_ approval: AccountApproval) {- run {- do { _ = try await store.client?.setApproval(approval) } catch { host.accounts.lastError = error.localizedDescription }- }- }-- @ViewBuilder private var accountLine: some View {- HStack(spacing: 8) {- if let owner = cloud?.owner {- Image(systemName: "person.crop.circle.badge.checkmark").foregroundStyle(Palette.secondary).accessibilityHidden(true)- Text(owner.userId == account.userID ? "In your account" : "In \(owner.email ?? "another") account")- .appFont(.callout)- Spacer()- Button("Remove from account") { confirmUnclaim = true }- .buttonStyle(.secondary)- .disabled(busy || store.connection != .online)- } else {- Image(systemName: "person.crop.circle.badge.plus").foregroundStyle(Palette.secondary).accessibilityHidden(true)- Text(account.isSignedIn ? "Not in your account" : "Sign in to add it to your account").appFont(.callout)- Spacer()- if account.isSignedIn {- Button(busy ? "Adding…" : "Add to account") { run { await host.claim(store) } }- .buttonStyle(.secondary)- .disabled(busy || store.connection != .online)- }- }- }- }-- private func deviceRow(_ device: AuthorizedDevice) -> some View {- HStack(spacing: 8) {- Image(systemName: device.platform == "macos" ? "laptopcomputer" : "iphone")- .frame(width: 18)- .foregroundStyle(Palette.secondary)- .accessibilityHidden(true)- VStack(alignment: .leading, spacing: 1) {- Text(device.name)- Text(detail(device)).appFont(.caption).foregroundStyle(Palette.tertiary)- }- Spacer()- IconButton("Revoke access", systemImage: "xmark.circle") { confirmRevoke = device }- }- .accessibilityElement(children: .combine)- }-- private func detail(_ device: AuthorizedDevice) -> String {- var parts = [device.source == "account" ? "Approved through the account" : "Paired with a QR code"]- if device.connected == true {- parts.append("connected")- } else if let seen = device.lastSeenAt {- parts.append("seen \(RelativeTime.day(Date(milliseconds: seen)))")- }- return parts.joined(separator: " · ")- }-- private func loadDevices() async {- guard let client = store.client, store.connection == .online else { return }- devices = (try? await client.devices()) ?? devices- }-- private func run(_ work: @escaping @MainActor () async -> Void) {- busy = true- Task {- await work()- busy = false- }- }-}--// MARK: - SSH--private struct SSHRow: View {- let profile: SSHProfile- let edit: () -> Void- @Environment(HostController.self) private var host- @Environment(\.accessibilityReduceMotion) private var reduceMotion-- var body: some View {- let status = host.ssh.status(of: profile.id)- VStack(alignment: .leading, spacing: 8) {- HStack(spacing: 10) {- Image(systemName: "terminal").frame(width: 22).foregroundStyle(Palette.secondary).accessibilityHidden(true)- VStack(alignment: .leading, spacing: 1) {- Text(profile.name.isEmpty ? profile.host : profile.name).appFont(.callout.weight(.medium))- Text(line(status)).appFont(.caption).foregroundStyle(isProblem(status) ? Palette.warning : Palette.secondary)- .fixedSize(horizontal: false, vertical: true)- }- Spacer()- switch status {- case .connected, .connecting, .retrying:- IconButton("Disconnect", systemImage: "stop.circle") { host.ssh.disconnect(profile.id) }- default:- IconButton("Connect", systemImage: "arrow.clockwise") { host.ssh.connect(profile.id) }- }- IconButton("Edit", systemImage: "pencil", action: edit)- IconButton("Remove", systemImage: "trash") { host.ssh.remove(profile.id) }- }- if case let .confirmHostKey(name, fingerprints, _) = status {- VStack(alignment: .leading, spacing: 6) {- Text("First connection to \(name). Check that its host key fingerprint matches what the computer's owner sees (`ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub`).")- .appFont(.caption).foregroundStyle(Palette.secondary)- .fixedSize(horizontal: false, vertical: true)- ForEach(fingerprints, id: \.self) { Text($0).appFont(.caption.monospaced()).textSelection(.enabled) }- HStack {- Button("Trust and connect") { host.ssh.trustHostKey(profile.id) }.buttonStyle(.primary)- Button("Cancel") { host.ssh.disconnect(profile.id) }.buttonStyle(.secondary)- }- }- .transition(.opacity.combined(with: .move(edge: .top)))- }- if status == .notInstalled {- HStack(spacing: 6) {- Text(SSH.installCommand)- .appFont(.caption.monospaced())- .textSelection(.enabled)- .padding(6)- .frame(maxWidth: .infinity, alignment: .leading)- .background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 6))- IconButton("Copy install command", systemImage: "doc.on.doc") {- NSPasteboard.general.clearContents()- NSPasteboard.general.setString(SSH.installCommand, forType: .string)- }- }- .transition(.opacity.combined(with: .move(edge: .top)))- }- }- .card()- .animation(Motion.reduced(Motion.layout, reduceMotion), value: status)- }-- private func line(_ status: SSHComputers.Status) -> String {- let target = [profile.user.map { "\($0)@" } ?? "", profile.host, profile.port.map { ":\($0)" } ?? ""].joined()- switch status {- case .idle: return "\(target) · Not connected"- case let .connecting(step): return step- case .confirmHostKey: return "\(target) · Confirm the host key"- case .connected: return "\(target) · Connected"- case let .retrying(message): return "\(message) Retrying…"- case let .failed(message): return message- case .notInstalled: return "codync-host isn't installed on \(profile.host). Install it there:"- }- }-- private func isProblem(_ status: SSHComputers.Status) -> Bool {- switch status {- case .retrying, .failed, .notInstalled: true- default: false- }- }-}--/// Add or change an SSH computer. Only fields ssh takes as separate arguments; nothing goes through a shell.-private struct SSHProfileEditor: View {- @State var profile: SSHProfile- let isNew: Bool- @Environment(HostController.self) private var host- @Environment(\.dismissModal) private var dismiss- @Environment(\.accessibilityReduceMotion) private var reduceMotion- @State private var port = ""- @State private var remotePort = ""- @State private var user = ""- @State private var chooseKey = false- @State private var problem: String?-- init(profile: SSHProfile, isNew: Bool) {- _profile = State(initialValue: profile)- self.isNew = isNew- _port = State(initialValue: profile.port.map(String.init) ?? "")- _remotePort = State(initialValue: String(profile.remotePort))- _user = State(initialValue: profile.user ?? "")- }-- var body: some View {- VStack(spacing: 0) {- ModalHeader(isNew ? "Add SSH computer" : "Edit SSH computer") {- IconButton(isNew ? "Add" : "Save", systemImage: "checkmark", action: save)- .keyboardShortcut(.defaultAction)- }- form- }- .frame(width: 460)- .animation(Motion.reduced(Motion.layout, reduceMotion), value: problem)- .animation(Motion.reduced(Motion.layout, reduceMotion), value: profile.identityFile)- .fileImporter(isPresented: $chooseKey, allowedContentTypes: [.item]) { result in- if case let .success(url) = result { profile.identityFile = url.path }- }- }-- private var form: some View {- VStack(alignment: .leading, spacing: 16) {- CardSection {- SSHField("Name", text: $profile.name, prompt: "Optional")- SSHField("Host", text: $profile.host, prompt: "SSH alias or hostname")- SSHField("User", text: $user, prompt: "From SSH config")- SSHField("SSH port", text: $port, prompt: "From SSH config")- HStack {- Text("Key")- Spacer()- Text(profile.identityFile.map { URL(filePath: $0).lastPathComponent } ?? "ssh-agent / SSH config")- .foregroundStyle(Palette.secondary)- IconButton("Choose key file", systemImage: "key") { chooseKey = true }- if profile.identityFile != nil {- IconButton("Use ssh-agent", systemImage: "xmark.circle") { profile.identityFile = nil }- .transition(.opacity.combined(with: .scale(scale: 0.8)))- }- }- SSHField("Codync port", text: $remotePort, prompt: "")- }- Text("Codync opens an SSH tunnel to codync-host on that computer's loopback. It uses your SSH config and ssh-agent; agent forwarding stays off.")- .appFont(.caption).foregroundStyle(Palette.secondary)- .fixedSize(horizontal: false, vertical: true)- if let problem {- Text(problem).appFont(.caption).foregroundStyle(Palette.danger)- .transition(.opacity.combined(with: .move(edge: .top)))- }- }- .padding([.horizontal, .bottom], 20)- .padding(.top, 4)- }-- private func save() {- var p = profile- p.host = p.host.trimmingCharacters(in: .whitespaces)- p.name = p.name.trimmingCharacters(in: .whitespaces)- let u = user.trimmingCharacters(in: .whitespaces)- p.user = u.isEmpty ? nil : u- let portText = port.trimmingCharacters(in: .whitespaces)- if portText.isEmpty {- p.port = nil- } else if let n = Int(portText) {- p.port = n- } else {- problem = "The SSH port must be a number."- return- }- guard let remote = Int(remotePort.trimmingCharacters(in: .whitespaces)) else {- problem = "The Codync port must be a number."- return- }- p.remotePort = remote- if !isNew, let old = host.ssh.profiles.first(where: { $0.id == p.id }), old.host != p.host || old.port != p.port {- // A different address may be a different computer: learn its identity again.- p.computerId = nil- }- if let problem = SSH.validate(p) {- self.problem = problem- return- }- if isNew { host.ssh.add(p) } else { host.ssh.update(p) }- dismiss()- }-}--private extension View {- /// A section's title row (the CardSection heading).- func sectionHeader() -> some View {- frame(minHeight: 24).padding(.leading, 2).padding(.bottom, 10)- }-- /// One filled group, like a CardSection's.- func card() -> some View {- padding(16)- .frame(maxWidth: .infinity, alignment: .leading)- .background(Palette.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))- .padding(.bottom, 8)- }-}--/// A labelled text field row in the SSH card.-private struct SSHField: View {- let label: String- @Binding var text: String- let prompt: String-- init(_ label: String, text: Binding<String>, prompt: String) {- self.label = label- _text = text- self.prompt = prompt- }-- var body: some View {- HStack {- Text(label).foregroundStyle(Palette.text)- Spacer(minLength: 12)- TextField(label, text: $text, prompt: Text(prompt))- .textFieldStyle(.plain)- .multilineTextAlignment(.trailing)- .labelsHidden()- }- }-}diff --git a/apps/macos/Views/SettingsView.swift b/apps/macos/Views/SettingsView.swiftdeleted file mode 100644index 296a6606..00000000--- a/apps/macos/Views/SettingsView.swift+++ /dev/null@@ -1,265 +0,0 @@-import CodyncKit-import CodyncUI-import SwiftUI--/// The chat window's Settings: pages in a sidebar, ChatGPT's settings layout-/// (`docs/design/reference/chatgpt-settings-*.png`).-enum SettingsPage: String, CaseIterable, Identifiable {- case general, computers, voice, usage, updates-- var id: Self { self }-- var title: String {- switch self {- case .general: "General"- case .computers: "Computers & devices"- case .voice: "Voice chat"- case .usage: "Usage"- case .updates: "Updates"- }- }-- /// The sidebar's label, short enough for its width.- var label: String { self == .computers ? "Computers" : title }-- /// The sidebar group it's listed under.- var group: String {- switch self {- case .general, .voice, .usage: "Personal"- case .computers, .updates: "This Mac"- }- }-- var icon: String {- switch self {- case .general: "gearshape"- case .computers: "desktopcomputer"- case .voice: "waveform"- case .usage: "gauge.with.dots.needle.33percent"- case .updates: "arrow.down.circle"- }- }-}--struct SettingsView: View {- /// Kept here: the sheet's content doesn't follow the window's state once shown.- @State private var page: SettingsPage- let onSignIn: (AccountSession.SignInProvider) -> Void- let onSignOut: () -> Void-- init(page: SettingsPage,- onSignIn: @escaping (AccountSession.SignInProvider) -> Void, onSignOut: @escaping () -> Void) {- _page = State(initialValue: page)- self.onSignIn = onSignIn- self.onSignOut = onSignOut- }- @Environment(HostController.self) private var host- @Environment(\.dismissModal) private var dismiss- @Environment(\.accessibilityReduceMotion) private var reduceMotion-- var body: some View {- HStack(spacing: 0) {- sidebar- Rectangle().fill(Palette.border).frame(width: 1)- VStack(alignment: .leading, spacing: 0) {- Text(page.title)- .appFont(.system(size: 24, weight: .semibold))- .foregroundStyle(Palette.text)- .padding(.horizontal, 32)- .padding(.top, 30)- .padding(.bottom, 8)- content- .padding(.horizontal, 18)- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)- .id(page)- .transition(.opacity)- }- }- .overlay(alignment: .topTrailing) {- IconButton("Close", systemImage: "xmark") { dismiss() }- .keyboardShortcut(.cancelAction)- .padding(14)- }- .background(Palette.background)- .animation(Motion.reduced(Motion.fade, reduceMotion), value: page)- }-- private var sidebar: some View {- VStack(alignment: .leading, spacing: 2) {- ForEach(["Personal", "This Mac"], id: \.self) { group in- Text(group)- .appFont(.system(size: 12, weight: .medium))- .foregroundStyle(Palette.tertiary)- .padding(.horizontal, 10)- .padding(.top, group == "Personal" ? 0 : 16)- .padding(.bottom, 4)- ForEach(SettingsPage.allCases.filter { $0.group == group }) { item in- sidebarItem(item)- }- }- Spacer()- }- .padding(10)- .padding(.top, 20)- .frame(width: 200)- }-- private func sidebarItem(_ item: SettingsPage) -> some View {- Button { page = item } label: {- HStack(spacing: 10) {- Image(systemName: item.icon).frame(width: 18).foregroundStyle(Palette.secondary)- Text(item.label).lineLimit(1)- Spacer(minLength: 4)- if item == .computers && !host.approvals.isEmpty {- Text("\(host.approvals.count)").appFont(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.secondary)- }- }- .appFont(.system(size: 13))- .foregroundStyle(Palette.text)- .padding(.horizontal, 10)- .frame(height: 32)- .background(item == page ? Palette.text.opacity(0.08) : .clear, in: RoundedRectangle(cornerRadius: 10, style: .continuous))- .contentShape(Rectangle())- }- .buttonStyle(.plain)- .accessibilityAddTraits(item == page ? .isSelected : [])- }-- @ViewBuilder private var content: some View {- switch page {- case .general: GeneralSettings(onSignIn: onSignIn, onSignOut: onSignOut)- case .computers: ComputersView(showsHeader: false)- case .voice:- if let store = host.store {- VoiceChatSettingsView(showsHeader: false).environment(store)- } else {- CardForm {- Text("Voice keys are kept by this Mac's host, which isn't running.").foregroundStyle(Palette.secondary)- }- }- case .usage: CardForm { UsageLimitsList() }- case .updates: UpdateSettings()- }- }-}--/// Account, window and app preferences.-private struct GeneralSettings: View {- let onSignIn: (AccountSession.SignInProvider) -> Void- let onSignOut: () -> Void- @Environment(HostController.self) private var host- @Environment(AccountSession.self) private var account- @AppStorage("sidebarCompact") private var compact = false- @AppStorage(ConversationTypography.preferenceKey) private var fontSize = ConversationTypography.defaultSize- @AppStorage(SharedStore.usageIconStyleKey, store: UserDefaults(suiteName: SharedStore.appGroup))- private var usageIconStyle = UsageIconStyle.character.rawValue-- var body: some View {- CardForm {- CardSection("Account", footer: account.errorMessage) {- HStack(spacing: 10) {- Image(systemName: "person.crop.circle")- .appFont(.system(size: 26))- .foregroundStyle(Palette.secondary)- .accessibilityHidden(true)- VStack(alignment: .leading, spacing: 1) {- Text(account.isSignedIn ? (account.email ?? "Signed in") : "Not signed in").lineLimit(1)- Text(account.isSignedIn ? "Reach your computers from anywhere" : "Sign in to reach your computers from anywhere")- .appFont(.caption).foregroundStyle(Palette.secondary)- }- Spacer(minLength: 8)- if account.isSignedIn {- Button(account.isBusy ? "Please wait…" : "Sign out", action: onSignOut)- .buttonStyle(.secondary)- .disabled(account.isBusy)- } else {- Button("Apple") { onSignIn(.apple) }.buttonStyle(.secondary).disabled(account.isBusy)- Button("Google") { onSignIn(.google) }.buttonStyle(.secondary).disabled(account.isBusy)- }- }- }- CardSection("Appearance") {- ValueRow("Text size") {- ChoicePicker(selection: $fontSize, options: ConversationTypography.sizes.map { size in- (size, size == ConversationTypography.defaultSize ? "\(Int(size)) pt (Default)" : "\(Int(size)) pt")- })- }- ValueRow("Usage icons") {- ChoicePicker(selection: $usageIconStyle, options: [- (UsageIconStyle.character.rawValue, "Character"), (UsageIconStyle.original.rawValue, "Original"),- ])- }- Toggle("Compact sidebar", isOn: $compact).toggleStyle(.codync)- }- CardSection("System") {- Toggle("Open at login", isOn: Binding(get: { host.launchAtLogin }, set: { host.setLaunchAtLogin($0) }))- .toggleStyle(.codync)- }- }- }-}--/// Every computer's usage limits, grouped by computer when there's more than one.-struct UsageLimitsList: View {- @Environment(HostController.self) private var host-- var body: some View {- let stores = host.accounts.computers.compactMap { host.accounts.store(for: $0.id) }- let withUsage = stores.filter { !$0.usage.providers.isEmpty }- if withUsage.isEmpty {- Text("No usage information yet.").foregroundStyle(Palette.secondary)- } else {- ForEach(withUsage, id: \.computer.id) { store in- if stores.count > 1 {- Label { Text(store.hostName) } icon: { ComputerBadge(store.computer, size: 16) }- .appFont(.headline)- }- UsageLimits(usage: store.usage)- }- }- }-}--/// Sparkle's update check and preferences, the same as the menu bar's Updates menu.-private struct UpdateSettings: View {- @Environment(UpdatesManager.self) private var updates-- var body: some View {- @Bindable var updates = updates- CardForm {- CardSection("Codync", footer: footer) {- ValueRow("Version", detail: updates.lastUpdateCheckDate.map { "Last checked \($0.formatted(date: .abbreviated, time: .shortened))" }) {- HStack(spacing: 10) {- Text(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "")- Button(updates.availableVersion.map { "Update to \($0)" } ?? "Check for updates") {- updates.checkForUpdates()- }- .buttonStyle(.secondary)- .disabled(!updates.canCheckForUpdates && !updates.hasStagedUpdate)- }- }- Toggle("Automatically check for updates", isOn: $updates.automaticallyChecksForUpdates)- .toggleStyle(.codync)- .disabled(!updates.isSupported)- Toggle("Automatically download and install", isOn: $updates.automaticallyDownloadsUpdates)- .toggleStyle(.codync)- .disabled(!updates.isSupported)- if let error = updates.errorMessage {- HStack {- Text(error).foregroundStyle(Palette.warning).fixedSize(horizontal: false, vertical: true)- Spacer(minLength: 8)- Button("Retry") { updates.retryInstallation() }- .buttonStyle(.secondary)- .disabled(updates.preparingInstallation)- }- }- }- }- }-- private var footer: String? {- if !updates.isSupported { return "Updates are available in release builds." }- if let app = updates.waitingForApp { return "Waiting for iPhone app \(app) to pass App Store review." }- return nil- }-}diff --git a/apps/project.yml b/apps/project.ymlindex e80fdbb8..b05816de 100644--- a/apps/project.yml+++ b/apps/project.yml@@ -10,14 +10,11 @@ options:icon:file: truepackages:- Sparkle:- url: https://github.com/sparkle-project/Sparkle- exactVersion: 2.10.0Clerk:url: https://github.com/clerk/clerk-iosexactVersion: 1.5.6CodyncKit:- path: ../kit+ path: ios/KitWebRTC:url: https://github.com/stasel/WebRTCexactVersion: 153.0.0@@ -38,97 +35,6 @@ settings:Release:CODYNC_ENV: maintargets:- macOS:- type: application- platform: macOS- sources:- - path: shared- excludes:- - Config- - path: macos- excludes:- - LaunchAgents- # Registered with SMAppService.agent when Remote screen is turned on.- - path: macos/LaunchAgents/com.pokai.Codync.screen.plist- buildPhase:- copyFiles:- destination: wrapper- subpath: Contents/Library/LaunchAgents- dependencies:- - package: Sparkle- product: Sparkle- - package: Clerk- product: ClerkKit- - package: CodyncKit- product: CodyncKit- - package: CodyncKit- product: CodyncUI- - target: Screen- embed: true- codeSign: true- copy:- destination: wrapper- subpath: Contents/Library/LoginItems- settings:- base:- PRODUCT_NAME: Codync- PRODUCT_BUNDLE_IDENTIFIER: com.pokai.Codync- GENERATE_INFOPLIST_FILE: YES- INFOPLIST_FILE: macos/Resources/Info.plist- # Sparkle compares this version; iOS retains its separate upload counter.- CURRENT_PROJECT_VERSION: "$(MARKETING_VERSION)"- INFOPLIST_KEY_CFBundleDisplayName: Codync- INFOPLIST_KEY_LSApplicationCategoryType: public.app-category.developer-tools- INFOPLIST_KEY_NSHumanReadableCopyright: ""- INFOPLIST_KEY_NSMicrophoneUsageDescription: Talk to your bots in a voice call.- INFOPLIST_KEY_NSSpeechRecognitionUsageDescription: Your words are transcribed on this Mac and sent to your bot as a message.- ENABLE_HARDENED_RUNTIME: YES- # Voice calls: the hardened runtime blocks the microphone without audio-input.- # A file, not ENABLE_RESOURCE_ACCESS_AUDIO_INPUT, so the release re-sign can pass it too.- CODE_SIGN_ENTITLEMENTS: macos/Resources/macOS.entitlements- ENABLE_APP_SANDBOX: NO- ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon- # Black / white instead of the system blue wherever macOS draws the app's accent.- ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME: AccentColor- postBuildScripts:- - name: Codync environment- basedOnDependencyAnalysis: false- showEnvVars: false- script: |- # Debug builds use dev (dev-api.codync.dev), Release builds use main (api.codync.dev).- cp "$SRCROOT/shared/Config/$CODYNC_ENV.plist" "$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/AccountConfig.plist"- - name: Embed codync-host- basedOnDependencyAnalysis: false- showEnvVars: false- script: |- # Builds the Rust host and ships it inside Codync.app/Contents/MacOS.- export PATH="$HOME/.cargo/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"- if ! command -v cargo >/dev/null; then- echo "warning: cargo not found; Codync.app will look for codync-host on PATH instead"- exit 0- fi- PROFILE=release- [ "$CONFIGURATION" = "Debug" ] && PROFILE=debug- FLAGS=""- [ "$PROFILE" = "release" ] && FLAGS="--release"- if [ "$PROFILE" = "release" ]; then- rustup target add aarch64-apple-darwin x86_64-apple-darwin >/dev/null 2>&1 || true- cargo build --release --manifest-path "$SRCROOT/../host/Cargo.toml" --target aarch64-apple-darwin &&- cargo build --release --manifest-path "$SRCROOT/../host/Cargo.toml" --target x86_64-apple-darwin &&- lipo -create -output "$SRCROOT/../host/target/codync-host-universal" \- "$SRCROOT/../host/target/aarch64-apple-darwin/release/codync-host" \- "$SRCROOT/../host/target/x86_64-apple-darwin/release/codync-host" &&- BIN="$SRCROOT/../host/target/codync-host-universal" ||- { cargo build --release --manifest-path "$SRCROOT/../host/Cargo.toml" && BIN="$SRCROOT/../host/target/release/codync-host"; }- else- cargo build --manifest-path "$SRCROOT/../host/Cargo.toml" && BIN="$SRCROOT/../host/target/debug/codync-host"- fi- [ -n "$BIN" ] || { echo "error: building codync-host failed"; exit 1; }- DEST="$TARGET_BUILD_DIR/$EXECUTABLE_FOLDER_PATH/codync-host"- cp "$BIN" "$DEST"- if [ -n "$EXPANDED_CODE_SIGN_IDENTITY" ] && [ "$CODE_SIGNING_ALLOWED" != "NO" ]; then- codesign --force --options runtime --timestamp=none --sign "$EXPANDED_CODE_SIGN_IDENTITY" "$DEST"- fi# Screen capture, input and WebRTC for Remote screen. A separate signed bundle so# macOS's Screen Recording / Accessibility grants belong to it (see host/src/screen.rs).Screen:@@ -161,6 +67,8 @@ targets:- Widgets- NotificationService- WhatsNew.md+ # The app's shared Swift package (models, client, screens), added as a package below.+ - Kitdependencies:- package: Clerkproduct: ClerkKitdiff --git a/apps/shared/AccountSession.swift b/apps/shared/AccountSession.swiftindex cbe33320..99d75f27 100644--- a/apps/shared/AccountSession.swift+++ b/apps/shared/AccountSession.swift@@ -110,13 +110,7 @@ final class AccountSession {case .google:result = try await clerk.auth.signInWithOAuth(provider: .google, prefersEphemeralWebBrowserSession: isSignedIn)case .apple:- #if os(macOS)- // The desktop OAuth flow uses the Services ID grouped with our iOS App ID.- // Clerk therefore receives the same Apple identity, including Hide My Email.- result = try await clerk.auth.signInWithOAuth(provider: .apple, prefersEphemeralWebBrowserSession: isSignedIn)- #elseresult = try await clerk.auth.signInWithApple()- #endif}switch result {case .signIn(let signIn):diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.mdnew file mode 100644index 00000000..f55df9b9--- /dev/null+++ b/docs/architecture/desktop-app.md@@ -0,0 +1,83 @@+# Desktop app (macOS and Linux)++Codync's computer-side app is one Electron app in `apps/desktop/` for macOS and Linux. It+replaced the SwiftUI Mac app (`apps/macos/`) and the GTK 4 Linux app (`apps/linux/`) in 2.7.0.+The iPhone app stays native SwiftUI; its package moved from `kit/` into `apps/ios/Kit/`.++## Why++- **The chat was too slow.** Long transcripts with Markdown, variable-height rows and+ streaming replies are where SwiftUI's lazy stacks struggle: scrolling and following a reply+ as it streams needed an AppKit scroll view with hand-managed row hosting to stay usable. A+ browser engine lays out and scrolls long text natively.+- **Two desktop apps were too much to keep in step.** Every UI change had to land in SwiftUI+ and in GTK. One TypeScript app now covers both platforms (and Windows later, if wanted).+- The iPhone app has no such alternative and keeps SwiftUI, so `kit/` lost its second+ platform and became the iPhone app's own package.++## Layout++| Path | |+|---|---|+| `src/main/` | Main process: host service (`host-controller.ts`), loopback HTTP/SSE proxy (`host-proxy.ts`), menu bar/tray, windows, account sign-in (Clerk Frontend API, `account.ts`), cloud API and device key (`cloud.ts`), updates (`updates.ts`), SSH tunnels (`ssh.ts`), Codync Screen agent (`screen.ts`), on-device speech (`speech.ts`), browser sign-in callbacks (`auth.ts`) |+| `src/preload/` | The `window.codync` bridge (types in `src/shared/ipc.ts`) |+| `src/renderer/store/` | `BotStore` (port of kit's), `AppModel` (window state, approvals), `CloudModel` (claims, cloud default), `AccountSession` |+| `src/renderer/components/` | Design system: controls, overlays (sheets, dialogs, menus), SF Symbol icons, character avatars, thinking orbs |+| `src/renderer/views/` | Screens, mirroring kit's folders (`thread/`, `bots/`, `marketplace/`, `settings/`, `routines/`, `call/`) |+| `native/speech-macos/` | `codync-speech`, a Swift helper running SFSpeechRecognizer for on-device calls |+| `tools/export-symbols.swift` | Renders the SF Symbols the app uses into masks at build time (macOS) |++The renderer owns all state; closing the window hides it, so the menu bar keeps its data.+HTTP to the host leaves from the main process (the loopback API has no CORS).++## Platform notes++- **Icons**: SF Symbols may only ship in apps for Apple platforms, so the masks are generated+ on macOS at build time and never committed; Linux draws the closest Lucide icons.+- **On-device speech** is macOS only; Linux calls use OpenAI or Gemini on the user's key.+- **Host**: the Mac app bundles `codync-host` in `Contents/Resources`; Linux uses the installed+ host (an AppImage's mount path changes on every launch, so a service can't point into it).+- **Remote screen** on macOS registers `CodyncScreen.app` (built from the Xcode `Screen` target)+ as an SMAppService agent; Linux starts its helper from the host, as before.+- **Other computers in the account** are reached through this computer's own host and SSH+ tunnels only. The encrypted channel to account computers (`ChannelTransport`) wasn't ported:+ the product targets one computer, so "Ask for access" rows show status only.+- **Updates**: electron-updater from GitHub releases (`latest-mac.yml` carries `minApp`, the same+ iPhone gate as before). Installs of the SwiftUI app get the first desktop release through one+ more Sparkle appcast, generated for the zip by the release workflow.++## Development++```sh+cd apps/desktop+npm ci+node tools/account-config.mjs dev # Clerk key + cloud URL for this build+npm run icons # macOS: SF Symbol masks+npm run dev # against the installed host on 19222+CODYNC_PORT=19333 CODYNC_HOME=/path/to/home npm run dev # against a manually run host+npm run typecheck && npm test+```++UI checks: `CODYNC_SHOW_INACTIVE=1` opens the window without taking focus,+`CODYNC_DEBUG_OPEN=compose|group|plugins|computers|<bot name>` opens a screen, and+`CODYNC_REMOTE_DEBUG=<port>` lets a script drive the renderer over the DevTools protocol.+Packaging: `npm run dist:mac` / `npm run dist:linux` after placing the native pieces listed at+the top of `electron-builder.yml` (the release workflow, `.github/workflows/release-desktop.yml`,+does this).++## Parity with the SwiftUI app++The port follows the Swift sources view by view (metrics, fonts, colors, motion), including the+Mac chat redesign that was in progress at the time (larger chat text, actions beside messages,+one composer capsule, circular chat controls, Jump to latest). It was checked side by side with+the SwiftUI build against the same host using screenshots from Computer Use.++## The SwiftUI apps in the history++`apps/macos/`, `apps/linux/` and the Mac code paths in `kit/` are in Git. The commit that+removed them is `git log --oneline -1 -- apps/macos`; its parent is the last SwiftUI version:++```sh+git show <commit>^:apps/macos/Views/ChatWindow.swift+git worktree add ../codync-swiftui <commit>^+```diff --git a/kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/Contents.json b/kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/Contents.jsondeleted file mode 100644index 73c00596..00000000--- a/kit/Sources/CodyncKit/Resources/ProviderIcons.xcassets/Contents.json+++ /dev/null@@ -1,6 +0,0 @@-{- "info" : {- "author" : "xcode",- "version" : 1- }-}diff --git a/kit/Sources/CodyncUI/Thread/MarkdownText.swift b/kit/Sources/CodyncUI/Thread/MarkdownText.swiftdeleted file mode 100644index 8b93583c..00000000--- a/kit/Sources/CodyncUI/Thread/MarkdownText.swift+++ /dev/null@@ -1,145 +0,0 @@-#if os(macOS)-import CodyncKit-import SwiftUI--/// The Mac's Markdown renderer (the iPhone's is `MarkdownText+iOS.swift`).-/// Small block-level Markdown renderer: paragraphs, headings, lists, quotes and-/// fenced code; inline styling comes from `AttributedString(markdown:)`.-public struct MarkdownText: View {- let blocks: [Block]- let streaming: Bool- @Environment(\.accessibilityReduceMotion) private var reduceMotion- @Environment(\.conversationTypography) private var typography-- private var contentTransition: ContentTransition {- streaming && !reduceMotion ? .interpolate : .identity- }-- private var textAnimation: Animation? {- streaming ? Motion.reduced(Motion.fade, reduceMotion) : nil- }-- public init(_ source: String, streaming: Bool = false) {- blocks = Self.parse(source)- self.streaming = streaming- }-- enum Block: Hashable {- case paragraph(String)- case heading(String, level: Int)- case bullet(String, marker: String)- case quote(String)- case code(String, language: String)- }-- public var body: some View {- VStack(alignment: .leading, spacing: 8) {- ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in- view(for: block)- }- }- .textSelection(.enabled)- }-- @ViewBuilder private func view(for block: Block) -> some View {- switch block {- case let .paragraph(t):- Text(Self.inline(t))- .font(typography.body)- .foregroundStyle(Palette.text)- .contentTransition(contentTransition)- .animation(textAnimation, value: t)- case let .heading(t, level):- Text(Self.inline(t))- .font(typography.heading(level: level))- .foregroundStyle(Palette.text)- .contentTransition(contentTransition)- .animation(textAnimation, value: t)- case let .bullet(t, marker):- HStack(alignment: .firstTextBaseline, spacing: 6) {- Text(marker).foregroundStyle(Palette.secondary).monospacedDigit()- Text(Self.inline(t))- .foregroundStyle(Palette.text)- .contentTransition(contentTransition)- .animation(textAnimation, value: t)- }- .font(typography.body)- case let .quote(t):- Text(Self.inline(t))- .font(typography.body)- .foregroundStyle(Palette.secondary)- .contentTransition(contentTransition)- .animation(textAnimation, value: t)- .padding(.leading, 10)- .overlay(alignment: .leading) { Rectangle().fill(Palette.border).frame(width: 3) }- case let .code(t, _):- ScrollView(.horizontal, showsIndicators: false) {- Text(t)- .font(typography.code)- .foregroundStyle(Palette.text)- .padding(10)- }- .background(Palette.codeBackground, in: RoundedRectangle(cornerRadius: 8))- }- }-- static func inline(_ s: String) -> AttributedString {- (try? AttributedString(markdown: s, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) ?? AttributedString(s)- }-- static func parse(_ source: String) -> [Block] {- var blocks: [Block] = []- var paragraph: [String] = []- var code: [String]?- var language = ""-- func flush() {- if !paragraph.isEmpty {- blocks.append(.paragraph(paragraph.joined(separator: "\n")))- paragraph = []- }- }-- for raw in source.components(separatedBy: "\n") {- let line = raw.trimmingCharacters(in: .whitespaces)- if line.hasPrefix("```") {- if let c = code {- blocks.append(.code(c.joined(separator: "\n"), language: language))- code = nil- } else {- flush()- code = []- language = String(line.dropFirst(3))- }- continue- }- if code != nil {- code?.append(raw)- continue- }- if line.isEmpty {- flush()- } else if let hashes = line.firstIndex(where: { $0 != "#" }), line.hasPrefix("#"), line[hashes] == " " {- flush()- let level = line.distance(from: line.startIndex, to: hashes)- blocks.append(.heading(String(line[hashes...]).trimmingCharacters(in: .whitespaces), level: level))- } else if line.hasPrefix("- ") || line.hasPrefix("* ") || line.hasPrefix("• ") {- flush()- blocks.append(.bullet(String(line.dropFirst(2)), marker: "•"))- } else if let dot = line.firstIndex(of: "."), line[..<dot].allSatisfy(\.isNumber), !line[..<dot].isEmpty,- line[line.index(after: dot)...].hasPrefix(" ") {- flush()- blocks.append(.bullet(String(line[line.index(dot, offsetBy: 2)...]), marker: String(line[...dot])))- } else if line.hasPrefix("> ") {- flush()- blocks.append(.quote(String(line.dropFirst(2))))- } else {- paragraph.append(raw)- }- }- if let c = code { blocks.append(.code(c.joined(separator: "\n"), language: language)) }- flush()- return blocks- }-}-#endifdiff --git a/kit/Sources/CodyncUI/Thread/RepliesView+macOS.swift b/kit/Sources/CodyncUI/Thread/RepliesView+macOS.swiftdeleted file mode 100644index cbd232a1..00000000--- a/kit/Sources/CodyncUI/Thread/RepliesView+macOS.swift+++ /dev/null@@ -1,40 +0,0 @@-#if os(macOS)-import CodyncKit-import SwiftUI--extension RepliesView {- /// The Mac's replies: a lazy stack that opens at the newest.- @ViewBuilder var messages: some View {- let replies = model.replies(botId, root: rootId)- ScrollView {- LazyVStack(alignment: .leading, spacing: 0) {- if let root {- ChatRow(entry: root, groupStart: true, chat: chat) { showTrace = true }- HStack(spacing: 10) {- Text(replies.isEmpty ? "No replies yet" : replies.count == 1 ? "1 reply" : "\(replies.count) replies")- .appFont(.caption)- .foregroundStyle(Palette.tertiary)- .fixedSize()- Rectangle().fill(Palette.border).frame(height: 1)- }- .padding(.vertical, 12)- }- ForEach(ChatItem.build(replies, streaming: chat?.isWorking(in: botId, thread: rootId) == true && !model.isOffline)) { item in- if case let .entry(e, groupStart) = item.kind {- ChatRow(entry: e, groupStart: groupStart, chat: chat) { showTrace = true }- }- }- if let chat, chat.isWorking(in: botId, thread: rootId), !model.isOffline {- WorkingIndicator(bot: chat, thinking: model.currentThinking(botId, thread: rootId)).padding(.top, 6)- }- Color.clear.frame(height: 8)- }- .padding(.horizontal, 16)- .padding(.top, 8)- }- .scrollIndicators(.never)- .defaultScrollAnchor(.bottom)- .scrollDismissesKeyboard(.interactively)- }-}-#endifdiff --git a/kit/Sources/CodyncUI/Thread/ThreadView+macOS.swift b/kit/Sources/CodyncUI/Thread/ThreadView+macOS.swiftdeleted file mode 100644index dc92fbd9..00000000--- a/kit/Sources/CodyncUI/Thread/ThreadView+macOS.swift+++ /dev/null@@ -1,414 +0,0 @@-#if os(macOS)-import CodyncKit-import SwiftUI--extension ThreadView {- var platformBody: some View {- GeometryReader { geometry in- HStack(spacing: 0) {- conversation.frame(maxWidth: .infinity)- if let openThread, geometry.size.width >= 680 {- HStack(spacing: 0) {- Rectangle().fill(Palette.border).frame(width: 1)- RepliesView(botId: botId, rootId: openThread.id) { closeThread() }- .frame(width: min(420, geometry.size.width * 0.45))- }- .id(openThread.id)- .transition(.move(edge: .trailing).combined(with: .opacity))- } else if showSettings && geometry.size.width >= 680 {- HStack(spacing: 0) {- Rectangle().fill(Palette.border).frame(width: 1)- detailsPanel.frame(width: 292)- }- .transition(.move(edge: .trailing).combined(with: .opacity))- }- }- .clipped()- .onGeometryChange(for: CGFloat.self) {- $0.size.width- } action: {- availableWidth = $0- }- }- .ignoresSafeArea(.container, edges: .top)- .animation(Motion.reduced(Motion.layout, reduceMotion), value: openThread)- .codyncSheet(isPresented: $compactDetails) {- detailsPanel.frame(width: 340, height: 600)- }- .codyncSheet(isPresented: Binding(get: { openThread != nil && availableWidth < 680 }, set: { if !$0 { openThread = nil } })) {- if let openThread {- RepliesView(botId: botId, rootId: openThread.id) { closeThread() }.frame(width: 440, height: 600)- }- }- }-- /// The Mac's messages: every loaded message in a lazy stack, brought to the newest as it- /// changes while the reader is at the bottom.- @ViewBuilder var transcript: some View {- let thread = model.chat(botId)- let items = ChatItem.build(thread, streaming: bot?.isWorking(in: botId, thread: nil) == true && !model.isOffline)- ScrollViewReader { proxy in- ScrollView {- LazyVStack(alignment: .leading, spacing: 0) {- if !model.historyComplete.contains(botId), thread.count >= 50 {- Button("Load earlier messages") { Task { await model.loadOlder(botId) } }- .buttonStyle(.plain)- .appFont(.footnote)- .foregroundStyle(Palette.secondary)- .frame(maxWidth: .infinity)- .padding(.vertical, 12)- }- if items.isEmpty, let bot {- if bot.isGroup { GroupIntroCard(group: bot).padding(.top, 40) } else { IntroCard(bot: bot).padding(.top, 40) }- }- ForEach(items) { item in- row(item)- .id(item.id)- .transition(item.id == items.last?.id- ? .asymmetric(insertion: .move(edge: .bottom).combined(with: .opacity), removal: .opacity)- : .identity)- }- // 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, thinking: model.currentThinking(botId, thread: nil))- .padding(.top, 6)- .id("working")- }- Color.clear.frame(height: 8).id("bottom")- }- .padding(.horizontal, 16)- .padding(.top, 8)- .animation(Motion.reduced(Motion.conversation, reduceMotion), value: items.last?.id)- .frame(maxWidth: 820)- .frame(maxWidth: .infinity)- }- .scrollIndicators(.never)- .conversationInitialBottomAnchor()- .scrollDismissesKeyboard(.interactively)- .conversationScrollEdges()- .conversationBottomObserver($isAtBottom)- .onChange(of: items.last?.id) { _, _ in- guard isAtBottom || items.last?.isUserMessage == true else { return }- withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {- proxy.scrollTo("bottom", anchor: .bottom)- }- }- .onChange(of: items.last?.textContent) { _, _ in- guard isAtBottom else { return }- withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {- proxy.scrollTo("bottom", anchor: .bottom)- }- }- .onChange(of: bot?.isWorking) { _, _ in- guard isAtBottom else { return }- withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {- proxy.scrollTo("bottom", anchor: .bottom)- }- }- .onChange(of: typography.pointSize) { _, _ in- guard isAtBottom else { return }- proxy.scrollTo("bottom", anchor: .bottom)- }- }- }-- func platformChrome(_ content: some View) -> some View {- content- // Grok's desktop chat: no title bar. The chat blurs and fades as it scrolls up, with the bot- // in a floating solid pill and the actions as glass buttons on the right.- .safeAreaInset(edge: .top, spacing: 0) {- ZStack {- HStack(spacing: 8) {- Spacer(minLength: 0)- if !showSettings || availableWidth < 680 {- IconButton("Conversation details", systemImage: "chevron.left.2") { toggleDetails() }- .keyboardShortcut("i", modifiers: [.command, .option])- .frosted(in: Circle())- .transition(.opacity)- }- }- VStack(spacing: 2) {- header- if model.shownConnection != .online || model.mismatch != nil { connectionSubtitle }- }- .padding(.leading, 10)- .padding(.trailing, 16)- .padding(.vertical, 9)- .background(Palette.background, in: Capsule())- .shadow(color: .black.opacity(0.12), radius: 16, y: 4)- }- .padding(.horizontal, 16)- .padding(.top, 10)- .padding(.bottom, 14)- .background(alignment: .top) { TopFade() }- }- }-- var header: some View {- Button(action: toggleDetails) { title }- .buttonStyle(.plain)- .accessibilityLabel("View conversation details")- .help("View conversation details")- }-- private func toggleDetails() {- if availableWidth < 680 {- compactDetails.toggle()- } else {- withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { showSettings.toggle() }- }- }-- /// Its own view so it stays live inside the compact modal (which captures its content).- private var detailsPanel: some View {- DetailsPanel(botId: botId, routineId: routineId, editing: $editingDetails, editGroup: { editingGroup = true },- share: {- compactDetails = false- if let bot { templateRequest = EditorRequest(BotDraft(bot)) }- }) {- withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { showSettings = false }- compactDetails = false- }- .id(routineRequest)- }-- func presentRoutine() {- editingDetails = false- openThread = nil- showSettings = true- if availableWidth < 680 { compactDetails = true }- }-- func editProfile(_ bot: Bot) {- withAnimation(Motion.reduced(Motion.layout, reduceMotion)) {- editingDetails = true- showSettings = true- }- if availableWidth < 680 { compactDetails = true }- }-}--/// A group's bots in the Mac inspector; clicking one opens its own chat.-private struct GroupMembersList: View {- let group: Bot- @Environment(BotStore.self) private var model-- var body: some View {- ScrollView {- VStack(alignment: .leading, spacing: 2) {- Text("\(group.members.count) bots").appFont(.system(size: 13, weight: .semibold)).padding(.bottom, 6)- ForEach(model.members(of: group)) { bot in- Button { model.selection = bot.id } label: {- HStack(spacing: 10) {- CharacterAvatar(bot: bot, size: 26)- VStack(alignment: .leading, spacing: 1) {- Text(bot.name).appFont(.system(size: 13)).foregroundStyle(Palette.text)- Text(bot.isWorking ? (bot.activity.isEmpty ? "Working…" : bot.activity) : bot.folderName)- .appFont(.system(size: 11)).foregroundStyle(Palette.tertiary).lineLimit(1)- }- Spacer()- }- .padding(.vertical, 6)- .contentShape(Rectangle())- }- .buttonStyle(PressScale())- .help("Open \(bot.name)'s own chat")- }- }- .padding(.horizontal, 16)- }- }-}--/// 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- /// Shares the bot as a template.- let share: () -> Void- let close: () -> Void- @Environment(BotStore.self) private var model- @Environment(\.accessibilityReduceMotion) private var reduceMotion-- private var bot: Bot? { model.bots[botId] }-- var body: some View {- VStack(spacing: 0) {- HStack(spacing: 8) {- if editing {- roundButton("Back to details", "chevron.left") { setEditing(false) }- panelTitle("Settings")- Spacer()- } else if bot?.isGroup == true {- panelTitle("Members")- Spacer()- roundButton("Edit group", "gearshape", action: editGroup)- } else {- panelTitle("Details")- Spacer()- roundButton("Create template", "square.and.arrow.up", action: share)- roundButton("Bot settings", "gearshape") { setEditing(true) }- }- roundButton("Close details", "chevron.right.2", action: close)- .keyboardShortcut("i", modifiers: [.command, .option])- }- .padding(.horizontal, 12)- .frame(height: 54)- ZStack {- if let bot, bot.isGroup {- GroupMembersList(group: bot)- } else if editing {- BotSettingsPanel(botId: botId)- .transition(.move(edge: .trailing).combined(with: .opacity))- } else {- details- .transition(.move(edge: .leading).combined(with: .opacity))- }- }- .frame(maxHeight: .infinity, alignment: .top)- .clipped()- }- .background(Palette.background)- }-- private func setEditing(_ on: Bool) {- withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { editing = on }- }-- private func panelTitle(_ title: String) -> some View {- Text(title)- .appFont(.system(size: 15, weight: .semibold))- .foregroundStyle(Palette.text)- .padding(.leading, 4)- }-- /// A round action in the panel's header, frosted like the chat's title pill (Grok's style).- private func roundButton(_ label: String, _ symbol: String, action: @escaping () -> Void) -> some View {- Button(action: action) {- Image(systemName: symbol)- .appFont(.system(size: 13, weight: .medium))- .foregroundStyle(Palette.text)- .frame(width: 32, height: 32)- .frosted(in: Circle())- .contentShape(Circle())- }- .buttonStyle(PressScale())- .accessibilityLabel(label)- .help(label)- }-- private var details: some View {- ScrollView {- VStack(alignment: .leading, spacing: 28) {- computerSummary- RoutinesView(botId: botId, initialId: routineId)- if let bot { agentSummary(bot) }- }- .padding(.horizontal, 16)- .padding(.top, 4)- .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)- .appFont(.system(size: 15, weight: .medium))- .foregroundStyle(Palette.text)- .lineLimit(2)- Text("Remote screen")- .appFont(.system(size: 13))- .foregroundStyle(Palette.secondary)- }- }- if !model.isOffline {- Label(computerStatus, systemImage: computerStatusSymbol)- .appFont(.system(size: 13))- .foregroundStyle(Palette.text)- .fixedSize(horizontal: false, vertical: true)- }- if screenReady {- Text("View and control this Mac from your iPhone.")- .appFont(.system(size: 12))- .foregroundStyle(Palette.secondary)- .fixedSize(horizontal: false, vertical: true)- .padding(.top, -8)- }- }- .frame(maxWidth: .infinity, alignment: .leading)- .padding(16)- .background(Palette.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))- }-- private func agentSummary(_ bot: Bot) -> some View {- CardSection("Agent", footer: bot.description.isEmpty ? nil : bot.description) {- infoRow("Runtime") {- HStack(spacing: 6) {- AgentIcon(registry: model.hello?.backends.first { $0.id == bot.backend }?.registry, size: 14)- Text(model.backendName(bot.backend))- }- }- infoRow(bot.managedWorkspace ? "Workspace" : "Folder") {- Text(bot.managedWorkspace ? "Personal" : bot.folderName)- .truncationMode(.middle)- .help(bot.managedWorkspace ? "Personal workspace, managed by Codync" : bot.cwd)- }- if let chosen = bot.model, !chosen.isEmpty {- infoRow("Model") { Text(chosen).truncationMode(.middle) }- }- }- }-- /// Label on the left, value on the right, one line.- private func infoRow(_ label: String, @ViewBuilder value: () -> some View) -> some View {- HStack(spacing: 12) {- Text(label).foregroundStyle(Palette.secondary)- Spacer(minLength: 8)- value().foregroundStyle(Palette.text).lineLimit(1)- }- .appFont(.system(size: 13))- }-- private var screenReady: Bool {- !model.isOffline && model.screen?.enabled == true- && model.screen?.connected == true && model.screen?.capture == true- }-- private var computerStatusSymbol: String {- 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 {- 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 to connect"- }-}--/// The top edge of the chat: messages fade out gradually as they scroll under the title pill,-/// readable behind the pill and gone only at the very top.-private struct TopFade: View {- var body: some View {- ZStack {- Rectangle().fill(.ultraThinMaterial)- .mask(LinearGradient(colors: [.black, .clear], startPoint: .top, endPoint: .center))- LinearGradient(stops: [.init(color: Palette.background, location: 0),- .init(color: Palette.background.opacity(0.6), location: 0.35),- .init(color: Palette.background.opacity(0), location: 1)],- startPoint: .top, endPoint: .bottom)- }- .ignoresSafeArea(edges: .top)- .allowsHitTesting(false)- }-}-#endifdiff --git a/kit/Tests/CodyncKitTests/AppFontTests.swift b/kit/Tests/CodyncKitTests/AppFontTests.swiftdeleted file mode 100644index 9c5d83e6..00000000--- a/kit/Tests/CodyncKitTests/AppFontTests.swift+++ /dev/null@@ -1,46 +0,0 @@-import SwiftUI-import Testing-@testable import CodyncKit--#if os(macOS)-@Test func appFontsPreserveDefaultStyling() {- let styles: [(AppFont, Font)] = [- (.body, .body),- (.title3, .title3),- (.footnote, .footnote),- (.headline, .headline),- (.caption.bold(), .caption.bold()),- (.footnote.monospaced(), .footnote.monospaced()),- (.caption.monospacedDigit(), .caption.monospacedDigit()),- (.system(size: 12), .system(size: 12)),- (.system(size: 20, weight: .medium, design: .rounded), .system(size: 20, weight: .medium, design: .rounded)),- ]- for (appFont, original) in styles {- #expect(appFont.scaled(by: 1) == original)- }-}--@Test func appFontsPreserveRelativeSizesAndTraits() throws {- guard #available(macOS 26, *) else { return }- let context = EnvironmentValues().fontResolutionContext- let styles: [AppFont] = [.compactBody, .compactSecondary, .headline, .caption.bold(), .footnote.monospaced(),- .system(size: 20, weight: .medium, design: .rounded)]- for font in styles {- let original = font.scaled(by: 1).resolve(in: context)- for scale: CGFloat in [11.0 / 12, 1.5] {- let enlarged = font.scaled(by: scale).resolve(in: context)- #expect(abs(enlarged.pointSize / original.pointSize - scale) < 0.001)- #expect(enlarged.weight == original.weight)- #expect(enlarged.isBold == original.isBold)- #expect(enlarged.isMonospaced == original.isMonospaced)- }- // Exercise the macOS 14–15 path even when this test runs on a newer Mac.- let fallbackOriginal = font.fallbackScaled(by: 1).resolve(in: context)- let fallbackEnlarged = font.fallbackScaled(by: 1.5).resolve(in: context)- #expect(abs(fallbackEnlarged.pointSize / fallbackOriginal.pointSize - 1.5) < 0.001)- #expect(fallbackEnlarged.weight == original.weight)- #expect(fallbackEnlarged.isBold == original.isBold)- #expect(fallbackEnlarged.isMonospaced == original.isMonospaced)- }-}-#endifdiff --git a/packaging/homebrew/codync.rb b/packaging/homebrew/codync.rbindex 536a55de..92eeabef 100644--- a/packaging/homebrew/codync.rb+++ b/packaging/homebrew/codync.rb@@ -1,5 +1,5 @@# Homebrew cask template for the leepokai/homebrew-codync tap.-# The release job in .github/workflows/release-macos.yml fills in the version and the+# The macOS job in .github/workflows/release-desktop.yml fills in the version and the# DMG's sha256 on every `v*` tag.cask "codync" doversion "0.0.0"@@ -14,12 +14,12 @@ cask "codync" dodepends_on macos: :sonomaapp "Codync.app"- binary "#{appdir}/Codync.app/Contents/MacOS/codync-host"+ binary "#{appdir}/Codync.app/Contents/Resources/codync-host"# The app sets up the host service when it opens. Upgrades remove the service too;# Homebrew reopens the app afterwards, which sets it up again on the new version.uninstall early_script: {- executable: "#{appdir}/Codync.app/Contents/MacOS/codync-host",+ executable: "#{appdir}/Codync.app/Contents/Resources/codync-host",args: ["uninstall"],must_succeed: false,},@@ -27,6 +27,7 @@ cask "codync" dozap trash: ["~/.codync",+ "~/Library/Application Support/Codync","~/Library/Preferences/com.pokai.Codync.plist",]diff --git a/packaging/install.sh b/packaging/install.shindex 724af2ca..0cc971d3 100755--- a/packaging/install.sh+++ b/packaging/install.sh@@ -91,24 +91,33 @@ install_mac_app() {$sudo rm -rf /Applications/Codync.app$sudo ditto "$mnt/Codync.app" /Applications/Codync.apphdiutil detach -quiet "$mnt"- mkdir -p "$BIN_DIR" && ln -sf /Applications/Codync.app/Contents/MacOS/codync-host "$BIN_DIR/codync-host"+ mkdir -p "$BIN_DIR" && ln -sf /Applications/Codync.app/Contents/Resources/codync-host "$BIN_DIR/codync-host"say "Installed Codync.app to /Applications"- restart_service /Applications/Codync.app/Contents/MacOS/codync-host+ restart_service /Applications/Codync.app/Contents/Resources/codync-hostopen /Applications/Codync.app}install_linux_app() {name=codync-linux-$ARCH- fetch "$name.tar.gz"- tar xzf "$TMP/$name.tar.gz" -C "$TMP"- place "$TMP/$name/bin/codync" "$BIN_DIR/codync"+ fetch "$name.AppImage"+ place "$TMP/$name.AppImage" "$BIN_DIR/codync"data=${XDG_DATA_HOME:-$HOME/.local/share}[ "$(id -u)" = 0 ] && data=/usr/local/share- mkdir -p "$data" && cp -R "$TMP/$name/share/." "$data/"+ mkdir -p "$data/applications"+ cat > "$data/applications/com.pokai.Codync.desktop" <<EOF+[Desktop Entry]+Name=Codync+Comment=Your coding agents as teammates+Exec=$BIN_DIR/codync %U+Terminal=false+Type=Application+Categories=Development;+MimeType=x-scheme-handler/codync;x-scheme-handler/com.pokai.codync;+StartupWMClass=Codync+EOFsay "Installed the Codync desktop app to $BIN_DIR/codync"- if command -v ldd >/dev/null && missing=$(ldd "$BIN_DIR/codync" 2>&1 | grep 'not found'); then- echo " It won't start yet: it needs GTK 4, libadwaita, VTE (GTK 4) and glibc 2.39+ (Ubuntu 24.04 or newer). Missing:"- echo "$missing" | sed 's/^[[:space:]]*/ /' | sort -u+ if command -v ldconfig >/dev/null && ! ldconfig -p 2>/dev/null | grep -q libfuse.so.2; then+ echo " AppImages need FUSE 2 to start (Ubuntu: sudo apt install libfuse2t64)."fi}diff --git a/tools/asc-submit.py b/tools/asc-submit.pyindex 5c893fe4..0ca723d7 100755--- a/tools/asc-submit.py+++ b/tools/asc-submit.py@@ -42,7 +42,7 @@ NOTES = Path(__file__).resolve().parent.parent / "apps/ios/WhatsNew.md"EMOJI = re.compile("[\U00010000-\U0010FFFF\u2600-\u27BF\uFE0F\u200D]")WORKFLOW_ID = "44342080-ce08-4dc1-be35-34ce6cbb41b5" # Xcode Cloud "Release": Archive iOS for the App Store# What the iPhone app is built from; apps/project.yml counts except its version lines.-IOS_PATHS = ["apps/ios", "apps/shared", "kit", "apps/Codync.xcodeproj/project.xcworkspace"]+IOS_PATHS = ["apps/ios", "apps/shared", "apps/Codync.xcodeproj/project.xcworkspace"]def git(*args):