Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat(android): native phone client (#151)

leepokai87d8fbefb3c4
diff --git a/.githooks/pre-commit b/.githooks/pre-commit
index 8f332772..367f8be4 100755
--- a/.githooks/pre-commit
+++ b/.githooks/pre-commit
@@ -63,6 +63,19 @@ for dir in cloud relay discord; do
fi
done
+if touches '^apps/(android/|project\.yml)'; then
+ # Gradle needs JDK 21: macOS finds it with java_home, elsewhere JAVA_HOME points at it.
+ jdk=$( (/usr/libexec/java_home -v 21 2>/dev/null) || printf '%s' "${JAVA_HOME:-}")
+ if [ -n "$jdk" ]; then
+ staged_copy
+ echo "Checking the Android app (unit tests, compile)..."
+ (cd "$snapshot/apps/android" && JAVA_HOME="$jdk" ./gradlew --console=plain -q --build-cache \
+ :core:test :app:testDebugUnitTest :app:compileDebugKotlin)
+ else
+ echo "Skipping the Android checks (needs JDK 21)."
+ fi
+fi
+
if touches '^apps/screen-linux/'; then
staged_copy
echo "Checking Linux screen helper formatting..."
diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml
new file mode 100644
index 00000000..4ffbcb6a
--- /dev/null
+++ b/.github/workflows/android.yml
@@ -0,0 +1,43 @@
+name: Android
+
+on:
+ push:
+ branches: [main, dev]
+ paths:
+ - "apps/android/**"
+ - "apps/project.yml"
+ - "docs/reference/fixtures/remote-relay-vectors.json"
+ - ".github/workflows/android.yml"
+ pull_request:
+ paths:
+ - "apps/android/**"
+ - "apps/project.yml"
+ - "docs/reference/fixtures/remote-relay-vectors.json"
+ - ".github/workflows/android.yml"
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: apps/android
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: "21"
+ - uses: android-actions/setup-android@v3
+ with:
+ packages: platform-tools
+ - run: sdkmanager "platforms;android-37.0" "build-tools;37.0.0"
+ - uses: gradle/actions/setup-gradle@v4
+ - run: ./gradlew :core:test :app:testDebugUnitTest :app:assembleDebug :app:assembleDebugAndroidTest :app:assembleRelease :app:lintDebug
+ - uses: actions/upload-artifact@v4
+ with:
+ name: codync-android-debug
+ path: apps/android/app/build/outputs/apk/debug/*.apk
diff --git a/AGENTS.md b/AGENTS.md
index 4bc2d273..22d89940 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -5,6 +5,7 @@
- `host/`: Rust daemon, ACP integration, SQLite storage, HTTP/SSE API, and terminal UI; unit tests live alongside modules in `src/`.
- `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, Linux and Windows (Electron, React, TypeScript): [docs/architecture/desktop-app.md](docs/architecture/desktop-app.md).
+- `apps/android/`: Android phone app (Kotlin, Jetpack Compose), ported from the iPhone app: `core` (models, crypto, transport), `design` (Codync's components), `app` (screens, store, widgets): [apps/android/README.md](apps/android/README.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.
@@ -22,6 +23,7 @@ Run from the repository root unless a command changes directories:
- `cd apps/desktop && npm ci && npm run dev`: run the desktop app while developing and for its e2e check (renderer reloads on save, restart after `src/main` or preload changes; unpackaged, unsigned). After a host change run `node tools/native-host.mjs dev` there first: `npm run dev` prefers that build over `host/target/debug`. Package `npm run dist:mac:dev` (about 45 s) only for what an unpackaged run lacks (bundled host install, Codync Screen / computer use, system permissions); `dist:*:main` only to check the production 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 apps/android && ./gradlew :core:test :app:testDebugUnitTest :app:assembleDebug :app:lintDebug` (JDK 21, Android SDK 37): Android checks; `adb install -r app/build/outputs/apk/debug/app-debug.apk` installs Codync Dev.
- `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.
@@ -51,7 +53,7 @@ Use four-space indentation for Swift and Rust, two spaces for TypeScript. Follow
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, and the iPhone root uses the system `TabView`, 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, `ContentUnavailableView`. Use `apps/ios/Kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `.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.
+- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation, and the iPhone root uses the system `TabView`, 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, `ContentUnavailableView`. Use `apps/ios/Kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `.codyncDialog`, `ToggleStyle.codync`); on the desktop, `apps/desktop/src/renderer/components/` (`Sheet`, `Dialog`, `AnchoredMenu`, `ModalHeader`, `Controls.tsx`, `Icon` for SF Symbols); on Android, the `apps/android/design/` module (`CodyncSheet`, `ModalHeader`, `CodyncDialog`, `DropdownMenu`, `contextActions`, `Controls.kt`, `Symbol` for SF Symbols). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.
## Clean code
@@ -59,7 +61,7 @@ Name Swift files after their main `UpperCamelCase` type; use `snake_case.rs` and
## Cross-platform UI changes
-- 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, Linux and Windows), and terminal UI (`host/src/tui/`). This applies in every direction.
+- 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/`), Android (`apps/android/app/`), desktop (`apps/desktop/src/renderer/`, macOS, Linux and Windows), 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.
diff --git a/CLAUDE.md b/CLAUDE.md
index f2946614..35f17aef 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -10,6 +10,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess
- 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`
+- Android app (`apps/android/`) is Kotlin + Jetpack Compose, ported screen for screen from the iPhone app: screens use the `design` module (glass, sheets, menus, controls, `Symbol` for SF Symbol names), never Material widgets beyond `Text`; CI runs the Gradle checks in `.github/workflows/android.yml` ([apps/android/README.md](apps/android/README.md))
- 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)
@@ -19,7 +20,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess
## Architecture
-- Clients: iOS app (SwiftUI), desktop app for macOS, Linux and Windows (`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).
+- Clients: iOS app (SwiftUI), Android app (`apps/android/`, follows the iOS app; gaps in [docs/plans/android-app.md](docs/plans/android-app.md)), desktop app for macOS, Linux and Windows (`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).
- **Host owns the logic**: bot management, sessions, agent processes, MCP servers/connectors, routing, routines, memory, validation and anything heavy or needed by more than one client run in the Rust host. iOS, desktop and TUI render host state and send intents through the host API; they keep only UI state and device-only work (mic/speech, Keychain, push decryption; desktop main process: host service, SSH, updates). A client that needs something the host lacks gets a new host method, never its own copy: [ownership rules](docs/architecture/overview.md#host-owns-the-logic).
- 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).
@@ -40,7 +41,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess
## Cross-platform UI changes
-- 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, Linux and Windows), and terminal UI (`host/src/tui/`). This applies in every direction.
+- 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/`), Android (`apps/android/app/`), desktop (`apps/desktop/src/renderer/`, macOS, Linux and Windows), 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.
@@ -60,7 +61,7 @@ Keep only the latest build: in this checkout, Apple builds go to `build/dd` only
## End-to-end test every change
-After every change, test it end to end on the real apps, not just builds and unit tests: install the new build (old one stopped first) and walk through the changed flow. Drive the desktop app with Computer Use, and the iPhone app on an iOS Simulator through Device Hub (Xcode's `DeviceHub.app`). Report any check that could not run and why.
+After every change, test it end to end on the real apps, not just builds and unit tests: install the new build (old one stopped first) and walk through the changed flow. Drive the desktop app with Computer Use, the iPhone app on an iOS Simulator through Device Hub (Xcode's `DeviceHub.app`), and the Android app on an emulator (`adb`). Report any check that could not run and why.
- **Minimal e2e** (default): only the platform of the computer you test on (on the Mac: macOS).
- **Full e2e** (large changes: platform code, packaging, the desktop main process; or when asked): macOS, Linux (Lima `codync-linux`) and Windows (UTM, [Windows testing](docs/guides/windows-testing.md)). A platform whose VM isn't installed is skipped and reported, not set up.
- **Desktop build to use**: develop and e2e with `npm run dev` in `apps/desktop` (renderer reloads on save, restart it after `src/main` or preload changes; nothing packaged or signed). After a host change run `node tools/native-host.mjs dev` there first: `npm run dev` prefers that build over `host/target/debug`. Package `npm run dist:mac:dev` (about 45 s) only for what an unpackaged run lacks: the bundled host install, Codync Screen / computer use, system permissions. `dist:*:main` (universal, timestamped, minutes) only to check the production app.
diff --git a/apps/android/.gitignore b/apps/android/.gitignore
new file mode 100644
index 00000000..74691b84
--- /dev/null
+++ b/apps/android/.gitignore
@@ -0,0 +1,11 @@
+.gradle/
+.kotlin/
+**/build/
+local.properties
+codync.local.properties
+**/google-services.json
+*.jks
+*.keystore
+captures/
+.idea/
+
diff --git a/apps/android/README.md b/apps/android/README.md
new file mode 100644
index 00000000..44559c82
--- /dev/null
+++ b/apps/android/README.md
@@ -0,0 +1,177 @@
+# Codync Android
+
+A native Kotlin/Compose phone client using the existing host's encrypted channel
+and account APIs. It follows the iPhone app screen for screen (layout, wording,
+motion and the Liquid Glass look), built from the iOS sources in
+`apps/ios/Views` and `apps/ios/Kit/Sources/CodyncUI`. What's still missing is in the
+[parity and acceptance checklist](../../docs/plans/android-app.md).
+
+## Build
+
+Use JDK 21, Android SDK 37 and Build Tools 37.0.0. Set `JAVA_HOME` and
+`ANDROID_HOME`, or set `sdk.dir` in ignored `local.properties`.
+
+```sh
+cd apps/android
+./gradlew :core:test :app:testDebugUnitTest :app:assembleDebug :app:lintDebug
+./gradlew :app:assembleRelease
+adb install -r app/build/outputs/apk/debug/app-debug.apk
+```
+
+Stop the old app before rebuilding. Upgrade with `adb install -r`, using the
+original package and signing key; retain device data and identity. Release APKs
+are unsigned until distribution signing is configured. The checksum-pinned
+Gradle wrapper is checked in. `versionName` follows `apps/project.yml`;
+Android's `versionCode` is independent. Feature PRs do not bump product versions.
+
+## Account and push configuration
+
+A clean checkout builds `com.pokai.Codync.android.dev` (Codync Dev) or
+`com.pokai.Codync.android` (Codync). Debug/release read their account configuration from
+`apps/shared/Config/dev.plist` and `main.plist`. The default push relay comes from
+`CodyncKit/Client/SharedStore.swift`.
+
+Firebase client configuration is deployment-specific and excluded from Git.
+Without it the app builds, pairs and chats; Account and State explain that push
+is unavailable. It does not request notification permission or schedule FCM
+registration in that configuration. Foreground task status remains available.
+
+For a private deployment, create ignored `apps/android/codync.local.properties`.
+Override cloud, Clerk and push relay **together**; partial tuples fail the build.
+Command-line Gradle properties take precedence over this file.
+
+```properties
+codyncApplicationId=com.example.codync
+codyncAppName=Codync Local
+codyncCloudUrl=https://cloud.example.com
+codyncClerkPublishableKey=YOUR_MATCHING_CLERK_PUBLISHABLE_KEY
+codyncPushRelayUrl=https://push.example.com
+codyncGoogleServicesFile=/absolute/path/to/google-services.json
+```
+
+The Firebase client file must contain the final package names, including `.dev`
+for debug. Its matching service account belongs only in the push Worker's
+`FCM_SERVICE_ACCOUNT` secret, never in the app. Before installing a private APK,
+check its generated `BuildConfig`, package, Firebase project and certificate
+against the saved deployment configuration. Compilation alone does not verify
+which backend the app will use.
+
+## Pair and use
+
+Run `codync-host pair` on the computer and scan its code or paste the resulting
+`codync://pair` link (`codync-dev://pair` for Codync Dev, which pairs only with a
+development host). Setup shows the Mac and Linux install paths, as on iOS. Pairing links
+and one-time codes remain in memory. Account login discovers computers; each
+host must still approve access.
+
+This increment supports **one paired computer per account context**. Remove the
+current pairing in Computers & settings before pairing another. Multiple-computer
+support is tracked in the checklist. Accounts have separate device keys, mirrors,
+files, image caches and composer drafts.
+
+The roster shows activity, previews, unread counts, groups and pin/hide actions;
+touch and hold a bot, then move it, to reorder (the order syncs through the host). Cached bots remain readable offline and are labeled as saved. An
+unreachable computer is distinguished from an empty online roster. Chat supports
+final replies, Markdown/code, permissions, reactions, threads, history and Full
+conversation.
+
+Text and private attachment drafts survive process death separately for each bot
+and thread. Sends retain their nonce through durable queue commit and retry.
+Uncertain sends require explicit retry with the same ID. Text can wait in the
+encrypted relay mailbox; files require a live computer and are unavailable in
+groups. Files are capped at 100 MiB each and uploaded in 384 KiB chunks. Sharing
+uses a temporary copy rather than exposing the private cache.
+
+## Ownership and storage
+
+- `app`: Compose screens, Android lifecycle, Keystore-wrapped identity,
+ account-scoped storage, files, notifications and widgets.
+- `core`: JVM models, crypto, pairing, RPC and transport. The host retains bot,
+ agent, memory, routine, connector and other product logic.
+- `design`: Codync's design system on Android, mirroring CodyncUI: `Palette`,
+ `Type` (Inter, since SF Pro ships only on Apple platforms), `Motion`, glass
+ (`Glass.kt`, Kyant backdrop: blur, lens refraction and highlight standing in for
+ Liquid Glass), sheets, menus, dialogs, controls and avatars. `Symbol("sf.name")`
+ draws the Material Symbols Rounded stand-in for each SF Symbol the iOS app names
+ (`python3 tools/symbols.py` regenerates them; SF Symbols may not ship on Android).
+ Screens use these components, never Material widgets beyond `Text`.
+
+Ed25519/X25519 seeds use Android Keystore AES-GCM wrapping; no global crypto
+provider is replaced. Local data is excluded from backup and device transfer.
+The mirror commits updates, send reconciliation and the event cursor together.
+Context retirement joins writers before changing identity or closing databases.
+A changed host identity produces an error rather than silently trusting new keys.
+
+Direct HTTP/WebSocket connections use Codync's encrypted channel. Cloud URLs
+require HTTPS. Minimum API is 29 and target API is 36; declared minimums do not
+establish device acceptance. Targeting API 37 requires local-network permission
+work.
+
+## Validation
+
+```sh
+./gradlew :app:assembleDebugAndroidTest
+ANDROID_SERIAL=emulator-5580 ./gradlew :app:connectedDebugAndroidTest
+```
+
+Use a disposable emulator/application for ordinary instrumentation: it includes
+local reset and credential fixtures. Do not run it against a personal phone's
+saved accounts. Mutating live suites require `fixtureComputerId` matching an
+isolated fake-agent host. Shared vectors come from
+[remote-relay-vectors.json](../../docs/reference/fixtures/remote-relay-vectors.json).
+
+`LiveChatTest` uses `liveHost=true` and a bot named `Android chat acceptance`
+running [fake_agent.py](../../host/tests/fake_agent.py). `LiveThreadTest` exercises
+replies. `LiveDraftTest` uses `draftPhase=prepare` and `restore` with an OS process
+stop between phases. File acceptance verifies a multi-chunk round trip byte for
+byte. `LiveRosterTest` offers separately opted-in read-only inspection of an
+existing connection; it is not the ordinary reset suite.
+
+The emulator-only `-PcodyncReleaseTests=true` variant signs an R8 acceptance build
+with the debug key. Ordinary release APKs remain unsigned. Physical camera,
+keyboard/TalkBack, provider login, background push, voice and release acceptance
+are separate [checklist](../../docs/plans/android-app.md) gates.
+
+## Dependencies and assets
+
+Versions are pinned in [libs.versions.toml](gradle/libs.versions.toml). Terminal
+packages, hashes and MIT notices are in
+[vendor-manifest.json](app/src/main/assets/terminal/vendor-manifest.json).
+`python3 tools/vendor-terminal.py` regenerates them from integrity-checked npm
+archives using pinned esbuild. The terminal exposes only a constrained bridge
+and explicit HTTP links. Vosk/JNA and the checksum-verified English model have
+notices in [voice-manifest.json](app/src/main/assets/licenses/voice-manifest.json).
+That speech prototype does not establish full voice parity.
+
+AndroidX, Compose, CameraX, Glance, WorkManager, Firebase and desugaring artifacts
+come from Google Maven. Other dependencies use the configured repositories.
+AndroidX native libraries, Vosk and JNA are upstream artifacts; no custom native
+crypto or camera library is introduced. WebRTC artifact selection remains open.
+
+| Dependency | Version | Source/license and role |
+| --- | --- | --- |
+| Gradle | 9.6.0 | [Gradle](https://gradle.org/releases/), Apache-2.0; checksum-pinned wrapper |
+| Android Gradle plugin | 9.4.1 | [Compatibility](https://developer.android.com/build/releases/agp-9-4-0-release-notes), Apache-2.0; SDK 36 build |
+| Kotlin and Compose compiler | 2.4.20 | [Kotlin](https://kotlinlang.org/docs/releases.html), Apache-2.0 |
+| Compose BOM | 2026.09.00 | [AndroidX](https://developer.android.com/develop/ui/compose/bom/bom-mapping), Apache-2.0; UI components |
+| AndroidX Activity / Lifecycle | 1.12.2 / 2.10.0 | [AndroidX](https://developer.android.com/jetpack/androidx/releases), Apache-2.0; platform lifecycle |
+| Coroutines / serialization | 1.10.2 / 1.9.0 | [Kotlin libraries](https://github.com/Kotlin), Apache-2.0; concurrency and JSON |
+| OkHttp | 4.12.0 | [Square](https://square.github.io/okhttp/), Apache-2.0; WebSockets and test server |
+| Bouncy Castle | 1.86 | [BC Java](https://www.bouncycastle.org/download/bouncy-castle-java/), [BC license](https://www.bouncycastle.org/licence.html); lightweight Ed25519/X25519/ChaCha20-Poly1305 |
+| JUnit / AndroidX Test | 4.13.2 / runner 1.7.0 / ext 1.3.0 | [JUnit](https://junit.org/junit4/), EPL-1.0; [AndroidX Test](https://developer.android.com/training/testing), Apache-2.0 |
+| CommonMark and GFM extensions | 0.30.0 | [CommonMark Java](https://github.com/commonmark/commonmark-java), BSD-2-Clause; selectable Markdown, tables and strikethrough |
+| Coil | 3.4.0 | [Coil](https://github.com/coil-kt/coil/releases/tag/3.4.0), Apache-2.0; bounded image loading and caching |
+| Java API desugaring | 2.1.5 | [Android desugaring](https://developer.android.com/studio/write/java11-default-support-table), GPL-2.0 with Classpath Exception; CommonMark runtime support |
+| Clerk Android | 1.1.11 | [Clerk SDK](https://github.com/clerk/clerk-android), MIT; native account sessions and browser/provider authentication |
+| Firebase BOM / Google Services plugin | 34.19.0 / 4.5.0 | [Firebase Android](https://firebase.google.com/support/release-notes/android), Apache-2.0; FID registration and data-only FCM delivery |
+| WorkManager | 2.12.0 | [AndroidX Work](https://developer.android.com/jetpack/androidx/releases/work), Apache-2.0; bounded background registration retries |
+| Glance | 1.2.0 | [AndroidX Glance](https://developer.android.com/jetpack/androidx/releases/glance), Apache-2.0; responsive native app widgets |
+| CameraX | 1.6.2 | [AndroidX Camera](https://developer.android.com/jetpack/androidx/releases/camera), Apache-2.0; lifecycle-bound preview/analysis, minimum API 23, optional camera permission |
+| ZXing Core | 3.5.4 | [ZXing releases](https://github.com/zxing/zxing/releases/tag/zxing-3.5.4), Apache-2.0; bundled Java QR decoding without a network/model download |
+| xterm / fit / web-links | 6.0.0 / 0.11.0 / 0.12.0 | [xterm.js](https://github.com/xtermjs/xterm.js/tree/6.0.0), MIT; bundled terminal rendering and explicit HTTP links, with each license included in the assets |
+| Vosk Android / English model | 0.3.75 / small-en-us-0.15 | [Vosk](https://github.com/alphacep/vosk-api), Apache-2.0; bundled offline recognition and checksum-pinned model |
+| JNA | 5.18.1 | [Java Native Access](https://github.com/java-native-access/jna/tree/5.18.1), Apache-2.0 option with notice; native speech binding |
+| Kyant backdrop / shapes | 2.0.1 / 1.2.1 | [AndroidLiquidGlass](https://github.com/Kyant0/AndroidLiquidGlass), Apache-2.0; glass blur, lens and highlight (RenderEffect API 31+, RuntimeShader API 33+), continuous-corner shapes |
+| Inter | 4.x variable | [Inter](https://rsms.me/inter/), OFL-1.1; the app's type face in `design/src/main/res/font` |
+| Material Symbols Rounded | upstream SVGs | [Material Design Icons](https://github.com/google/material-design-icons), Apache-2.0; vector stand-ins for SF Symbols |
+| esbuild (asset regeneration only) | 0.28.2 | [esbuild](https://esbuild.github.io/api/#target), MIT; transforms newer syntax for older WebViews, never included as an APK binary |
diff --git a/apps/android/app/build.gradle.kts b/apps/android/app/build.gradle.kts
new file mode 100644
index 00000000..ec71b412
--- /dev/null
+++ b/apps/android/app/build.gradle.kts
@@ -0,0 +1,185 @@
+import java.security.MessageDigest
+import java.util.zip.ZipFile
+import java.util.Properties
+
+plugins {
+ alias(libs.plugins.android.application)
+ alias(libs.plugins.kotlin.serialization)
+ alias(libs.plugins.kotlin.compose)
+ alias(libs.plugins.google.services) apply false
+}
+
+// Private deployments opt in as one tuple; never silently mix account providers.
+val deployment = Properties().apply {
+ val local = rootProject.file("codync.local.properties")
+ if (local.exists()) local.inputStream().use(::load)
+}
+fun deploymentValue(name: String): String? = providers.gradleProperty(name).orNull ?: deployment.getProperty(name)
+val accountOverrides = listOf("codyncCloudUrl", "codyncClerkPublishableKey", "codyncPushRelayUrl")
+check(accountOverrides.none { deploymentValue(it) != null } || accountOverrides.all { deploymentValue(it) != null }) {
+ "Override cloud, Clerk and push relay together in codync.local.properties or Gradle properties."
+}
+fun accountValue(variant: String, key: String): String {
+ val plist = rootProject.file("../shared/Config/$variant.plist").readText()
+ return requireNotNull(Regex("<key>$key</key>\\s*<string>([^<]*)</string>").find(plist)?.groupValues?.get(1)) {
+ "Missing $key in the shared $variant account configuration."
+ }
+}
+val upstreamRelay = rootProject.file("../ios/Kit/Sources/CodyncKit/Client/SharedStore.swift").readLines()
+ .first { it.contains("static let relayURL =") }.substringAfter('"').substringBefore('"')
+val firebaseConfig = deploymentValue("codyncGoogleServicesFile")?.takeIf(String::isNotBlank)?.let(::file)
+check(firebaseConfig == null || firebaseConfig.isFile) { "The configured Firebase file does not exist." }
+if (firebaseConfig != null) apply(plugin = "com.google.gms.google-services")
+
+val productVersion = rootProject.file("../project.yml").readLines()
+ .first { it.trimStart().startsWith("MARKETING_VERSION:") }
+ .substringAfter(':').trim()
+// Explicit, emulator-only R8 acceptance; ordinary release artifacts stay unsigned.
+val releaseTests = providers.gradleProperty("codyncReleaseTests").map(String::toBoolean).getOrElse(false)
+
+val voiceModel = configurations.create("voiceModel") {
+ isCanBeConsumed = false
+ isCanBeResolved = true
+}
+val voiceAssets = layout.buildDirectory.dir("generated/voiceAssets")
+@CacheableTask
+abstract class VoiceModelAssets : DefaultTask() {
+ @get:InputFiles @get:PathSensitive(PathSensitivity.NONE) abstract val archives: ConfigurableFileCollection
+ @get:Input abstract val expectedHash: Property<String>
+ @get:OutputDirectory abstract val assetDirectory: DirectoryProperty
+ @TaskAction fun generate() {
+ val archive = archives.singleFile
+ val digest = MessageDigest.getInstance("SHA-256")
+ archive.inputStream().use { input ->
+ val buffer = ByteArray(1024 * 1024)
+ while (true) { val count = input.read(buffer); if (count < 0) break; digest.update(buffer, 0, count) }
+ }
+ check(digest.digest().joinToString("") { "%02x".format(it) } == expectedHash.get()) {
+ "The pinned offline voice model's integrity check failed."
+ }
+ val root = assetDirectory.get().asFile
+ root.deleteRecursively()
+ val destination = root.resolve("voice").toPath().normalize()
+ ZipFile(archive).use { zip ->
+ for (entry in zip.entries()) {
+ val output = destination.resolve(entry.name).normalize()
+ check(output.startsWith(destination)) { "Invalid voice model archive path." }
+ if (entry.isDirectory) output.toFile().mkdirs()
+ else {
+ output.parent.toFile().mkdirs()
+ zip.getInputStream(entry).use { input -> output.toFile().outputStream().use { input.copyTo(it) } }
+ }
+ }
+ }
+ }
+}
+val prepareVoiceModel = tasks.register<VoiceModelAssets>("prepareVoiceModel") {
+ archives.from(voiceModel)
+ expectedHash.set("30f26242c4eb449f948e42cb302dd7a686cb29a3423a8367f99ff41780942498")
+ assetDirectory.set(voiceAssets)
+}
+
+fun javaString(value: String): String = "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"")
+ .replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t") + "\""
+
+android {
+ namespace = "com.codync.android"
+ compileSdk = 37
+ defaultConfig {
+ applicationId = deploymentValue("codyncApplicationId") ?: "com.pokai.Codync.android"
+ minSdk = 29
+ targetSdk = 36
+ versionCode = 1
+ versionName = productVersion
+ testInstrumentationRunner = if (releaseTests) "com.codync.android.VoiceReleaseRunner" else "androidx.test.runner.AndroidJUnitRunner"
+ buildConfigField("String", "PUSH_RELAY_URL", javaString(deploymentValue("codyncPushRelayUrl") ?: upstreamRelay))
+ buildConfigField("boolean", "PUSH_CONFIGURED", (firebaseConfig != null).toString())
+ }
+ buildTypes {
+ debug {
+ applicationIdSuffix = ".dev"
+ versionNameSuffix = "-dev"
+ resValue("string", "app_name", deploymentValue("codyncAppName") ?: "Codync Dev")
+ manifestPlaceholders["urlScheme"] = "codync-dev"
+ buildConfigField("String", "URL_SCHEME", "\"codync-dev\"")
+ buildConfigField("String", "CLOUD_URL", javaString(deploymentValue("codyncCloudUrl") ?: accountValue("dev", "cloudURL")))
+ buildConfigField("String", "CLERK_PUBLISHABLE_KEY", javaString(deploymentValue("codyncClerkPublishableKey") ?: accountValue("dev", "clerkPublishableKey")))
+ }
+ release {
+ resValue("string", "app_name", deploymentValue("codyncAppName") ?: "Codync")
+ manifestPlaceholders["urlScheme"] = "codync"
+ buildConfigField("String", "URL_SCHEME", "\"codync\"")
+ buildConfigField("String", "CLOUD_URL", javaString(deploymentValue("codyncCloudUrl") ?: accountValue("main", "cloudURL")))
+ buildConfigField("String", "CLERK_PUBLISHABLE_KEY", javaString(deploymentValue("codyncClerkPublishableKey") ?: accountValue("main", "clerkPublishableKey")))
+ isMinifyEnabled = true
+ proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
+ }
+ create("releaseAcceptance") {
+ initWith(getByName("release"))
+ applicationIdSuffix = ".dev"
+ versionNameSuffix = "-r8-test"
+ signingConfig = signingConfigs.getByName("debug")
+ matchingFallbacks += "release"
+ proguardFiles("release-acceptance.pro")
+ }
+ }
+ if (releaseTests) testBuildType = "releaseAcceptance"
+ buildFeatures.compose = true
+ buildFeatures.buildConfig = true
+ buildFeatures.resValues = true
+ sourceSets.getByName("androidTest").assets.srcDir(rootProject.file("../../docs/reference/fixtures"))
+ compileOptions {
+ isCoreLibraryDesugaringEnabled = true
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+}
+androidComponents.beforeVariants(androidComponents.selector().withBuildType("releaseAcceptance")) { it.enable = releaseTests }
+androidComponents.onVariants { variant ->
+ variant.sources.assets?.addGeneratedSourceDirectory(prepareVoiceModel) { task -> task.assetDirectory }
+}
+afterEvaluate {
+ if (firebaseConfig != null) tasks.withType<com.google.gms.googleservices.GoogleServicesTask>().configureEach {
+ googleServicesJsonFiles.set(listOf(firebaseConfig))
+ }
+}
+kotlin.compilerOptions.jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
+
+dependencies {
+ add(voiceModel.name, "com.alphacephei.models:vosk-model-small-en-us:0.15@zip")
+ implementation(libs.vosk) { exclude(group = "net.java.dev.jna", module = "jna") }
+ implementation("net.java.dev.jna:jna:${libs.versions.jna.get()}@aar")
+ coreLibraryDesugaring(libs.desugar)
+ implementation(libs.commonmark)
+ implementation(libs.commonmark.tables)
+ implementation(libs.commonmark.strikethrough)
+ implementation(libs.coil.compose)
+ implementation(libs.coil.network)
+ implementation(libs.clerk)
+ implementation(platform(libs.firebase.bom))
+ implementation(libs.firebase.messaging)
+ implementation(libs.work)
+ implementation(libs.glance)
+ implementation(libs.camera.core)
+ implementation(libs.camera.camera2)
+ implementation(libs.camera.lifecycle)
+ implementation(libs.camera.view)
+ implementation(project(":core"))
+ implementation(project(":design"))
+ implementation(platform(libs.compose.bom))
+ implementation(libs.compose.ui)
+ implementation(libs.compose.foundation)
+ implementation(libs.compose.material3)
+ implementation(libs.activity.compose)
+ implementation(libs.lifecycle.compose)
+ implementation(libs.lifecycle.viewmodel)
+ implementation(libs.coroutines.android)
+ implementation(libs.serialization.json)
+ debugImplementation(libs.compose.tooling)
+ debugImplementation(libs.compose.test.manifest)
+ testImplementation(libs.junit)
+ androidTestImplementation(platform(libs.compose.bom))
+ androidTestImplementation(libs.compose.test)
+ androidTestImplementation(libs.androidx.test.runner)
+ androidTestImplementation(libs.androidx.test.junit)
+}
diff --git a/apps/android/app/proguard-rules.pro b/apps/android/app/proguard-rules.pro
new file mode 100644
index 00000000..f2097e49
--- /dev/null
+++ b/apps/android/app/proguard-rules.pro
@@ -0,0 +1,16 @@
+# Bouncy Castle is used through its lightweight APIs; no provider reflection.
+-dontwarn javax.naming.**
+-dontwarn java.lang.invoke.**
+
+# Vosk binds these native methods by their names through JNA.
+-keep class org.vosk.LibVosk { *; }
+-keep class com.sun.jna.** { *; }
+# JNA creates a NativeMapped pointer argument through its public constructor.
+-keepclassmembers class * extends com.sun.jna.PointerType { public <init>(); }
+-dontwarn java.awt.**
+
+# Glance persists widget class identity to distinguish receivers across upgrades.
+# Keep each class/constructor distinct while optimizing its implementation.
+-keep,allowoptimization class com.codync.android.** extends androidx.glance.appwidget.GlanceAppWidget {
+ public <init>();
+}
diff --git a/apps/android/app/release-acceptance.pro b/apps/android/app/release-acceptance.pro
new file mode 100644
index 00000000..dc978787
--- /dev/null
+++ b/apps/android/app/release-acceptance.pro
@@ -0,0 +1,4 @@
+# Framework instrumentation calls this test-variant boundary by reflection.
+-keep class com.codync.android.ReleaseWidgetSmoke {
+ public static void run(android.app.Instrumentation);
+}
diff --git a/apps/android/app/src/androidTest/assets/voice-test.wav b/apps/android/app/src/androidTest/assets/voice-test.wav
new file mode 100644
index 00000000..c41144a2
Binary files /dev/null and b/apps/android/app/src/androidTest/assets/voice-test.wav differ
diff --git a/apps/android/app/src/androidTest/java/com/codync/android/VoiceReleaseRunner.java b/apps/android/app/src/androidTest/java/com/codync/android/VoiceReleaseRunner.java
new file mode 100644
index 00000000..b1a8104e
--- /dev/null
+++ b/apps/android/app/src/androidTest/java/com/codync/android/VoiceReleaseRunner.java
@@ -0,0 +1,91 @@
+package com.codync.android;
+
+import android.app.Activity;
+import android.app.Instrumentation;
+import android.content.res.AssetManager;
+import android.os.Build;
+import android.os.Bundle;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import com.sun.jna.Pointer;
+import org.json.JSONObject;
+import org.vosk.LibVosk;
+import org.vosk.Model;
+
+/** A platform-only runner exercises the actual R8 native binding without test-library keep rules. */
+public final class VoiceReleaseRunner extends Instrumentation {
+ @Override public void onCreate(Bundle arguments) { super.onCreate(arguments); start(); }
+ @Override public void onStart() {
+ Bundle result = new Bundle();
+ File temporary = new File(getTargetContext().getCacheDir(), "release-voice-smoke");
+ try {
+ if (!Build.PRODUCT.contains("sdk")) throw new IllegalStateException("Use an emulator for release acceptance");
+ temporary.mkdirs();
+ copy(getTargetContext().getAssets(), "voice/vosk-model-small-en-us-0.15", temporary);
+ byte[] wav;
+ try (InputStream input = getContext().getAssets().open("voice-test.wav")) {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ byte[] buffer = new byte[8192]; int count;
+ while ((count = input.read(buffer)) != -1) bytes.write(buffer, 0, count);
+ wav = bytes.toByteArray();
+ }
+ ByteBuffer header = ByteBuffer.wrap(wav).order(ByteOrder.LITTLE_ENDIAN);
+ byte[] pcm = null;
+ for (int offset = 12; offset + 8 <= wav.length;) {
+ int length = header.getInt(offset + 4);
+ if (length < 0 || length > wav.length - offset - 8) throw new IllegalStateException("Invalid speech fixture");
+ if (new String(wav, offset, 4, StandardCharsets.US_ASCII).equals("data")) pcm = Arrays.copyOfRange(wav, offset + 8, offset + 8 + length);
+ offset += 8 + length + length % 2;
+ }
+ if (pcm == null) throw new IllegalStateException("Missing fixture audio");
+ LibVosk.vosk_set_log_level(-1);
+ StringBuilder heard = new StringBuilder();
+ Model model = new Model();
+ model.setPointer(LibVosk.vosk_model_new(temporary.getAbsolutePath()));
+ if (model.getPointer() == null) throw new IllegalStateException("The minified native model did not load");
+ Pointer recognizer = null;
+ try {
+ recognizer = LibVosk.vosk_recognizer_new(model, 16000f);
+ if (recognizer == null) throw new IllegalStateException("The minified native recognizer did not load");
+ for (int position = 0; position < pcm.length; position += 4096) {
+ byte[] chunk = Arrays.copyOfRange(pcm, position, Math.min(position + 4096, pcm.length));
+ if (LibVosk.vosk_recognizer_accept_waveform(recognizer, chunk, chunk.length)) heard.append(new JSONObject(LibVosk.vosk_recognizer_result(recognizer)).optString("text")).append(' ');
+ }
+ heard.append(new JSONObject(LibVosk.vosk_recognizer_final_result(recognizer)).optString("text"));
+ } finally {
+ if (recognizer != null) LibVosk.vosk_recognizer_free(recognizer);
+ LibVosk.vosk_model_free(model.getPointer());
+ }
+ if (!heard.toString().contains("one zero zero zero one") || !heard.toString().contains("zero one eight zero three")) throw new AssertionError("Minified speech recognition did not match the fixture");
+ Class<?> widgets = Class.forName("com.codync.android.ReleaseWidgetSmoke", true, getTargetContext().getClassLoader());
+ widgets.getMethod("run", Instrumentation.class).invoke(null, this);
+ result.putString("stream", "\nOK (2 tests)\n");
+ finish(Activity.RESULT_OK, result);
+ } catch (Throwable error) {
+ Throwable detail = error instanceof java.lang.reflect.InvocationTargetException && error.getCause() != null ? error.getCause() : error;
+ result.putString("stream", "\nFAILURES!!!\n" + detail.getClass().getSimpleName() + ": " + detail.getMessage() + "\n");
+ finish(Activity.RESULT_CANCELED, result);
+ } finally { erase(temporary); }
+ }
+ private void copy(AssetManager assets, String source, File target) throws Exception {
+ for (String child : assets.list(source)) {
+ String path = source + "/" + child; File output = new File(target, child);
+ if (assets.list(path).length > 0) { output.mkdirs(); copy(assets, path, output); }
+ else try (InputStream input = assets.open(path); FileOutputStream destination = new FileOutputStream(output)) {
+ byte[] buffer = new byte[8192]; int count;
+ while ((count = input.read(buffer)) != -1) destination.write(buffer, 0, count);
+ }
+ }
+ }
+ private void erase(File file) {
+ File[] children = file.listFiles();
+ if (children != null) for (File child : children) erase(child);
+ file.delete();
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt
new file mode 100644
index 00000000..069c91d3
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt
@@ -0,0 +1,165 @@
+package com.codync.android
+
+import android.graphics.Bitmap
+import android.os.Build
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.ui.graphics.asAndroidBitmap
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.lifecycle.viewmodel.compose.viewModel
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import com.codync.android.design.LocalDismissModal
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import java.io.File
+
+/** The account sheet and Computers & settings. Read-only: no test confirms a sign-out, route, removal or reset. */
+class AccountScreenTest {
+ @get:Rule val compose = createComposeRule()
+ private val first = SavedAccount("first", "first-session", "[email protected]", null)
+ private val second = SavedAccount("second", "second-session", "[email protected]", null)
+ private val account = AccountState(ready = true, configured = true, userId = first.userId,
+ accounts = listOf(first, second), multiple = true)
+ private val computer = Computer("paired", "Fixture computer", "fixture-key")
+ private fun fixture(accountState: AccountState = account) = AppState(loading = false,
+ setupComplete = true, account = accountState, contextId = "profile-fixture")
+
+ @Before fun isolatedEmulatorOnly() { assumeTrue(Build.PRODUCT.startsWith("sdk")) }
+
+ @Test fun signedInOverviewKeepsTheProfileAboveItsNavigation() {
+ var scanned = false; var settings = false; var closed = false
+ compose.setContent { Hosted { CompositionLocalProvider(LocalDismissModal provides { closed = true }) {
+ AccountSwitcherView(fixture(), viewModel(), { settings = true }) { scanned = true }
+ } } }
+ compose.onNodeWithText("Account").assertIsDisplayed()
+ val scan = compose.onNodeWithText("Scan a computer's code").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ val identity = compose.onNodeWithText(first.email).assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ val computers = compose.onNodeWithText("Computers").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ assertTrue(scan.bottom < identity.top)
+ assertTrue(identity.bottom < computers.top)
+ compose.onNodeWithContentDescription(first.email).assertIsSelected().assertIsNotEnabled()
+ compose.onNodeWithContentDescription(second.email).assertIsNotSelected().assertIsEnabled()
+ compose.onNodeWithContentDescription("Add account").assertIsDisplayed()
+ compose.onNodeWithText("Sign out").assertIsDisplayed()
+ compose.onNodeWithText("Continue with Google").assertDoesNotExist()
+ compose.onNodeWithText("Start over").assertDoesNotExist()
+ snapshot("signed-in")
+ compose.onNodeWithText("Scan a computer's code").performClick()
+ compose.onNodeWithText("Computers").performClick()
+ compose.onNodeWithContentDescription("Close").performClick()
+ assertTrue(scanned && settings && closed)
+ }
+
+ @Test fun theAddButtonRevealsProvidersOnlyOnDemandAndASessionChangeLocksTheSheet() {
+ val state = mutableStateOf(fixture())
+ compose.setContent { Hosted { AccountSwitcherView(state.value, viewModel(), {}, {}) } }
+ compose.onNodeWithContentDescription("Add account").performClick()
+ compose.onNodeWithText("Continue with Apple").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithText("Continue with Google").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithContentDescription("Add account").performScrollTo().performClick()
+ compose.onNodeWithText("Continue with Google").assertDoesNotExist()
+ compose.runOnUiThread { state.value = state.value.copy(busy = setOf("session")) }
+ compose.onNodeWithContentDescription("Signing in").assertIsDisplayed()
+ compose.onNodeWithContentDescription(second.email).assertIsNotEnabled()
+ compose.onNodeWithContentDescription("Add account").assertIsNotEnabled()
+ compose.onNodeWithText("Sign out").assertIsNotEnabled()
+ }
+
+ @Test fun signedOutProvidersAndUnconfiguredPairingRemainAvailable() {
+ val state = mutableStateOf(fixture(AccountState(ready = true, configured = true)))
+ compose.setContent { Hosted { AccountSwitcherView(state.value, viewModel(), {}, {}) } }
+ val apple = compose.onNodeWithText("Continue with Apple").assertIsDisplayed().assertIsEnabled().fetchSemanticsNode().boundsInRoot
+ val google = compose.onNodeWithText("Continue with Google").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ assertTrue(apple.bottom <= google.top)
+ assertEquals(apple.left, google.left, 1f)
+ assertEquals(apple.right, google.right, 1f)
+ compose.onNodeWithText("Other sign-in options").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithText("Sign out").assertDoesNotExist()
+ compose.runOnUiThread { state.value = state.value.copy(account = state.value.account.copy(ready = false, error = "Couldn't restore sign-in.")) }
+ compose.onNodeWithText("Continue with Apple").assertIsNotEnabled()
+ compose.onNodeWithText("Continue with Google").assertIsNotEnabled()
+ compose.onNodeWithText("Couldn't restore sign-in.").performScrollTo().assertIsDisplayed()
+ compose.runOnUiThread { state.value = state.value.copy(account = AccountState(ready = true, configured = false)) }
+ compose.onNodeWithText("QR pairing only in this build").assertIsDisplayed()
+ compose.onNodeWithText("Continue with Apple").assertDoesNotExist()
+ compose.onNodeWithText("Scan a computer's code").assertIsDisplayed()
+ compose.onNodeWithText("Computers").assertIsDisplayed()
+ snapshot("pairing-only")
+ }
+
+ @Test fun signOutAsksFirstAndCancelKeepsTheAccount() {
+ compose.setContent { Hosted { AccountSwitcherView(fixture(), viewModel(), {}, {}) } }
+ compose.onNodeWithText("Sign out").performClick()
+ compose.onNodeWithText("Sign out of ${first.email}?").assertIsDisplayed()
+ compose.onNodeWithText("This phone forgets the account's computers. Your bots stay on them.").assertIsDisplayed()
+ compose.onNodeWithText("Cancel").performClick()
+ compose.onNodeWithText("Sign out of ${first.email}?").assertDoesNotExist()
+ compose.onNodeWithText(first.email).assertIsDisplayed()
+ }
+
+ @Test fun computerSettingsKeepRoutesNotificationsAndResetBehindConfirmations() {
+ val state = fixture().copy(computers = listOf(computer), connection = LinkState.Ready(HostRoute.Direct),
+ bots = listOf(Bot("hidden", "Hidden scout", hidden = true)))
+ var paired = 0; var popped = 0; var extensions = 0
+ compose.setContent { Hosted { SettingsView(state, viewModel(), { popped++ }, { paired++ }, {}) { extensions++ } } }
+ compose.onNodeWithText("Computers & settings").assertIsDisplayed()
+ compose.onAllNodesWithText(computer.name).assertCountEquals(1)
+ compose.onNodeWithText("1 bot · Wi-Fi/Tailscale").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Extensions").performClick()
+ assertEquals(1, extensions)
+ compose.onNodeWithText("Pair a computer").performClick()
+ assertEquals(1, paired)
+ compose.onNodeWithText("Hidden scout").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithContentDescription("Unhide").assertIsDisplayed()
+ if (BuildConfig.PUSH_CONFIGURED) compose.onNode(hasText("Push notifications") and isToggleable()).performScrollTo().assertIsDisplayed()
+ else compose.onNodeWithText("Push isn't set up in this build. Bots and chats still update while Codync is open.").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithText("App version").performScrollTo().assertIsDisplayed()
+ snapshot("computers")
+ compose.onNodeWithText("Start over").performScrollTo().performClick()
+ compose.onNodeWithText("Start over?").assertIsDisplayed()
+ compose.onNodeWithText("Cancel").performClick()
+ compose.onNodeWithText("Start over?").assertDoesNotExist()
+ compose.onNodeWithText(computer.name).performScrollTo().performTouchInput { longClick() }
+ compose.onNodeWithText("Remove").performClick()
+ compose.onNodeWithText("Remove ${computer.name}?").assertIsDisplayed()
+ compose.onNodeWithText("Cancel").performClick()
+ compose.onNodeWithContentDescription("Connection").performClick()
+ compose.onNodeWithText("Wi-Fi or Tailscale only, never Cloudflare").assertIsDisplayed()
+ compose.onNodeWithText("Auto: Wi-Fi or Tailscale, then Cloudflare").assertIsSelected()
+ }
+
+ @Test fun accountComputersAskForAccessAndAPendingRequestShowsItsCode() {
+ val cloud = CloudComputer("account-computer", "Account computer", "account-key", online = true)
+ val asked = mutableListOf<CloudComputer>()
+ val state = mutableStateOf(fixture().copy(cloudComputers = listOf(cloud)))
+ compose.setContent { Hosted { SettingsView(state.value, viewModel(), null, {}, { asked.add(it) }, {}) } }
+ compose.onNodeWithText("Online · In your account").assertIsDisplayed()
+ compose.onNodeWithText("Ask for access").performClick()
+ assertEquals(listOf(cloud), asked)
+ compose.runOnUiThread { state.value = state.value.copy(access = AccessTicket("request", Long.MAX_VALUE, "123456", cloud.computerId, cloud.signKey)) }
+ compose.onNodeWithText("Waiting for your OK on the computer · 123456").assertIsDisplayed()
+ compose.onNodeWithText("Code").performClick()
+ assertEquals(listOf(cloud, cloud), asked)
+ }
+
+ @Test fun thePendingAccessBannerShowsTheCodeAndCancels() {
+ var cancelled = false
+ compose.setContent { Hosted { AccessBanner(AccessTicket("request", Long.MAX_VALUE, "123456", "computer", "key"), "Fixture computer") { cancelled = true } } }
+ compose.onNodeWithText("Approve on Fixture computer").assertIsDisplayed()
+ compose.onNodeWithText("Code 123 456").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Cancel request").performClick()
+ assertTrue(cancelled)
+ }
+
+ private fun snapshot(name: String) {
+ if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") != "true") return
+ val bitmap = compose.onRoot().captureToImage().asAndroidBitmap()
+ val file = File(InstrumentationRegistry.getInstrumentation().targetContext.cacheDir, "account-$name.png")
+ file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/AgentSettingsScreenTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/AgentSettingsScreenTest.kt
new file mode 100644
index 00000000..889f44e6
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/AgentSettingsScreenTest.kt
@@ -0,0 +1,107 @@
+package com.codync.android
+
+import androidx.compose.foundation.layout.Column
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.*
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createComposeRule
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import org.junit.Assert.*
+import org.junit.Rule
+import org.junit.Test
+import java.util.concurrent.atomic.AtomicBoolean
+
+class AgentSettingsScreenTest {
+ @get:Rule val compose = createComposeRule()
+ private val online = AppState(loading = false, computers = listOf(Computer("fixture", "Fixture computer", "fixture")),
+ actualConnection = LinkState.Ready(HostRoute.Direct))
+ private val model = hasContentDescription("Model:", substring = true)
+
+ @Composable private fun Picker(state: AppState, backend: String, selected: String?, choose: (String?) -> Unit, load: suspend (String) -> AgentModels) =
+ AgentModelPicker(state, load, backend, selected, emptyMap(), false, null, { id, _ -> choose(id) }, {})
+
+ @Test fun hostModelsRetainAnUnknownOverrideAndFoldTheRecommendedDefault() {
+ var selected by mutableStateOf<String?>("old-model")
+ compose.setContent { Hosted { Picker(online, "agent", selected, { selected = it }) {
+ AgentModels(listOf(AgentModel("auto", "Default (recommended)"), AgentModel("host-model", "Host model", "From this agent")))
+ } } }
+ compose.waitUntil { compose.onAllNodes(model).fetchSemanticsNodes().size == 1 }
+ compose.onNodeWithContentDescription("Model: old-model").performClick()
+ compose.onAllNodesWithText("Default (recommended)").assertCountEquals(1)
+ compose.onNodeWithText("Default (recommended)").performClick()
+ assertNull(selected)
+ compose.onNodeWithContentDescription("Model: Default (recommended)").performClick()
+ compose.onNodeWithText("Host model").performClick()
+ assertEquals("host-model", selected)
+ compose.onNodeWithContentDescription("Refresh model list").assertIsDisplayed()
+ }
+
+ @Test fun aLateCancelledModelDiscoveryCannotReplaceAnotherAgentsCatalog() {
+ var backend by mutableStateOf("old")
+ val started = AtomicBoolean(false); val returned = AtomicBoolean(false)
+ compose.setContent { Hosted { Column {
+ TextButton(onClick = { backend = "new" }) { Text("Switch agent") }
+ Picker(online, backend, null, {}) { id ->
+ if (id == "old") withContext(NonCancellable) { started.set(true); delay(600); returned.set(true) }
+ AgentModels(listOf(AgentModel(id, "$id advertised model")))
+ }
+ } } }
+ compose.waitUntil { started.get() }
+ compose.onNodeWithText("Switch agent").performClick()
+ compose.waitUntil { compose.onAllNodes(model).fetchSemanticsNodes().size == 1 }
+ compose.waitUntil(3_000) { returned.get() }
+ compose.onNode(model).performClick()
+ compose.onNodeWithText("new advertised model").assertIsDisplayed()
+ compose.onNodeWithText("old advertised model").assertDoesNotExist()
+ }
+
+ @Test fun anOfflineModelOverrideRemainsEditableWithoutInventingAProviderList() {
+ var selected by mutableStateOf<String?>("my-model")
+ compose.setContent { Hosted { Picker(online.copy(actualConnection = LinkState.Connecting), "agent", selected, { selected = it }) {
+ fail("Offline must not query models"); AgentModels(emptyList())
+ } } }
+ compose.onNodeWithText("Connect to this computer to load its models. You can still enter a model ID.").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Retry model list").assertIsDisplayed()
+ compose.onNode(model).assertDoesNotExist()
+ compose.onNode(hasSetTextAction() and hasText("my-model")).performTextReplacement("saved-model")
+ assertEquals("saved-model", selected)
+ }
+
+ @Test fun hostFolderBrowsingFiltersLocallyDrillsInAndSelectsTheAuthoritativeDirectory() {
+ var chosen: String? = null
+ val requests = mutableListOf<String?>()
+ compose.setContent { Hosted { FolderPicker("/home", true, { path ->
+ requests.add(path)
+ if (path == "/home/Repo") DirListing("/home/Repo", "/home", true, emptyList())
+ else DirListing("/home", "/", false, listOf(DirItem("Repo", "/home/Repo", true), DirItem("Other", "/home/Other")))
+ }) { chosen = it } } }
+ compose.waitUntil { compose.onAllNodesWithText("Repo").fetchSemanticsNodes().size == 1 }
+ compose.onNode(hasSetTextAction()).performTextInput("repo")
+ compose.onNodeWithText("Other").assertDoesNotExist()
+ assertEquals(listOf<String?>("/home"), requests)
+ compose.onNodeWithText("Repo").performClick()
+ compose.waitUntil { compose.onAllNodesWithText("Use “Repo”").fetchSemanticsNodes().size == 1 }
+ assertEquals(listOf<String?>("/home", "/home/Repo"), requests)
+ compose.onNodeWithText("Use “Repo”").performClick()
+ assertEquals("/home/Repo", chosen)
+ compose.onNodeWithContentDescription("Back").performClick()
+ compose.waitUntil { compose.onAllNodesWithText("Other").fetchSemanticsNodes().size == 1 }
+ compose.onNodeWithText("Use “home”").performClick()
+ assertEquals("/home", chosen)
+ }
+
+ @Test fun anUnavailableOrOfflineFolderShowsWhyWithoutOfferingIt() {
+ val online = mutableStateOf(true)
+ var loads = 0
+ compose.setContent { Hosted { FolderPicker("/missing", online.value, { loads++; throw java.io.IOException("This folder no longer exists.") }) {
+ fail("A folder that failed to load can't be chosen")
+ } } }
+ compose.waitUntil { compose.onAllNodesWithText("This folder no longer exists.").fetchSemanticsNodes().size == 1 }
+ compose.onNodeWithText("Use “missing”").assertDoesNotExist()
+ compose.runOnUiThread { online.value = false }
+ compose.onNodeWithText("Connect to this computer to browse its folders.").assertIsDisplayed()
+ assertEquals(1, loads)
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/AttachmentFilesTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/AttachmentFilesTest.kt
new file mode 100644
index 00000000..f7ca3ebc
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/AttachmentFilesTest.kt
@@ -0,0 +1,56 @@
+package com.codync.android
+
+import android.graphics.Bitmap
+import androidx.core.content.FileProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.MAX_FILE_BYTES
+import java.io.File
+import java.io.RandomAccessFile
+import java.util.UUID
+import kotlinx.coroutines.runBlocking
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Test
+
+class AttachmentFilesTest {
+ private val context = InstrumentationRegistry.getInstrumentation().targetContext
+ private val root = File(context.noBackupFilesDir, "files-test-" + UUID.randomUUID()).apply { mkdirs() }
+ private val shared = File(context.cacheDir, "shared-attachments/test-" + UUID.randomUUID()).apply { mkdirs() }
+ private val files = AttachmentFiles(context, root)
+ private fun uri(file: File) = FileProvider.getUriForFile(context, context.packageName + ".files", file)
+ @After fun cleanup() { root.deleteRecursively(); shared.deleteRecursively() }
+
+ @Test fun aPickedFileIsCopiedBeforeTheProviderGrantCanDisappear() = runBlocking {
+ val source = File(shared, "data.txt").apply { writeText("content") }
+ val outgoing = files.import(uri(source))
+ source.delete()
+ assertEquals("data.txt", outgoing.name)
+ assertEquals("content", File(outgoing.path).readText())
+ files.discard(outgoing)
+ assertFalse(File(outgoing.path).exists())
+ }
+
+ @Test fun oversizedProviderFilesAreRejectedBeforeCopying() = runBlocking {
+ val source = File(shared, "too-large.bin")
+ RandomAccessFile(source, "rw").use { it.setLength(MAX_FILE_BYTES + 1) }
+ try { files.import(uri(source)); fail("Expected size validation") }
+ catch (_: IllegalArgumentException) { }
+ assertTrue(File(root, "outgoing").listFiles().orEmpty().isEmpty())
+ }
+
+ @Test fun supportedNonPortableImagesBecomeBoundedJpegFiles() = runBlocking {
+ val source = File(shared, "photo.bmp")
+ // Android detects image format from its bytes; the nonportable name selects preparation.
+ source.outputStream().use { Bitmap.createBitmap(16, 8, Bitmap.Config.ARGB_8888).compress(Bitmap.CompressFormat.PNG, 100, it) }
+ val outgoing = files.import(uri(source))
+ assertEquals("photo.jpg", outgoing.name)
+ val bitmap = AttachmentFiles.thumbnail(File(outgoing.path), 4096)
+ assertEquals(16, bitmap.width); assertEquals(8, bitmap.height)
+ }
+
+ @Test fun fileSharingCannotExposePrivateIdentityOrMirrorStorage() {
+ val private = File(root, "identity").apply { writeText("private") }
+ try { uri(private); fail("Private storage was exposed") }
+ catch (_: IllegalArgumentException) { }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt
new file mode 100644
index 00000000..f4d1eb7f
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt
@@ -0,0 +1,134 @@
+package com.codync.android
+
+import android.graphics.Bitmap
+import android.os.Build
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.graphics.asAndroidBitmap
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.lifecycle.viewmodel.compose.viewModel
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import com.codync.android.design.LocalDismissModal
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import java.io.File
+
+/** Read-only UI fixtures: no test taps Save or Create, so production bots are never changed. */
+class BotEditorTest {
+ @get:Rule val compose = createComposeRule()
+ private val scout = BotDraft(id = "fixture", name = "Scout", avatarShape = "blob", avatarColor = "blue")
+
+ @Before fun isolatedEmulatorOnly() { assumeTrue(Build.PRODUCT.startsWith("sdk")) }
+
+ @Test fun settingsShowTheAvatarFirstAndTheAgentPickerOffersACustomCommand() {
+ var closed = false
+ render(scout, close = { closed = true })
+ compose.onNodeWithText("Settings").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Save").assertIsEnabled()
+ compose.onNodeWithContentDescription("blob shape").assertIsSelected()
+ compose.onNodeWithContentDescription("cloud shape").performClick().assertIsSelected()
+ compose.onNodeWithContentDescription("blob shape").assertIsNotSelected()
+ compose.onNodeWithContentDescription("Green").performScrollTo().performClick().assertIsSelected()
+ val name = compose.onNode(hasSetTextAction() and hasText("Scout")).assertIsDisplayed()
+ snapshot("bot-editor-settings-preview.png")
+ name.performTextReplacement("")
+ compose.onNodeWithContentDescription("Save").assertIsNotEnabled()
+ compose.onNodeWithContentDescription("Agent: Claude").performScrollTo().performClick()
+ compose.onNodeWithText("Codex (not installed)").assertIsDisplayed()
+ compose.onNodeWithText("Custom command").performClick()
+ compose.onNode(hasSetTextAction() and hasText("ACP command", substring = true)).performScrollTo().performTextInput("my-agent --acp")
+ compose.onNodeWithText("my-agent --acp").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Agent: Custom command").performClick()
+ compose.onNodeWithText("Codex (not installed)").performClick()
+ compose.onNodeWithText("Install Codex on your computer.").assertIsDisplayed()
+ compose.onNode(hasSetTextAction() and hasText("ACP command", substring = true)).assertDoesNotExist()
+ compose.onNodeWithContentDescription("Close").performClick()
+ assertTrue(closed)
+ }
+
+ @Test fun newBotsStayUnnamedAndNeedTheComputerToCreate() {
+ render(BotDraft(avatarShape = "blob", avatarColor = "blue"))
+ compose.onNodeWithText("New bot").assertIsDisplayed()
+ compose.onNodeWithText("Name").assertDoesNotExist()
+ compose.onNodeWithContentDescription("Create").assertIsEnabled()
+ compose.onNodeWithContentDescription("Agent: Claude").performScrollTo().assertIsDisplayed()
+ snapshot("bot-editor-new-preview.png")
+ }
+
+ @Test fun anOfflineNewBotCannotBeCreated() {
+ render(BotDraft(avatarShape = "blob", avatarColor = "blue"), fixture().copy(actualConnection = LinkState.Connecting))
+ compose.onNodeWithContentDescription("Create").assertIsNotEnabled()
+ compose.onNodeWithText("Connect this computer to create the bot.").assertIsDisplayed()
+ }
+
+ @Test fun workspaceAndPermissionsUseMenusWhileNotificationsAndPluginsUseRealSwitches() {
+ val plugins = PluginListing(listOf(InstalledConnector("git", "GitHub", kind = "local", command = "git-server")),
+ listOf(InstalledSkill("review", "Review changes", "Review before pushing", "local", "/skills/review.md")))
+ render(scout.copy(cwd = "/home/Project", notify = null), fixture().copy(plugins = plugins))
+ compose.onNodeWithText("This project is the default starting folder. The bot can work elsewhere when you ask.").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithContentDescription("Workspace").performClick()
+ compose.onNodeWithText("Personal workspace").performClick()
+ compose.onNodeWithText("This bot has its own space for files. It can work in other folders when you ask.").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Permissions: Approve automatically").performScrollTo().performClick()
+ compose.onNodeWithText("Ask me").performClick()
+ compose.onNodeWithText("You'll get an approval card and a notification whenever the agent asks.").assertIsDisplayed()
+ toggle("Notifications").performScrollTo().assertIsOn().performClick().assertIsOff()
+ toggle("Use the computer").performScrollTo().assertIsOff()
+ toggle("GitHub").performScrollTo().assertIsOn().performClick().assertIsOff()
+ toggle("Review changes").performScrollTo().assertIsOff().performClick().assertIsOn()
+ compose.onNodeWithContentDescription("Workspace").performScrollTo().performClick()
+ compose.onNodeWithText("Choose project folder…").performClick()
+ compose.onNodeWithText("Folders").assertIsDisplayed()
+ }
+
+ @Test fun offlineSettingsDisableSavingButKeepTheModelEditable() {
+ render(scout.copy(model = "old-model"), fixture().copy(actualConnection = LinkState.Connecting))
+ compose.onNodeWithContentDescription("Save").assertIsNotEnabled()
+ compose.onNodeWithText("Reconnect to this computer to save settings.").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithText("Connect to this computer to load its models. You can still enter a model ID.").performScrollTo().assertIsDisplayed()
+ compose.onNode(hasSetTextAction() and hasText("old-model")).performTextReplacement("my-model")
+ compose.onNode(hasSetTextAction() and hasText("my-model")).assertIsDisplayed()
+ }
+
+ @Test fun pluginTogglesKeepUnknownSavedIdsWhileSwitchingInstalledOnes() {
+ var selection by mutableStateOf(listOf("missing-skill"))
+ compose.setContent { Hosted { PluginToggles("Skills", "No skills yet.",
+ listOf(Triple("installed-skill", "Fixture skill", "From the fixture")), selection, { selection = it }) } }
+ toggle("Fixture skill").assertIsOff().performClick().assertIsOn()
+ assertEquals(listOf("missing-skill", "installed-skill"), selection)
+ toggle("Fixture skill").performClick().assertIsOff()
+ assertEquals(listOf("missing-skill"), selection)
+ compose.onNodeWithText("No skills yet.").assertDoesNotExist()
+ }
+
+ private fun render(draft: BotDraft, state: AppState = fixture(), close: () -> Unit = {}) {
+ compose.setContent { Hosted { CompositionLocalProvider(LocalDismissModal provides close) { BotEditor(state, draft, viewModel()) } } }
+ }
+
+ private fun toggle(title: String) = compose.onNode(hasText(title) and isToggleable())
+
+ private fun fixture(): AppState = AppState(loading = false, setupComplete = true,
+ actualConnection = LinkState.Ready(HostRoute.Direct), plugins = PluginListing(emptyList(), emptyList()),
+ computers = listOf(Computer("fixture", "Fixture computer", "fixture-key")), hello = buildJsonObject {
+ put("backends", buildJsonArray {
+ add(buildJsonObject { put("id", "claude"); put("name", "Claude"); put("available", true) })
+ add(buildJsonObject { put("id", "codex"); put("name", "Codex"); put("available", false); put("installHint", "Install Codex on your computer.") })
+ })
+ put("screen", buildJsonObject { put("enabled", true) })
+ })
+
+ private fun snapshot(name: String) {
+ if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") != "true") return
+ val bitmap = compose.onRoot().captureToImage().asAndroidBitmap()
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ File(context.cacheDir, name).outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/CameraScannerTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/CameraScannerTest.kt
new file mode 100644
index 00000000..1fcb6b5f
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/CameraScannerTest.kt
@@ -0,0 +1,81 @@
+package com.codync.android
+
+import android.Manifest
+import android.content.pm.PackageManager
+import android.hardware.camera2.CameraManager
+import android.os.Handler
+import android.os.Looper
+import androidx.activity.ComponentActivity
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.material3.Text
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.core.content.ContextCompat
+import androidx.lifecycle.Lifecycle
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.design.CodyncTheme
+import java.util.concurrent.ConcurrentHashMap
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+
+class CameraScannerTest {
+ @get:Rule val compose = createAndroidComposeRule<ComponentActivity>()
+ private val context get() = InstrumentationRegistry.getInstrumentation().targetContext
+ private val hasCamera get() = context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)
+
+ @Test fun theViewfinderAsksForTheCameraInPlaceBeforeOpeningIt() {
+ assumeTrue(hasCamera)
+ assumeTrue(ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
+ compose.setContent { CodyncTheme { QrViewfinder({ fail("No code without a camera") }, Modifier.fillMaxSize()) } }
+ compose.onNodeWithText("Allow the camera to scan the code on your computer.").assertIsDisplayed()
+ compose.onNodeWithText("Allow camera").assertIsDisplayed().assertHasClickAction()
+ compose.onNodeWithText("Camera settings").assertDoesNotExist()
+ }
+
+ @Test fun aDeviceWithoutACameraPointsToThePasteField() {
+ assumeTrue(!hasCamera)
+ compose.setContent { CodyncTheme { QrViewfinder({}, Modifier.fillMaxSize()) } }
+ compose.onNodeWithText("Camera not available. Paste the link below.").assertIsDisplayed()
+ compose.onNodeWithText("Allow camera").assertDoesNotExist()
+ }
+
+ /** Explicit emulator gate. The ordinary suite does not silently grant physical camera access. */
+ @Test fun aRealCameraClosesInBackgroundReopensAndReleasesWhenTheViewfinderLeaves() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("inspectCamera") == "true")
+ assertTrue("Native camera fixture belongs on an emulator", android.os.Build.HARDWARE in listOf("ranchu", "goldfish"))
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ assumeTrue(hasCamera)
+ instrumentation.uiAutomation.grantRuntimePermission(context.packageName, Manifest.permission.CAMERA)
+ val manager = context.getSystemService(CameraManager::class.java)
+ val unavailable = ConcurrentHashMap.newKeySet<String>()
+ val callback = object : CameraManager.AvailabilityCallback() {
+ override fun onCameraUnavailable(cameraId: String) { unavailable.add(cameraId) }
+ override fun onCameraAvailable(cameraId: String) { unavailable.remove(cameraId) }
+ }
+ manager.registerAvailabilityCallback(callback, Handler(Looper.getMainLooper()))
+ val visible = mutableStateOf(true)
+ val errors = mutableListOf<String>()
+ try {
+ compose.setContent { CodyncTheme {
+ if (visible.value) QrViewfinder({ fail("The empty emulator camera must not find a pairing code") }, Modifier.fillMaxSize()) { it?.let(errors::add) }
+ else Text("Scanner closed")
+ } }
+ compose.waitUntil(15_000) { unavailable.isNotEmpty() }
+ assertEquals(emptyList<String>(), errors)
+ compose.activityRule.scenario.moveToState(Lifecycle.State.CREATED)
+ compose.waitUntil(15_000) { unavailable.isEmpty() }
+ compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
+ compose.waitUntil(15_000) { unavailable.isNotEmpty() }
+ compose.runOnUiThread { visible.value = false }
+ compose.onNodeWithText("Scanner closed").assertIsDisplayed()
+ compose.waitUntil(15_000) { unavailable.isEmpty() }
+ } finally {
+ compose.runOnUiThread { visible.value = false }
+ manager.unregisterAvailabilityCallback(callback)
+ }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/ChatLayoutTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/ChatLayoutTest.kt
new file mode 100644
index 00000000..209dee41
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/ChatLayoutTest.kt
@@ -0,0 +1,129 @@
+package com.codync.android
+
+import android.graphics.Bitmap
+import android.os.Build
+import androidx.activity.compose.setContent
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.asAndroidBitmap
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.lifecycle.ViewModelProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import java.io.File
+
+class ChatLayoutTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+
+ @Test fun oneWayBotMessagesShowAttributionWithoutAStatusLine() {
+ assumeTrue(Build.PRODUCT.startsWith("sdk"))
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ val bot = Bot("handoff-preview", "Dex")
+ val body = "Urgent. Investigate the connection error."
+ val heading = "Message from Miles: $body"
+ val detail = "Recipient stopped. Partial work may have happened."
+ val entry = Entry("bot-message", 1, bot.id, rev = 1, kind = "notice", data = buildJsonObject {
+ put("text", "$heading\n$detail"); put("heading", heading); put("delegationId", "request"); put("style", "error")
+ })
+ val state = AppState(loading = false, selectedBot = bot.id, bots = listOf(bot),
+ connection = LinkState.Ready(HostRoute.Direct), actualConnection = LinkState.Ready(HostRoute.Direct),
+ historyComplete = setOf(bot.id), entries = listOf(entry))
+ compose.runOnUiThread { compose.activity.setContent { Hosted { ChatScreen(state, store, {}) } } }
+ val label = compose.onNodeWithText("Message from Miles").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ val message = compose.onNodeWithText(body).assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ assertTrue(label.bottom <= message.top)
+ compose.onNodeWithText(detail).assertDoesNotExist()
+ compose.onNodeWithText(heading).assertDoesNotExist()
+ if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") == "true") {
+ val bitmap = compose.onRoot().captureToImage().asAndroidBitmap()
+ File(compose.activity.cacheDir, "bot-message-preview.png").outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ }
+ }
+
+ @Test fun botRepliesAppearBelowTheRequestInSeparateBubbles() {
+ assumeTrue(Build.PRODUCT.startsWith("sdk"))
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ val bot = Bot("reply-preview", "Dex")
+ val body = "Investigate the connection error."
+ val heading = "Request from Miles: $body"
+ val answer = "The caller cancelled while audio was connecting."
+ val entry = Entry("bot-reply", 1, bot.id, rev = 1, kind = "notice", data = buildJsonObject {
+ put("text", "$heading\nReply from Dex:\n$answer"); put("heading", heading)
+ put("delegationId", "request"); put("status", "completed")
+ })
+ val state = AppState(loading = false, selectedBot = bot.id, bots = listOf(bot),
+ connection = LinkState.Ready(HostRoute.Direct), actualConnection = LinkState.Ready(HostRoute.Direct),
+ historyComplete = setOf(bot.id), entries = listOf(entry))
+ compose.runOnUiThread { compose.activity.setContent { Hosted { ChatScreen(state, store, {}) } } }
+ val request = compose.onNodeWithText(body).assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ val attribution = compose.onNodeWithText("Reply from Dex").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ val reply = compose.onNodeWithText(answer).assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ assertTrue(request.bottom <= attribution.top)
+ assertTrue(attribution.bottom <= reply.top)
+ val fullReply = Entry("full-reply", 2, bot.id, rev = 2, kind = "agent", data = buildJsonObject {
+ put("text", answer); put("final", true)
+ })
+ compose.runOnUiThread { compose.activity.setContent {
+ Hosted { ChatScreen(state.copy(entries = listOf(entry, fullReply)), store, {}) }
+ } }
+ compose.onAllNodesWithText("Reply from Dex").assertCountEquals(1)
+ compose.onAllNodesWithText(answer).assertCountEquals(1)
+ compose.onNode(hasText(answer) and hasClickAction()).performTouchInput { longClick(Offset(4f, 4f)) }
+ compose.onNodeWithText("Reply in thread").assertIsDisplayed()
+ compose.onNodeWithText("Show what it did").assertIsDisplayed()
+ InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(android.view.KeyEvent.KEYCODE_BACK)
+ if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") == "true") {
+ val bitmap = compose.onRoot().captureToImage().asAndroidBitmap()
+ File(compose.activity.cacheDir, "bot-reply-preview.png").outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ }
+ }
+
+ @Test fun aShortConversationStaysNearItsComposerAndRetainsContextActions() {
+ assumeTrue(Build.PRODUCT.startsWith("sdk"))
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ val bot = Bot("layout-preview", "Scout", avatarColor = "green", avatarShape = "cloud")
+ val sent = "Add a weekly totals helper and check its tests."
+ val reply = "I added the helper and a test. All four tests pass."
+ val now = System.currentTimeMillis()
+ val state = AppState(loading = false, selectedBot = bot.id, bots = listOf(bot),
+ connection = LinkState.Ready(HostRoute.Direct), actualConnection = LinkState.Ready(HostRoute.Direct),
+ historyComplete = setOf(bot.id), entries = listOf(
+ Entry("user-layout", 1, bot.id, rev = 1, kind = "user", data = buildJsonObject { put("text", sent) }, createdAt = now),
+ Entry("agent-layout", 2, bot.id, rev = 1, kind = "agent", data = buildJsonObject { put("text", reply); put("author", bot.id); put("final", true) }, createdAt = now)))
+ compose.runOnUiThread { compose.activity.setContent { Hosted { ChatScreen(state, store, {}) } } }
+ compose.onNodeWithText("You").assertDoesNotExist()
+ compose.onNodeWithText("Message actions").assertDoesNotExist()
+ compose.onNodeWithText("Reply in thread").assertDoesNotExist()
+ compose.onAllNodesWithText(bot.name).assertCountEquals(1)
+ val user = compose.onNode(hasText(sent) and hasClickAction())
+ val agent = compose.onNode(hasText(reply) and hasClickAction())
+ val userBounds = user.fetchSemanticsNode().boundsInRoot
+ val agentBounds = agent.fetchSemanticsNode().boundsInRoot
+ val root = compose.onRoot().fetchSemanticsNode().boundsInRoot
+ assertTrue(userBounds.left > agentBounds.left)
+ assertTrue(userBounds.right > agentBounds.right)
+ assertTrue(userBounds.top > root.height / 2)
+ compose.onNodeWithContentDescription("Add files").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Call").assertIsDisplayed()
+ if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") == "true") {
+ val bitmap = compose.onRoot().captureToImage().asAndroidBitmap()
+ File(compose.activity.cacheDir, "layout-chat-preview.png").outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ }
+ user.performTouchInput { longClick(Offset(4f, 4f)) }
+ compose.onNodeWithText("Reply in thread").assertIsDisplayed()
+ compose.onNodeWithContentDescription("👍").assertIsDisplayed()
+ compose.onNodeWithText("Copy").assertIsDisplayed()
+ compose.onNodeWithText("Show what it did").assertDoesNotExist()
+ InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(android.view.KeyEvent.KEYCODE_BACK)
+ compose.onNodeWithText("Copy").assertDoesNotExist()
+ compose.onNode(chatMenu).performClick()
+ compose.onNodeWithText("Edit profile").assertIsDisplayed()
+ compose.onNodeWithText("Routines").assertIsDisplayed()
+ compose.onNodeWithText("Full conversation").assertIsDisplayed()
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionRequestCardTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionRequestCardTest.kt
new file mode 100644
index 00000000..798415fb
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionRequestCardTest.kt
@@ -0,0 +1,66 @@
+package com.codync.android
+
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.ui.semantics.SemanticsProperties
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.lifecycle.viewmodel.compose.viewModel
+import com.codync.android.core.*
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Rule
+import org.junit.Test
+
+/** A bot's connection request in the chat. Read-only: no test submits a credential to the store. */
+class ConnectionRequestCardTest {
+ @get:Rule val compose = createComposeRule()
+ private val bot = Bot("bot", "Scout")
+ private val online = AppState(loading = false, bots = listOf(bot), actualConnection = LinkState.Ready(HostRoute.Direct))
+
+ private fun card(request: ConnectionRequest, text: String = "") = Entry("request", 1, bot.id, rev = 1, kind = "connectionRequest",
+ data = buildJsonObject { put("text", text); put("connectionRequest", WireJson.encodeToJsonElement(ConnectionRequest.serializer(), request)) })
+
+ @Test fun aLoginNeedsAMaskedPasswordAndTheComputerBeforeSaving() {
+ val state = mutableStateOf(online)
+ // A site without a dot: no favicon to fetch.
+ val entry = card(ConnectionRequest("login", "pending", "Fixture login", bot.id, site = "fixture"))
+ compose.setContent { Hosted { ConnectionRequestCard(entry, state.value, viewModel(), { _, _ -> fail("Not an app") }, { _, _ -> fail("Not a connector") }) } }
+ compose.onNodeWithText("Save").assertIsNotEnabled()
+ compose.onNodeWithContentDescription("Username or email").performTextInput("fixture-user")
+ compose.onNodeWithContentDescription("Password or op:// reference")
+ .assert(SemanticsMatcher.keyIsDefined(SemanticsProperties.Password)).performTextInput("fixture-password")
+ compose.onNodeWithText("Save").assertIsEnabled()
+ compose.onNodeWithText("Saved securely on this computer. The bot types it into the sign-in page but never sees it.").assertIsDisplayed()
+ compose.runOnUiThread { state.value = online.copy(actualConnection = LinkState.Connecting) }
+ compose.onNodeWithText("Save").assertIsNotEnabled()
+ }
+
+ @Test fun anAppRequestOpensItsSheetForThisRequest() {
+ val opened = mutableListOf<Pair<String, ComposioApp>>()
+ val entry = card(ConnectionRequest("app", "pending", "GitHub", bot.id, toolkit = "github"), "Needs GitHub to open the PR.")
+ compose.setContent { Hosted { ConnectionRequestCard(entry, online, viewModel(), { id, app -> opened.add(id to app) }, { _, _ -> fail("Not a connector") }) } }
+ compose.onNodeWithText("Needs GitHub to open the PR.").assertIsDisplayed()
+ compose.onNodeWithText("Connect").performClick()
+ compose.waitUntil { opened.isNotEmpty() }
+ assertEquals("request", opened.single().first)
+ assertEquals("github", opened.single().second.slug)
+ }
+
+ @Test fun finishedAndUnknownRequestsNeverLookPending() {
+ val request = mutableStateOf(ConnectionRequest("connection", "ready", "Fixture connector", bot.id, connectorId = "fixture"))
+ compose.setContent { Hosted { ConnectionRequestCard(card(request.value), online, viewModel(), { _, _ -> }, { _, _ -> }) } }
+ compose.onNodeWithText("Connected").assertIsDisplayed()
+ compose.onNodeWithText("Connect").assertDoesNotExist()
+ compose.runOnUiThread { request.value = request.value.copy(status = "future-status") }
+ compose.onNodeWithText("Cancelled").assertIsDisplayed()
+ compose.onNodeWithText("Connected").assertDoesNotExist()
+ compose.onNodeWithText("Connect").assertDoesNotExist()
+ }
+
+ @Test fun aRequestForAnUnknownBotAsksForANewerApp() {
+ val entry = card(ConnectionRequest("secret", "pending", "Fixture key", "elsewhere"))
+ compose.setContent { Hosted { ConnectionRequestCard(entry, online, viewModel(), { _, _ -> }, { _, _ -> }) } }
+ compose.onNodeWithText("This connection request needs a newer app.").assertIsDisplayed()
+ compose.onNodeWithText("Connect").assertDoesNotExist()
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionUiTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionUiTest.kt
new file mode 100644
index 00000000..043c45ae
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionUiTest.kt
@@ -0,0 +1,43 @@
+package com.codync.android
+
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.viewmodel.compose.viewModel
+import com.codync.android.core.*
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+
+class ConnectionUiTest {
+ @get:Rule val compose = createComposeRule()
+ private fun fixture(link: LinkState) = AppState(loading = false, setupComplete = true, rosterLoaded = true,
+ computers = listOf(Computer("fixture", "Fixture computer", "fixture")), connection = link, actualConnection = link)
+
+ @Test fun theComputerRowNamesTheActualConnectionState() {
+ val state = mutableStateOf(fixture(LinkState.Failed("Your access was revoked.", 403)))
+ compose.setContent { Hosted { SettingsView(state.value, viewModel(), null, {}, {}, {}) } }
+ compose.onNodeWithText("Access denied").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Extensions").assertDoesNotExist()
+ compose.runOnUiThread { state.value = fixture(LinkState.ComputerOffline(null)) }
+ compose.onNodeWithText("Computer offline").assertIsDisplayed()
+ compose.runOnUiThread { state.value = fixture(LinkState.Ready(HostRoute.Direct)).copy(bots = listOf(Bot("bot", "Saved bot"))) }
+ compose.onNodeWithText("1 bot · Wi-Fi/Tailscale").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Extensions").assertIsDisplayed()
+ }
+
+ @Test fun cachedBotsStayListedWhileOfflineAndAnEmptyRosterOffersTheFirstBot() {
+ val state = mutableStateOf(fixture(LinkState.ComputerOffline(null)).copy(bots = listOf(Bot("bot", "Saved bot"))))
+ var created = false
+ compose.setContent { Hosted { BotListView(state.value, viewModel(), {}, {}, { created = true }, {}, {}, 0.dp) } }
+ compose.onNodeWithText("Saved bot").assertIsDisplayed()
+ compose.onNodeWithText("Offline").assertIsDisplayed()
+ compose.onNodeWithText("No bots yet").assertDoesNotExist()
+ compose.runOnUiThread { state.value = fixture(LinkState.Ready(HostRoute.Direct)) }
+ compose.onNodeWithText("1 connected").assertIsDisplayed()
+ compose.onNodeWithText("No bots yet").assertIsDisplayed()
+ compose.onNodeWithText("Create your first bot").performClick()
+ assertTrue(created)
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectorOAuthBookTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectorOAuthBookTest.kt
new file mode 100644
index 00000000..62fe4b3c
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectorOAuthBookTest.kt
@@ -0,0 +1,24 @@
+package com.codync.android
+
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import java.io.File
+import java.util.UUID
+import org.junit.Assert.*
+import org.junit.Test
+
+class ConnectorOAuthBookTest {
+ @Test fun aNewOwnerRestoresOnlyTheStateHashAndOtherAccountsCannotReadIt() {
+ val root = File(InstrumentationRegistry.getInstrumentation().targetContext.cacheDir, "oauth-fixture-" + UUID.randomUUID()).apply { mkdirs() }
+ val first = File(root, "first").apply { mkdirs() }; val other = File(root, "other").apply { mkdirs() }
+ try {
+ val pending = PendingConnectorOAuth.create(ConnectorSignIn("https://example.com/login?state=fixture-state", "app"), "c", "host", System.currentTimeMillis())
+ ConnectorOAuthBook(first).save(pending)
+ assertEquals(pending, ConnectorOAuthBook(first).read())
+ assertNull(ConnectorOAuthBook(other).read())
+ assertFalse(File(first, "connector-oauth.json").readText().contains("fixture-state"))
+ ConnectorOAuthBook(first).clear()
+ assertNull(ConnectorOAuthBook(first).read())
+ } finally { root.deleteRecursively() }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/DraftBookTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/DraftBookTest.kt
new file mode 100644
index 00000000..9b0d59f9
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/DraftBookTest.kt
@@ -0,0 +1,67 @@
+package com.codync.android
+
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Test
+import java.io.File
+import java.util.UUID
+
+class DraftBookTest {
+ private val root = File(InstrumentationRegistry.getInstrumentation().targetContext.noBackupFilesDir,
+ "draft-test-" + UUID.randomUUID()).apply { mkdirs() }
+ private val computer = "AAAAAAAAAAAAAAAAAAAAAA"
+ @After fun cleanup() { root.deleteRecursively() }
+
+ @Test fun reopeningRestoresEachChatAndThreadWithoutCrossingAccountsOrComputers() {
+ val file = File(root, "outgoing/file").apply { requireNotNull(parentFile).mkdirs(); writeText("saved attachment") }
+ val main = ComposerDraft("bot", text = "Unsent main chat", files = listOf(OutgoingFile(file.path, "file.txt", file.length())))
+ val thread = ComposerDraft("bot", "thread", text = "Unsent reply")
+ DraftBook(root, computer).save(listOf(main, thread))
+ assertEquals(listOf(main, thread), DraftBook(root, computer).read())
+ assertNotEquals(main.lane, thread.lane)
+ assertTrue(DraftBook(root, "BBBBBBBBBBBBBBBBBBBBBB").read().isEmpty())
+ val otherAccount = File(root, "other-account").apply { mkdirs() }
+ assertTrue(DraftBook(otherAccount, computer).read().isEmpty())
+ assertTrue(file.exists())
+ }
+
+ @Test fun aCrashAfterPendingCommitCannotRestoreAnotherSendForTheSameDraft() {
+ val draft = ComposerDraft("bot", text = "Send once")
+ val book = DraftBook(root, computer)
+ book.save(listOf(draft))
+ val pending = PendingSend(draft.nonce, "bot", text = draft.text, createdAt = 1)
+ assertTrue(book.recover(MirrorSnapshot(pending = listOf(pending))).isEmpty())
+ assertTrue(DraftBook(root, computer).read().isEmpty())
+ book.save(listOf(draft))
+ val confirmed = Entry("entry", 1, "bot", rev = 1, kind = "user",
+ data = buildJsonObject { put("clientNonce", draft.nonce); put("text", draft.text) })
+ assertTrue(book.recover(MirrorSnapshot(entries = listOf(confirmed))).isEmpty())
+ }
+
+ @Test fun rejectedOversizedOrForeignAttachmentWritesRetainThePreviousDraft() {
+ val book = DraftBook(root, computer)
+ val safe = ComposerDraft("bot", text = "Keep this")
+ book.save(listOf(safe))
+ for (invalid in listOf(safe.copy(text = "x".repeat(65537)),
+ safe.copy(files = listOf(OutgoingFile(File(root, "identity").path, "private", 1))))) {
+ try { book.save(listOf(invalid)); fail("Expected draft validation") }
+ catch (_: IllegalArgumentException) { }
+ assertEquals(listOf(safe), book.read())
+ }
+ }
+
+ @Test fun clearingOneLaneKeepsOtherDraftsAndTheDraftCountIsBounded() {
+ val book = DraftBook(root, computer)
+ val drafts = (0 until 64).map { ComposerDraft("bot-$it", text = "Unsent $it") }
+ book.save(drafts)
+ try { book.save(drafts + ComposerDraft("overflow", text = "Unsent")); fail("Expected bounded drafts") }
+ catch (_: IllegalArgumentException) { }
+ assertEquals(drafts, book.read())
+ book.save(drafts.drop(1))
+ assertEquals(drafts.drop(1), book.read())
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/FixtureHost.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/FixtureHost.kt
new file mode 100644
index 00000000..c52287f4
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/FixtureHost.kt
@@ -0,0 +1,15 @@
+package com.codync.android
+
+import android.os.Build
+import androidx.test.platform.app.InstrumentationRegistry
+import org.junit.Assert.assertEquals
+import org.junit.Assume.assumeTrue
+
+/** Mutating live suites require an emulator and the controller's disposable host ID. */
+internal fun requireFixtureHost(computerId: String) {
+ assumeTrue(Build.PRODUCT.startsWith("sdk"))
+ val expected = requireNotNull(InstrumentationRegistry.getArguments().getString("fixtureComputerId")) {
+ "Pass fixtureComputerId for the isolated acceptance host. Never run these suites on a user phone."
+ }
+ assertEquals("This suite must use its disposable host", expected, computerId)
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LayoutTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LayoutTest.kt
new file mode 100644
index 00000000..af1d218d
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LayoutTest.kt
@@ -0,0 +1,80 @@
+package com.codync.android
+
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.graphics.asAndroidBitmap
+import androidx.lifecycle.viewmodel.compose.viewModel
+import androidx.test.platform.app.InstrumentationRegistry
+import android.graphics.Bitmap
+import java.io.File
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.compose.ui.unit.Density
+import com.codync.android.core.*
+import org.junit.Assert.*
+import org.junit.Rule
+import org.junit.Test
+
+/** Read-only roster fixture: nothing here pairs, saves or sends. */
+class LayoutTest {
+ @get:Rule val compose = createComposeRule()
+ private val state = AppState(loading = false, setupComplete = true, rosterLoaded = true,
+ computers = listOf(Computer("fixture", "Acceptance computer", "fixture")),
+ connection = LinkState.Ready(HostRoute.Direct), actualConnection = LinkState.Ready(HostRoute.Direct), bots = (1..5).map {
+ Bot("bot-$it", "Bot $it", lastMessage = "A recent reply", unread = if (it == 1) 12 else 0)
+ })
+ private val computers = hasContentDescription("Computers,", substring = true)
+ private fun tab(title: String) = hasText(title) and isSelectable()
+
+ @Test fun theRosterShowsFiveRowsAndKeepsActionsOnDemand() {
+ compose.setContent { Hosted { CodyncApp(state, viewModel()) } }
+ (1..5).forEach { compose.onNodeWithText("Bot $it").assertIsDisplayed() }
+ compose.onNodeWithText("12").assertIsDisplayed()
+ snapshot("roster")
+ compose.onNodeWithText("New bot").assertDoesNotExist()
+ compose.onNodeWithText("Account").assertDoesNotExist()
+ compose.onNodeWithContentDescription("Switch account").performClick()
+ compose.onNodeWithText("Account").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Close").performClick()
+ compose.onNodeWithText("Account").assertDoesNotExist()
+ compose.onNodeWithContentDescription("New").performClick()
+ compose.onNodeWithText("New group chat").assertIsDisplayed()
+ compose.onNodeWithText("New bot").performClick()
+ compose.onNodeWithContentDescription("Create").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Close").performClick()
+ compose.onNodeWithContentDescription("Create").assertDoesNotExist()
+ compose.onNode(tab("State")).performClick().assertIsSelected()
+ compose.onNodeWithText("Widget").assertIsSelected()
+ compose.onNodeWithText("Choose your widget").performScrollTo().assertIsDisplayed()
+ snapshot("widget-gallery")
+ compose.onNodeWithText("Bot 1").assertDoesNotExist()
+ compose.onNode(tab("Bots")).performClick().assertIsSelected()
+ compose.onNodeWithText("Bot 5").assertIsDisplayed()
+ }
+
+ @Test fun largerTextKeepsTheHeaderControlsAndUnreadBadgeAccessible() {
+ compose.setContent {
+ val density = LocalDensity.current
+ CompositionLocalProvider(LocalDensity provides Density(density.density, 1.5f)) {
+ Hosted { CodyncApp(state, viewModel()) }
+ }
+ }
+ val account = compose.onNodeWithContentDescription("Switch account").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ val summary = compose.onNode(computers).assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ val new = compose.onNodeWithContentDescription("New").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ compose.onNodeWithContentDescription("12 unread").assertIsDisplayed()
+ assertTrue(account.right <= summary.left)
+ assertTrue(summary.right <= new.left)
+ snapshot("large-text")
+ compose.onNode(computers).performClick()
+ compose.onNodeWithText("Manage computers").assertIsDisplayed()
+ compose.onNodeWithText("Acceptance computer · Connected").assertIsDisplayed()
+ }
+
+ private fun snapshot(name: String) {
+ if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") != "true") return
+ val bitmap = compose.onRoot().captureToImage().asAndroidBitmap()
+ val file = File(InstrumentationRegistry.getInstrumentation().targetContext.cacheDir, "layout-$name.png")
+ file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveChatTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveChatTest.kt
new file mode 100644
index 00000000..8b4ea02b
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveChatTest.kt
@@ -0,0 +1,91 @@
+package com.codync.android
+
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.test.platform.app.InstrumentationRegistry
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import java.util.UUID
+import java.io.File
+import android.graphics.Bitmap
+import androidx.compose.ui.graphics.asAndroidBitmap
+import android.content.ClipData
+import android.content.ClipboardManager
+import androidx.core.content.FileProvider
+import androidx.lifecycle.ViewModelProvider
+import com.codync.android.core.*
+import kotlinx.serialization.json.*
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertArrayEquals
+
+/** Opt-in: the paired, isolated acceptance host uses host/tests/fake_agent.py. */
+class LiveChatTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+
+ @Test fun aRealHostSendPermissionAndReplyRoundTrip() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("liveHost") == "true")
+ val bot = "Android chat acceptance"
+ compose.waitUntil(30_000) { compose.onAllNodesWithText(bot).fetchSemanticsNodes().isNotEmpty() }
+ val back = compose.onAllNodes(hasText("Back") or hasContentDescription("Back")).fetchSemanticsNodes()
+ if (back.isEmpty()) compose.onNodeWithText(bot).performClick()
+ compose.waitUntil(10_000) { compose.onAllNodes(chatMenu).fetchSemanticsNodes().size == 1 }
+ val message = "Android acceptance " + UUID.randomUUID()
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ val local = LocalStore(context)
+ requireFixtureHost(local.computers().single().id)
+ val mirror = MirrorDatabase(context, local.directory, local.computers().single().id)
+ compose.onNode(hasSetTextAction()).performTextReplacement(message)
+ compose.onNodeWithContentDescription("Send").performClick()
+ compose.waitUntil(30_000) { compose.onAllNodesWithText("Allow once").fetchSemanticsNodes().isNotEmpty() }
+ compose.onNodeWithText("Allow once").performScrollTo().performClick()
+ try {
+ compose.waitUntil(30_000) {
+ val entries = mirror.snapshot().entries
+ val sent = entries.firstOrNull { it.kind == "user" && it.text == message }
+ sent != null && entries.any { it.seq > sent.seq && it.kind == "agent" && it.isChat }
+ }
+ compose.onAllNodes(hasText("Done:", substring = true)).onLast().assertIsDisplayed()
+ if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") == "true") {
+ val bitmap = compose.onRoot().captureToImage().asAndroidBitmap()
+ File(context.cacheDir, "layout-chat.png").outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ }
+ val source = File(context.cacheDir, "shared-attachments/live-" + UUID.randomUUID() + ".bin").apply { parentFile?.mkdirs() }
+ val bytes = ByteArray(HostFiles.CHUNK_BYTES + 17) { (it % 255).toByte() }
+ source.writeBytes(bytes)
+ try {
+ compose.runOnUiThread {
+ val uri = FileProvider.getUriForFile(context, context.packageName + ".files", source)
+ context.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newUri(context.contentResolver, "Acceptance file", uri))
+ }
+ compose.onNodeWithContentDescription("Add files").performClick()
+ compose.onNodeWithText("Paste").performClick()
+ compose.waitUntil(10_000) { compose.onAllNodes(hasText(source.name, substring = true)).fetchSemanticsNodes().isNotEmpty() }
+ compose.onNodeWithContentDescription("Send").performClick()
+ compose.waitUntil(30_000) { compose.onAllNodesWithText("Allow once").fetchSemanticsNodes().isNotEmpty() }
+ compose.onNodeWithText("Allow once").performScrollTo().performClick()
+ var sent: Entry? = null
+ compose.waitUntil(30_000) {
+ val entries = mirror.snapshot().entries
+ sent = entries.firstOrNull { entry -> entry.kind == "user" && entry.data["attachments"]?.jsonArray?.any { it.jsonObject["name"]?.jsonPrimitive?.content == source.name } == true }
+ val upload = sent
+ upload != null && entries.any { it.seq > upload.seq && it.kind == "agent" && it.isChat }
+ }
+ val entry = requireNotNull(sent)
+ val attachment = WireJson.decodeFromJsonElement<Attachment>(entry.data.getValue("attachments").jsonArray.single())
+ runBlocking {
+ val computer = local.computers().single().copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly)
+ val channel = HostConnector.connect(computer, local.identity())
+ val downloaded = File(context.cacheDir, "live-download-" + UUID.randomUUID())
+ try {
+ HostFiles(channel).download(entry.botId, attachment, downloaded)
+ assertArrayEquals(bytes, downloaded.readBytes())
+ } finally { channel.close(); downloaded.delete() }
+ }
+ } finally {
+ source.delete()
+ compose.runOnUiThread { context.getSystemService(ClipboardManager::class.java).clearPrimaryClip() }
+ }
+ } finally { mirror.close() }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveCredentialsTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveCredentialsTest.kt
new file mode 100644
index 00000000..e75dc45a
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveCredentialsTest.kt
@@ -0,0 +1,136 @@
+package com.codync.android
+
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.lifecycle.ViewModelProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import java.util.UUID
+
+/** Opt-in, account-free, disposable host only. The caller seeds requests through its local token. */
+class LiveCredentialsTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+
+ @Test fun savedSignInsAndImportedConnectorCredentialsStayOnTheHost() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("liveCredentials") == "true")
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ assertNull(PushPreferences.activeUser(context))
+ val local = LocalStore(context)
+ val computer = local.computers().single()
+ requireFixtureHost(computer.id)
+ val route = computer.copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly)
+ val channel = runBlocking { HostConnector.connect(route, local.identity()) }
+ val original = runBlocking { HostClient.bots(channel) }
+ val suffix = UUID.randomUUID().toString().take(8)
+ val site = "android-$suffix.fixture.invalid"
+ val name = "Android credentials $suffix"
+ try {
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.actualConnection is LinkState.Ready }
+ compose.runOnUiThread { store.openBot(null) }
+ compose.openExtensions()
+ compose.onNodeWithText("Credentials").performScrollTo().performClick()
+ field("github.com").performTextReplacement(site)
+ field("[email protected]").performTextReplacement("fixture-user")
+ field("Password or op:// reference").performTextReplacement(" fixture-password ")
+ compose.onNodeWithText("Save sign-in").performScrollTo().performClick()
+ compose.waitUntil(20_000) { listedLogins(channel).any { it.site == site } }
+ val saved = listedLogins(channel).single { it.site == site }
+ assertEquals("fixture-user", saved.username)
+ assertFalse(WireJson.encodeToJsonElement(saved).toString().contains("fixture-password"))
+ compose.waitUntil(20_000) { compose.onAllNodesWithText(site).fetchSemanticsNodes().size == 1 }
+ compose.onRowButton("Remove", site).performClick()
+ compose.waitUntil(20_000) { listedLogins(channel).none { it.id == saved.id } }
+ back()
+ // Paste an MCP config into a custom connector: every server in it is added.
+ compose.onNodeWithText("Custom connector").performScrollTo().performClick()
+ compose.onNodeWithText("Config").performClick()
+ val fixturePath = requireNotNull(InstrumentationRegistry.getArguments().getString("credentialMcp"))
+ assertTrue(fixturePath.endsWith("/Codync/host/tests/fixtures/credential_mcp.py"))
+ val config = buildJsonObject { putJsonObject("mcpServers") { putJsonObject(name) {
+ put("command", "/opt/homebrew/bin/python3.13"); put("args", JsonArray(listOf(JsonPrimitive(fixturePath))))
+ putJsonObject("env") { put("API_KEY", "test-private-key"); put("PRESERVED", "fixture-preserved") }
+ } } }.toString()
+ field("{ \"mcpServers\": { … } }").performTextReplacement(config)
+ compose.onNodeWithContentDescription("Add").performClick()
+ compose.waitUntil(30_000) { compose.onAllNodesWithText("Custom connector", useUnmergedTree = true).fetchSemanticsNodes().size == 1 }
+ compose.waitUntil(30_000) { runBlocking { channel.call("connectors") }.toString().contains(name) }
+ compose.onNodeWithText("Credentials").performScrollTo().performClick()
+ compose.waitUntil(20_000) { compose.onAllNodesWithText(name).fetchSemanticsNodes().isNotEmpty() }
+ compose.onAllNodesWithText(name).onLast().performScrollTo().performClick()
+ field("API_KEY").performTextReplacement("test-private-key")
+ compose.onNodeWithContentDescription("Save credentials").performClick()
+ compose.waitUntil(20_000) { compose.onAllNodesWithContentDescription("Save credentials").fetchSemanticsNodes().isEmpty() }
+ val listing = runBlocking { channel.call("connectors") }
+ val connector = WireJson.decodeFromJsonElement<List<InstalledConnector>>(listing.jsonObject.getValue("items")).single { it.name == name }
+ assertEquals(setOf("API_KEY", "PRESERVED"), connector.keys.toSet())
+ assertFalse(listing.toString().contains("test-private-key"))
+ assertFalse(listing.toString().contains("fixture-preserved"))
+ assertTrue(runCatching { runBlocking { channel.call("connectorRuntime", body("id" to connector.id)) } }.isFailure)
+ } finally {
+ runBlocking {
+ val logins = channel.call("credentialLogins")
+ for (login in WireJson.decodeFromJsonElement<List<SavedLogin>>(logins.jsonObject.getValue("items")).filter { it.site == site })
+ channel.call("credentialRemoveLogin", body("id" to login.id))
+ val plugins = channel.call("connectors")
+ for (connector in WireJson.decodeFromJsonElement<List<InstalledConnector>>(plugins.jsonObject.getValue("items")).filter { it.name == name })
+ channel.call("removeConnector", body("id" to connector.id))
+ val remaining = HostClient.bots(channel)
+ for (bot in original.filter { previous -> remaining.any { it.id == previous.id } }) channel.call("updateBot", buildJsonObject {
+ put("id", bot.id); put("connectors", WireJson.encodeToJsonElement(bot.connectors)); put("skills", WireJson.encodeToJsonElement(bot.skills))
+ })
+ }
+ channel.close()
+ }
+ }
+
+ @Test fun aLoginCardSavesWithoutPuttingThePasswordInChat() {
+ val args = InstrumentationRegistry.getArguments()
+ val botId = args.getString("credentialBot")
+ assumeTrue(botId != null && args.getString("liveCredentials") == "true")
+ val savedRequest = requireNotNull(args.getString("loginRequest"))
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ assertNull(PushPreferences.activeUser(context))
+ val local = LocalStore(context)
+ val computer = local.computers().single()
+ requireFixtureHost(computer.id)
+ val route = computer.copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly)
+ val channel = runBlocking { HostConnector.connect(route, local.identity()) }
+ try {
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ compose.waitUntil(30_000) { store.state.value.bots.any { it.id == botId } && store.state.value.entries.any { it.id == savedRequest } }
+ assertTrue(store.state.value.bots.single { it.id == botId }.name.startsWith("Android credentials acceptance"))
+ compose.runOnUiThread { store.openBot(botId) }
+ cardField(savedRequest, "Username or email").performTextReplacement("fixture-card-user")
+ cardField(savedRequest, "Password or op:// reference").performTextReplacement("fixture-card-password")
+ cardAction(savedRequest, "Save").performClick()
+ compose.waitUntil(20_000) { store.state.value.entries.any { it.id == savedRequest && it.data["connectionRequest"]?.jsonObject?.get("status")?.jsonPrimitive?.content == "ready" } }
+ compose.onNode(hasText("Saved") and hasAnyAncestor(hasTestTag("connection:$savedRequest"))).assertIsDisplayed()
+ runBlocking { store.finishConnectionRequest(savedRequest, value = "fixture-card-password", username = "fixture-card-user") }
+ val history = runBlocking { channel.call("history", body("botId" to botId)) }
+ val entries = history.jsonObject.getValue("entries").jsonArray
+ assertEquals(1, entries.count { it.jsonObject["id"]?.jsonPrimitive?.content == "connection-ack-$savedRequest" })
+ assertFalse(history.toString().contains("fixture-card-password"))
+ val publicLogins = runBlocking { channel.call("credentialLogins") }
+ assertFalse(publicLogins.toString().contains("fixture-card-password"))
+ } finally { channel.close() }
+ }
+
+ private fun listedLogins(channel: EncryptedChannel): List<SavedLogin> = runBlocking {
+ val response = channel.call("credentialLogins")
+ WireJson.decodeFromJsonElement(response.jsonObject.getValue("items"))
+ }
+ /** Extensions fields are labeled by their prompt. */
+ private fun field(prompt: String): SemanticsNodeInteraction = compose.onNode(hasSetTextAction() and hasContentDescription(prompt)).performScrollTo()
+ private fun cardField(id: String, prompt: String): SemanticsNodeInteraction = compose.onNode(
+ hasSetTextAction() and hasContentDescription(prompt) and hasAnyAncestor(hasTestTag("connection:$id"))).performScrollTo()
+ private fun back() = InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(android.view.KeyEvent.KEYCODE_BACK)
+ private fun cardAction(id: String, label: String): SemanticsNodeInteraction = compose.onNode(
+ hasClickAction() and hasText(label) and hasAnyAncestor(hasTestTag("connection:$id"))).performScrollTo()
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveDraftTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveDraftTest.kt
new file mode 100644
index 00000000..d64b99ed
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveDraftTest.kt
@@ -0,0 +1,85 @@
+package com.codync.android
+
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.core.content.FileProvider
+import androidx.lifecycle.ViewModelProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import java.io.File
+import kotlinx.serialization.json.*
+
+/** The controller kills the emulator process between prepare and restore. Isolated host only. */
+class LiveDraftTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+
+ @Test fun draftsSurviveProcessDeathAndQueueUsingTheirPersistedNonce() {
+ val phase = InstrumentationRegistry.getArguments().getString("draftPhase")
+ assumeTrue(phase in listOf("prepare", "restore"))
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ val local = LocalStore(context)
+ val computer = local.computers().single()
+ requireFixtureHost(computer.id)
+ assertNull(PushPreferences.activeUser(context))
+ val book = DraftBook(local.directory, computer.id)
+ val metadata = File(context.cacheDir, "draft-acceptance.json")
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ compose.waitUntil(30_000) { store.state.value.bots.any { it.name == "Android chat acceptance" } }
+ val bot = store.state.value.bots.single { it.name == "Android chat acceptance" }
+ compose.runOnUiThread { store.openBot(bot.id) }
+ // A cached roster can arrive before startup finishes; wait for the chat itself.
+ compose.waitUntil(10_000) { !store.state.value.loading && store.state.value.rosterLoaded &&
+ compose.onAllNodes(chatMenu).fetchSemanticsNodes().size == 1 }
+ val mainText = "Android unsent draft acceptance"
+ val replyText = "Android unsent reply acceptance"
+ if (phase == "prepare") {
+ compose.waitUntil(10_000) { compose.onAllNodes(hasSetTextAction()).fetchSemanticsNodes().size == 1 }
+ compose.onNode(hasSetTextAction()).performTextReplacement(mainText)
+ compose.waitUntil(10_000) { store.state.value.drafts[ComposerDraft.lane(bot.id, null)]?.text == mainText }
+ val source = File(context.cacheDir, "shared-attachments/draft-acceptance/draft.txt").apply {
+ requireNotNull(parentFile).mkdirs(); writeText("Private draft attachment acceptance")
+ }
+ val uri = FileProvider.getUriForFile(context, context.packageName + ".files", source)
+ compose.runOnUiThread { store.importFiles(listOf(uri)) { store.addDraftFiles(bot.id, null, it) } }
+ try { compose.waitUntil(10_000) { store.state.value.drafts[ComposerDraft.lane(bot.id, null)]?.files?.size == 1 } }
+ catch (_: Throwable) { throw AssertionError("Draft import failed: ${store.state.value.error}; busy=${store.state.value.busy}") }
+ val root = store.state.value.entries.first { it.botId == bot.id && it.isChat && it.threadId == null }.id
+ compose.runOnUiThread { store.editDraft(bot.id, root, replyText) }
+ try { compose.waitUntil(10_000) { book.read().any { it.botId == bot.id && it.threadId == root && it.text == replyText } &&
+ book.read().any { it.botId == bot.id && it.threadId == null && it.files.size == 1 && it.text == mainText } } }
+ catch (_: Throwable) {
+ val current = store.state.value.drafts[ComposerDraft.lane(bot.id, null)]
+ throw AssertionError("Draft persistence failed: mainText=${current?.text == mainText}, files=${current?.files?.size}, error=${store.state.value.error}")
+ }
+ val main = book.read().single { it.botId == bot.id && it.threadId == null }
+ metadata.writeText(buildJsonObject { put("nonce", main.nonce); put("thread", root) }.toString())
+ } else {
+ val saved = Json.parseToJsonElement(metadata.readText()).jsonObject
+ val root = saved.getValue("thread").jsonPrimitive.content
+ val nonce = saved.getValue("nonce").jsonPrimitive.content
+ val main = store.state.value.drafts.getValue(ComposerDraft.lane(bot.id, null))
+ assertEquals(nonce, main.nonce)
+ assertEquals("Private draft attachment acceptance", File(main.files.single().path).readText())
+ compose.onNode(hasSetTextAction() and hasText(mainText)).assertIsDisplayed()
+ compose.onNodeWithContentDescription("Remove draft.txt").assertIsDisplayed()
+ compose.runOnUiThread { store.openBot(bot.id, root) }
+ compose.waitUntil(10_000) { compose.onAllNodes(hasSetTextAction() and hasText(replyText)).fetchSemanticsNodes().size == 1 }
+ compose.runOnUiThread { store.openBot(bot.id) }
+ compose.waitUntil(10_000) { compose.onAllNodes(hasSetTextAction() and hasText(mainText)).fetchSemanticsNodes().size == 1 }
+ compose.onNodeWithContentDescription("Send").performClick()
+ compose.waitUntil(30_000) { store.state.value.entries.any { it.botId == bot.id && it.clientNonce == nonce } }
+ val sent = store.state.value.entries.single { it.botId == bot.id && it.clientNonce == nonce }
+ assertFalse(store.state.value.drafts.containsKey(ComposerDraft.lane(bot.id, null)))
+ compose.waitUntil(10_000) { book.read().none { it.nonce == nonce } }
+ compose.waitUntil(30_000) { store.state.value.entries.any { it.botId == bot.id && it.kind == "permission" && it.status == "pending" } }
+ compose.onNodeWithText("Allow once").performClick()
+ compose.waitUntil(30_000) { store.state.value.entries.any { it.botId == bot.id && it.seq > sent.seq && it.kind == "agent" && it.isChat } }
+ compose.runOnUiThread { store.editDraft(bot.id, root, "") }
+ compose.waitUntil(10_000) { book.read().none { it.botId == bot.id } }
+ metadata.delete()
+ }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveManagementTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveManagementTest.kt
new file mode 100644
index 00000000..55cce2b1
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveManagementTest.kt
@@ -0,0 +1,102 @@
+package com.codync.android
+
+import android.view.KeyEvent
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.lifecycle.ViewModelProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import java.util.UUID
+
+/** Opt-in, disposable fake-agent host only. Never execute this on a user's phone. */
+class LiveManagementTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+
+ @Test fun groupsCreateMentionEditAndDeleteWithoutChangingTheirMembers() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("liveHost") == "true")
+ val local = LocalStore(InstrumentationRegistry.getInstrumentation().targetContext)
+ val computer = local.computers().single().copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly)
+ val channel = runBlocking { HostConnector.connect(computer, local.identity()) }
+ val created = mutableListOf<String>()
+ try {
+ val parent = runBlocking { HostClient.bots(channel) }.single { it.name == "Android chat acceptance" }
+ val name = "Reviewer" + UUID.randomUUID().toString().take(6)
+ val result = runBlocking { channel.call("createBot", BotDraft.from(parent).copy(id = null, name = name, permission = "auto").body()) }
+ val member = HostClient.decode(result.jsonObject.getValue("bot").jsonObject)
+ created.add(member.id)
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ compose.waitUntil(30_000) { store.state.value.bots.any { it.id == member.id } }
+ compose.runOnUiThread { store.openBot(null) }
+ compose.onNodeWithContentDescription("New").performClick()
+ compose.onNodeWithText("New group chat").performClick()
+ compose.onNodeWithText("Add Member").performClick()
+ val search = hasSetTextAction() and hasText("Search bots")
+ compose.onNode(search).performTextReplacement(member.name)
+ compose.onNodeWithContentDescription("Add " + member.name).performClick()
+ compose.onNode(search).performTextReplacement(parent.name)
+ compose.onNodeWithContentDescription("Add " + parent.name).performClick()
+ compose.onNodeWithContentDescription("Remove " + member.name).assertIsDisplayed()
+ compose.onNodeWithContentDescription("Create").performClick()
+ compose.waitUntil(30_000) { store.state.value.bots.any { it.id == store.state.value.selectedBot && it.kind == "group" } }
+ val group = store.state.value.bots.single { it.id == store.state.value.selectedBot }
+ created.add(group.id)
+ assertEquals(listOf(member.id, parent.id), group.members)
+ compose.onNodeWithText("New session").assertDoesNotExist()
+ compose.onNode(hasSetTextAction()).performTextReplacement("@${member.name} Check the group lane")
+ compose.onNodeWithContentDescription("Send").performClick()
+ compose.waitUntil(30_000) { store.state.value.entries.any { it.botId == group.id && it.kind == "agent" && it.isChat } }
+ val replies = store.state.value.entries.filter { it.botId == group.id && it.kind == "agent" && it.isChat }
+ assertTrue(replies.isNotEmpty())
+ assertTrue(replies.all { it.data["author"]?.jsonPrimitive?.content == member.id })
+ openEditor()
+ // The name field shows the members' names until the group has its own.
+ compose.onNode(hasSetTextAction() and hasText(group.name.ifBlank { "${member.name}, ${parent.name}" })).performTextReplacement("Edited group")
+ compose.onNodeWithContentDescription("Save").performClick()
+ compose.waitUntil(30_000) { store.state.value.bots.firstOrNull { it.id == group.id }?.name == "Edited group" }
+ assertEquals(group.members, store.state.value.bots.single { it.id == group.id }.members)
+ compose.waitUntil(10_000) { compose.onAllNodes(chatMenu).fetchSemanticsNodes().size == 1 }
+ compose.runOnUiThread { store.openBot(null) }
+ rosterActions("Edited group")
+ compose.onNodeWithText("Pin").performScrollTo().performClick()
+ compose.waitUntil(30_000) { store.state.value.bots.single { it.id == group.id }.pinned }
+ rosterActions("Edited group")
+ compose.onNodeWithText("Hide from list").performScrollTo().performClick()
+ compose.waitUntil(30_000) { store.state.value.bots.single { it.id == group.id }.hidden }
+ // Hidden bots come back from Computers & settings.
+ compose.computerAction("Manage computers")
+ compose.onRowButton("Unhide", "Edited group").performClick()
+ compose.waitUntil(30_000) { !store.state.value.bots.single { it.id == group.id }.hidden }
+ InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)
+ compose.waitUntil(10_000) { compose.onAllNodesWithText("Computers & settings").fetchSemanticsNodes().isEmpty() }
+ rosterActions("Edited group")
+ compose.onNodeWithText("Edit group").performClick()
+ compose.onNodeWithText("Delete group chat").performScrollTo().performClick()
+ compose.onAllNodesWithText("Delete group chat").onLast().performClick()
+ compose.waitUntil(30_000) { store.state.value.bots.none { it.id == group.id } && "delete:" + group.id !in store.state.value.busy }
+ val remaining = runBlocking { HostClient.bots(channel) }
+ assertFalse(remaining.any { it.id == group.id })
+ assertTrue(remaining.any { it.id == member.id })
+ assertTrue(remaining.any { it.id == parent.id })
+ created.remove(group.id)
+ } finally {
+ runBlocking { for (id in created.asReversed()) channel.call("deleteBot", body("botId" to id)) }
+ channel.close()
+ }
+ }
+
+ private fun openEditor() {
+ // The host event can arrive before the save callback closes the editor.
+ compose.chatAction("Edit group")
+ }
+
+ private fun rosterActions(name: String) {
+ compose.waitUntil(10_000) { compose.onAllNodes(hasText(name) and hasClickAction()).fetchSemanticsNodes().size == 1 }
+ compose.onNode(hasText(name) and hasClickAction()).performTouchInput { longClick() }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveMemoryTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveMemoryTest.kt
new file mode 100644
index 00000000..47a2bb93
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveMemoryTest.kt
@@ -0,0 +1,60 @@
+package com.codync.android
+
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.lifecycle.ViewModelProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+
+/** The caller seeds and deletes a disposable bot on the isolated fake-agent host. */
+class LiveMemoryTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+
+ @Test fun forgettingFactsAndClearingMemoryPreserveTheConversation() {
+ val botId = InstrumentationRegistry.getArguments().getString("memoryBot")
+ assumeTrue(botId != null)
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ val local = LocalStore(context)
+ val computer = local.computers().single().copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly)
+ val channel = runBlocking { HostConnector.connect(computer, local.identity()) }
+ try {
+ val before = runBlocking { channel.call("history", body("botId" to botId)) }
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ compose.waitUntil(30_000) { store.state.value.bots.any { it.id == botId } }
+ assertTrue(store.state.value.bots.single { it.id == botId }.name.startsWith("Android memory acceptance"))
+ compose.runOnUiThread { store.openBot(botId) }
+ compose.chatAction("Edit profile")
+ val profile = "Android memory profile acceptance"
+ compose.waitUntil(30_000) { compose.onAllNodesWithText(profile).fetchSemanticsNodes().size == 1 }
+ compose.onNodeWithText("Android memory history acceptance").performScrollTo().assertIsDisplayed()
+ // Searching leaves one fact, so its menu is the only one.
+ val search = hasSetTextAction() and hasText("Search memories")
+ compose.onNode(search).performScrollTo().performTextInput("profile")
+ compose.waitUntil(30_000) { compose.onAllNodesWithContentDescription("Memory actions").fetchSemanticsNodes().size == 1 }
+ compose.onNodeWithContentDescription("Memory actions").performScrollTo().performClick()
+ compose.onNodeWithText("Forget").performClick()
+ compose.waitUntil(30_000) { compose.onAllNodesWithText(profile).fetchSemanticsNodes().isEmpty() }
+ compose.onNode(hasSetTextAction() and hasText("profile")).performTextReplacement("")
+ compose.waitUntil(30_000) { compose.onAllNodesWithText("Android memory history acceptance").fetchSemanticsNodes().size == 1 }
+ val left = MemoryListing.decode(runBlocking { channel.call("memory", body("botId" to botId)) }).facts
+ assertEquals("Android memory history acceptance", left.single().content)
+ compose.onNodeWithContentDescription("More").performScrollTo().performClick()
+ compose.onNodeWithText("Forget everything").performClick()
+ compose.onNodeWithText("Forget everything this bot remembers?").assertIsDisplayed()
+ compose.onNodeWithText("Forget everything").performClick()
+ compose.waitUntil(30_000) {
+ compose.onAllNodesWithText("Nothing yet. Important details are remembered as you chat.").fetchSemanticsNodes().size == 1
+ }
+ val after = runBlocking { channel.call("history", body("botId" to botId)) }
+ assertEquals(before.jsonObject.getValue("entries"), after.jsonObject.getValue("entries"))
+ val memory = runBlocking { channel.call("memory", body("botId" to botId)) }
+ assertTrue(MemoryListing.decode(memory).facts.isEmpty())
+ } finally { channel.close() }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LivePluginsTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LivePluginsTest.kt
new file mode 100644
index 00000000..d2e7c025
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LivePluginsTest.kt
@@ -0,0 +1,93 @@
+package com.codync.android
+
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.lifecycle.ViewModelProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import java.util.UUID
+
+/** Installs inert fixture plugins only on the disposable host and restores its original bot choices. */
+class LivePluginsTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+ @Test fun customConnectorsAndSkillsInstallAndRemoveThroughTheRealHost() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("liveHost") == "true")
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ assertNull(PushPreferences.activeUser(context))
+ val local = LocalStore(context)
+ val computer = local.computers().single()
+ requireFixtureHost(computer.id)
+ val route = computer.copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly)
+ val channel = runBlocking { HostConnector.connect(route, local.identity()) }
+ val original = runBlocking { HostClient.bots(channel) }
+ var connectorId: String? = null; var skillId: String? = null
+ val name = "Fixture " + UUID.randomUUID().toString().take(8)
+ try {
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.actualConnection is LinkState.Ready }
+ compose.runOnUiThread { store.openBot(null) }
+ compose.openExtensions()
+ compose.onNodeWithText("Custom connector").performScrollTo().performClick()
+ field("Name").performTextReplacement(name + " connector")
+ field("npx -y @scope/server").performTextReplacement("/usr/bin/false")
+ field("API_KEY=…").performTextReplacement("FIXTURE_ONLY=fixture-value")
+ compose.onNodeWithContentDescription("Add").assertIsEnabled().performClick()
+ compose.waitUntil(20_000) { runBlocking { channel.call("connectors") }.toString().contains(name + " connector") }
+ compose.onNodeWithText("Your own skill").performScrollTo().performClick()
+ field("Name").performTextReplacement(name + " skill")
+ field("When to use it").performTextReplacement("Disposable acceptance instructions")
+ field("Step by step, in plain words…").performTextReplacement("This skill belongs to the isolated Android acceptance fixture.")
+ compose.onNodeWithContentDescription("Save").assertIsEnabled().performClick()
+ compose.runOnUiThread { store.refreshPlugins() }
+ compose.waitUntil(20_000) { store.state.value.plugins?.let { plugins -> plugins.connectors.any { it.name == name + " connector" } &&
+ plugins.skills.any { it.name == name + " skill" } } == true && "plugins" !in store.state.value.busy }
+ val connector = store.state.value.plugins!!.connectors.single { it.name == name + " connector" }
+ connectorId = connector.id
+ assertTrue(connector.keys.contains("FIXTURE_ONLY"))
+ assertEquals("local", connector.kind)
+ assertFalse(WireJson.encodeToJsonElement(connector).toString().contains("fixture-value"))
+ val skill = store.state.value.plugins!!.skills.single { it.name == name + " skill" }
+ skillId = skill.id
+ // Installed connectors and skills, each removable after a confirmation.
+ compose.onNodeWithText("Connectors & skills").performScrollTo().performClick()
+ compose.onNodeWithContentDescription("Remove " + skill.name).performScrollTo().performClick()
+ compose.onNodeWithText("Remove ${skill.name}?").assertIsDisplayed()
+ compose.onNodeWithText("Cancel").performClick()
+ assertTrue(store.state.value.plugins!!.skills.any { it.id == skill.id })
+ compose.onNodeWithContentDescription("Remove " + skill.name).performScrollTo().performClick()
+ compose.onNodeWithText("Remove").performClick()
+ compose.waitUntil(15_000) { store.state.value.plugins?.skills?.none { it.id == skill.id } == true }
+ skillId = null
+ compose.onNodeWithContentDescription("Remove " + connector.name).performScrollTo().performClick()
+ compose.onNodeWithText("Remove").performClick()
+ compose.waitUntil(15_000) { store.state.value.plugins?.connectors?.none { it.id == connector.id } == true }
+ connectorId = null
+ assertNull(store.state.value.error)
+ } finally {
+ runBlocking {
+ // Find by fixture name as well, so an assertion before capturing the id still cleans up.
+ val connectorResponse = channel.call("connectors")
+ val connectors = WireJson.decodeFromJsonElement<List<InstalledConnector>>(connectorResponse.jsonObject.getValue("items"))
+ for (connector in connectors.filter { it.id == connectorId || it.name == name + " connector" }) channel.call("removeConnector", body("id" to connector.id))
+ val skillResponse = channel.call("skills")
+ val skills = WireJson.decodeFromJsonElement<List<InstalledSkill>>(skillResponse.jsonObject.getValue("items"))
+ for (skill in skills.filter { it.id == skillId || it.name == name + " skill" }) channel.call("removeSkill", body("id" to skill.id))
+ // The existing host enables newly installed connectors on its bots.
+ val remainingBots = HostClient.bots(channel)
+ val remaining = remainingBots.map { it.id }.toSet()
+ for (bot in original.filter { it.id in remaining }) channel.call("updateBot", buildJsonObject {
+ put("id", bot.id); put("connectors", WireJson.encodeToJsonElement(bot.connectors)); put("skills", WireJson.encodeToJsonElement(bot.skills))
+ })
+ }
+ channel.close()
+ }
+ }
+ /** Extensions fields are labeled by their prompt. */
+ private fun field(prompt: String): SemanticsNodeInteraction = compose.onNode(hasSetTextAction() and hasContentDescription(prompt)).performScrollTo()
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRosterTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRosterTest.kt
new file mode 100644
index 00000000..9a53a025
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRosterTest.kt
@@ -0,0 +1,101 @@
+package com.codync.android
+
+import androidx.test.platform.app.InstrumentationRegistry
+import androidx.test.core.app.ActivityScenario
+import androidx.lifecycle.ViewModelProvider
+import com.codync.android.core.HostClient
+import com.codync.android.core.HostConnector
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.long
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import java.io.File
+import org.junit.Assert.assertTrue
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+
+/** Explicit, read-only connection probe. Does not reset identity, accounts, mirrors or host data. */
+class LiveRosterTest {
+ @Test fun anExistingAccountConnectionReturnsItsCurrentRoster() {
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ assumeTrue(InstrumentationRegistry.getArguments().getString("inspectHost") == "true")
+ val context = instrumentation.targetContext
+ val local = LocalStore(context, PushPreferences.activeUser(context) ?: "local")
+ assertTrue("An existing identity is required", local.hasIdentity())
+ val computer = local.computers().first()
+ runBlocking {
+ withTimeout(45_000) {
+ val identity = local.identity()
+ val channel = HostConnector.connect(computer, identity)
+ try {
+ HostClient.hello(channel, computer)
+ val roster = HostClient.bots(channel)
+ assertTrue("The selected host must contain a bot for this opt-in probe", roster.isNotEmpty())
+ println("Read-only host roster: ${roster.size} bots via ${channel.route}")
+ } finally { channel.close() }
+ }
+ }
+ }
+
+ @Test fun anExistingAccountSyncPopulatesItsLocalMirror() {
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ assumeTrue(InstrumentationRegistry.getArguments().getString("inspectMirror") == "true")
+ val user = PushPreferences.activeUser(instrumentation.targetContext)
+ val expectedContext = LocalStore.referenceId(user ?: "local")
+ ActivityScenario.launch(MainActivity::class.java).use { scenario ->
+ var model: AppStore? = null
+ scenario.onActivity { activity ->
+ val store = ViewModelProvider(activity)[AppStore::class.java]
+ model = store
+ // A locked test phone may stop the Activity while we inspect sync independently.
+ store.setForeground(true)
+ }
+ val store = requireNotNull(model)
+ try {
+ runBlocking {
+ withTimeout(60_000) {
+ store.state.first { !it.loading && it.contextId == expectedContext && (user == null || it.account.ready) }
+ val synced = store.state.first { it.rosterLoaded && it.bots.isNotEmpty() }
+ println("Account mirror populated: ${synced.bots.size} bots")
+ if (InstrumentationRegistry.getArguments().getString("inspectCatchup") == "true") {
+ val head = requireNotNull(synced.hello).getValue("rev").jsonPrimitive.long
+ val local = LocalStore(instrumentation.targetContext, user ?: "local")
+ MirrorDatabase(instrumentation.targetContext, local.directory, synced.computers.first().id).use { mirror ->
+ while (withContext(Dispatchers.IO) { mirror.revision() } < head) delay(100)
+ println("Account mirror committed catch-up through the host head")
+ }
+ }
+ }
+ }
+ } finally { instrumentation.runOnMainSync { store.setForeground(false) } }
+ }
+ }
+
+ @Test fun anExistingDeviceProvidesAPrivatePushAcceptanceDestination() {
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ assumeTrue(InstrumentationRegistry.getArguments().getString("inspectPush") == "true")
+ val context = instrumentation.targetContext
+ val local = LocalStore(context, PushPreferences.activeUser(context) ?: "local")
+ assertTrue("An existing identity is required", local.hasIdentity())
+ val computer = local.computers().first()
+ val bot = MirrorDatabase(context, local.directory, computer.id).use { it.snapshot().bots.first() }
+ val permitted = context.getSystemService(android.app.NotificationManager::class.java).areNotificationsEnabled()
+ assertTrue("Enable notifications in the phone's app settings before physical push acceptance", permitted)
+ assertTrue("Enable bot notifications in Codync before push acceptance", PushPreferences.enabled(context))
+ val destination = buildJsonObject {
+ put("fid", requireNotNull(PushPreferences.fid(context)))
+ put("pushKey", local.identity().pushKey)
+ put("ctx", local.referenceId)
+ put("computerId", computer.id)
+ put("botId", bot.id)
+ }
+ // No seeds, credentials or opaque tickets leave the device. The controller deletes this file after reading.
+ File(context.cacheDir, "android-push-acceptance.json").writeText(destination.toString())
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutinesTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutinesTest.kt
new file mode 100644
index 00000000..7376f9e6
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutinesTest.kt
@@ -0,0 +1,142 @@
+package com.codync.android
+
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.lifecycle.ViewModelProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import java.util.UUID
+
+/** Opt-in isolated fake-agent fixture. All routines belong to a disposable clone. */
+class LiveRoutinesTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+
+ @Test fun routinesPreserveSchedulesAndPausedStateAndManageWebhookKeys() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("liveHost") == "true")
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ val local = LocalStore(context)
+ assertNull(PushPreferences.activeUser(context))
+ val computer = local.computers().single()
+ requireFixtureHost(computer.id)
+ val route = computer.copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly)
+ val channel = runBlocking { HostConnector.connect(route, local.identity()) }
+ var clone: Bot? = null
+ try {
+ val bots = runBlocking { HostClient.bots(channel) }
+ val parent = bots.single { it.name == "Android chat acceptance" }
+ val response = runBlocking { channel.call("createBot", BotDraft.from(parent).copy(id = null, name = "Routine acceptance " + UUID.randomUUID().toString().take(6), permission = "auto").body()) }
+ val bot = HostClient.decode(response.jsonObject.getValue("bot").jsonObject)
+ clone = bot
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.bots.any { it.id == bot.id } }
+ compose.runOnUiThread { store.refreshUsage(false) }
+ compose.waitUntil(15_000) { "usage" !in store.state.value.busy }
+ assertNull(store.state.value.error)
+ compose.runOnUiThread { store.openBot(bot.id) }
+ compose.chatAction("Routines")
+ compose.onNodeWithContentDescription("Ask the bot for a routine").performClick()
+ compose.waitUntil(10_000) { compose.onAllNodes(hasSetTextAction() and hasText("I want a routine that ")).fetchSemanticsNodes().size == 1 }
+ compose.runOnUiThread { store.editDraft(bot.id, null, "") }
+ compose.chatAction("Routines")
+ compose.waitUntil(10_000) { "routines:${bot.id}" !in store.state.value.busy && store.state.value.routines[bot.id] != null }
+ compose.onNodeWithText("No routines yet. Ask the bot for one, or set it up yourself with +.").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Set up a routine").performClick()
+ field(Input.Name).performTextReplacement("Schedule acceptance")
+ field(Input.Instruction).performTextReplacement("Report a fake-agent acceptance result")
+ field(Input.Cron).performTextReplacement("invalid cron")
+ compose.waitUntil(10_000) { compose.onAllNodesWithText("Check schedule again").fetchSemanticsNodes().isNotEmpty() }
+ compose.onNodeWithText("Create routine").assertIsNotEnabled()
+ field(Input.Cron).performTextReplacement("0 0 1 1 *")
+ field(Input.Zone).performTextReplacement("America/New_York")
+ waitEnabled("Create routine")
+ compose.onNodeWithText("Create routine").performClick()
+ compose.waitUntil(15_000) { store.state.value.routines[bot.id]?.routines?.size == 1 && "routines:${bot.id}" !in store.state.value.busy }
+ val schedule = store.state.value.routines.getValue(bot.id).routines.single()
+ val originalNext = schedule.nextRunAt
+ // Each row's switch pauses and resumes it.
+ toggle("Schedule acceptance").assertIsOn().performClick()
+ compose.waitUntil(15_000) { store.state.value.routines.getValue(bot.id).routines.single().enabled == false && "routines:${bot.id}" !in store.state.value.busy }
+ compose.onNodeWithText("Schedule acceptance").performClick()
+ compose.onNodeWithText("Edit routine").assertIsDisplayed()
+ field(Input.Name).performTextReplacement("Edited schedule")
+ waitEnabled("Save changes")
+ compose.onNodeWithText("Save changes").performClick()
+ try { compose.waitUntil(15_000) { store.state.value.routines.getValue(bot.id).routines.single().name == "Edited schedule" && "routines:${bot.id}" !in store.state.value.busy } }
+ catch (_: Throwable) { throw AssertionError("Routine save failed: ${store.state.value.error}; names=${store.state.value.routines[bot.id]?.routines?.map { it.name }}; busy=${store.state.value.busy}") }
+ val edited = store.state.value.routines.getValue(bot.id).routines.single()
+ assertFalse(edited.enabled)
+ assertEquals(schedule.triggers, edited.triggers)
+ toggle("Edited schedule").assertIsOff().performClick()
+ compose.waitUntil(15_000) { store.state.value.routines.getValue(bot.id).routines.single().enabled && "routines:${bot.id}" !in store.state.value.busy }
+ assertEquals(originalNext, store.state.value.routines.getValue(bot.id).routines.single().nextRunAt)
+
+ // Unsupported multiple triggers and filters survive an unrelated edit, even paused.
+ val triggers = WireJson.parseToJsonElement("""[{"type":"event","source":"github","event":"pull_request.opened","filters":{"repo":"org/project"}},{"type":"interval","seconds":31536000}]""").jsonArray
+ val original = runBlocking { channel.call("saveRoutine", buildJsonObject {
+ put("botId", bot.id); put("name", "Preserve triggers"); put("instruction", "Keep the original filters")
+ put("triggers", triggers); put("enabled", false)
+ }) }.jsonObject.getValue("routine").jsonObject
+ compose.waitUntil(15_000) { store.state.value.routines.getValue(bot.id).routines.size == 2 && "routines:${bot.id}" !in store.state.value.busy }
+ compose.onNodeWithText("Preserve triggers").performClick()
+ field(Input.Name).performTextReplacement("Preserved triggers")
+ waitEnabled("Save changes")
+ compose.onNodeWithText("Save changes").performClick()
+ try { compose.waitUntil(15_000) { store.state.value.routines.getValue(bot.id).routines.any { it.name == "Preserved triggers" } && "routines:${bot.id}" !in store.state.value.busy } }
+ catch (_: Throwable) { throw AssertionError("Trigger-preserving save failed: ${store.state.value.error}; names=${store.state.value.routines[bot.id]?.routines?.map { it.name }}") }
+ val preserved = store.state.value.routines.getValue(bot.id).routines.single { it.name == "Preserved triggers" }
+ assertEquals(original.getValue("triggers"), JsonArray(preserved.triggers))
+ assertFalse(preserved.enabled)
+
+ // A new webhook routine stays open on its URL and key.
+ compose.onNodeWithContentDescription("Set up a routine").performClick()
+ field(Input.Name).performTextReplacement("Webhook acceptance")
+ field(Input.Instruction).performTextReplacement("Report a fake webhook acceptance result")
+ compose.onNodeWithContentDescription("When to run: Schedule").performScrollTo().performClick()
+ compose.onNodeWithText("Webhook").performClick()
+ waitEnabled("Create routine")
+ compose.onNodeWithText("Create routine").performClick()
+ compose.waitUntil(15_000) { compose.onAllNodesWithContentDescription("Replace key").fetchSemanticsNodes().isNotEmpty() }
+ val webhookRoutine = store.state.value.routines.getValue(bot.id).routines.single { it.name == "Webhook acceptance" }
+ val firstKey = runBlocking { channel.call("routineWebhook", body("botId" to bot.id, "id" to webhookRoutine.id)) }.jsonObject.getValue("key")
+ compose.onNodeWithContentDescription("Replace key").performScrollTo().performClick()
+ compose.onNodeWithText("Replace the key?").assertIsDisplayed()
+ compose.onNodeWithText("Replace key").performClick()
+ compose.waitUntil(15_000) { compose.onAllNodesWithContentDescription("Hide key").fetchSemanticsNodes().isNotEmpty() }
+ val nextKey = runBlocking { channel.call("routineWebhook", body("botId" to bot.id, "id" to webhookRoutine.id)) }.jsonObject.getValue("key")
+ assertNotEquals(firstKey, nextKey)
+ compose.onNodeWithContentDescription("Test run").performClick()
+ compose.waitUntil(15_000) { compose.onAllNodesWithContentDescription("Started").fetchSemanticsNodes().isNotEmpty() }
+ compose.waitUntil(30_000) { store.state.value.routines.getValue(bot.id).runs.any { it.routineId == webhookRoutine.id && it.finishedAt != null } }
+ val run = store.state.value.routines.getValue(bot.id).runs.first { it.routineId == webhookRoutine.id }
+ assertEquals("succeeded", run.status)
+ assertNotNull(run.rootId)
+ compose.onNodeWithContentDescription("Delete routine").performClick()
+ compose.onNodeWithText("Delete routine?").assertIsDisplayed()
+ compose.onNodeWithText("Delete routine").performClick()
+ compose.waitUntil(15_000) { store.state.value.routines.getValue(bot.id).routines.none { it.id == webhookRoutine.id } }
+ compose.onNodeWithText("Webhook acceptance").assertDoesNotExist()
+ } finally {
+ clone?.let { bot -> runBlocking { channel.call("deleteBot", body("botId" to bot.id)) } }
+ channel.close()
+ }
+ }
+
+ private enum class Input { Name, Instruction, Cron, Zone }
+
+ /** The open editor's text fields, top to bottom: name, instruction, then a schedule's cron and time zone. */
+ private fun field(field: Input): SemanticsNodeInteraction {
+ val inEditor = hasSetTextAction() and hasAnyAncestor(hasScrollAction() and hasAnyDescendant(hasText("When to run")))
+ compose.waitUntil(10_000) { compose.onAllNodes(inEditor and isEnabled()).fetchSemanticsNodes().size > field.ordinal }
+ return compose.onAllNodes(inEditor)[field.ordinal].performScrollTo()
+ }
+ private fun toggle(routine: String) = compose.onNode(hasContentDescription(routine) and isToggleable())
+ private fun waitEnabled(label: String) {
+ compose.waitUntil(10_000) { compose.onAllNodes(hasText(label) and isEnabled()).fetchSemanticsNodes().size == 1 }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutingTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutingTest.kt
new file mode 100644
index 00000000..918aa33a
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutingTest.kt
@@ -0,0 +1,94 @@
+package com.codync.android
+
+import android.content.Intent
+import android.net.Uri
+import androidx.test.core.app.ActivityScenario
+import androidx.test.platform.app.InstrumentationRegistry
+import androidx.lifecycle.ViewModelProvider
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createEmptyComposeRule
+import com.codync.android.core.*
+import java.io.File
+import java.util.UUID
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.first
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+import org.junit.Rule
+
+/** Controller OS-kills the emulator between phases. Never touches user identities or real bots. */
+class LiveRoutingTest {
+ @get:Rule val compose = createEmptyComposeRule()
+ @Test fun coldNotificationFindsAnUncachedBotAndRejectsOtherContexts() {
+ val phase = InstrumentationRegistry.getArguments().getString("routePhase")
+ assumeTrue(phase in listOf("prepare", "restore"))
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ val context = instrumentation.targetContext
+ assertNull(PushPreferences.activeUser(context))
+ val local = LocalStore(context)
+ val computer = local.computers().single()
+ requireFixtureHost(computer.id)
+ val metadata = File(context.cacheDir, "route-acceptance.json")
+ val route = computer.copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly)
+ runBlocking {
+ val channel = HostConnector.connect(route, local.identity())
+ try {
+ if (phase == "prepare") {
+ // No Activity owns a sync channel while we create this new fixture bot.
+ val bots = HostClient.bots(channel)
+ val parent = bots.single { it.name == "Android chat acceptance" }
+ val response = channel.call("createBot", BotDraft.from(parent).copy(id = null, name = "Routing acceptance " + UUID.randomUUID().toString().take(6)).body())
+ val bot = HostClient.decode(response.jsonObject.getValue("bot").jsonObject)
+ val cached = MirrorDatabase(context, local.directory, computer.id).use { it.snapshot().bots }
+ assertFalse(cached.any { it.id == bot.id })
+ metadata.writeText(buildJsonObject { put("bot", bot.id); put("parent", parent.id) }.toString())
+ return@runBlocking
+ }
+ val saved = Json.parseToJsonElement(metadata.readText()).jsonObject
+ val bot = saved.getValue("bot").jsonPrimitive.content
+ fun link(id: String = bot, scope: String = "local", cid: String = computer.id): Uri = Uri.Builder().scheme("codync").authority("bot").appendPath(id)
+ .appendQueryParameter("scope", scope).appendQueryParameter("computer", cid).build()
+ try {
+ val intent = Intent(Intent.ACTION_VIEW, link(), context, MainActivity::class.java)
+ ActivityScenario.launch<MainActivity>(intent).use { scenario ->
+ var model: AppStore? = null
+ scenario.onActivity { model = ViewModelProvider(it)[AppStore::class.java] }
+ val store = requireNotNull(model)
+ withTimeout(35_000) { store.state.first { !it.loading && it.contextId == "local" && it.selectedBot == bot } }
+ assertNull(store.state.value.account.userId)
+ assertNull(store.state.value.error)
+ suspend fun reject(uri: Uri, message: String) {
+ instrumentation.runOnMainSync { store.openBot(null); store.clearError(); store.openLink(uri) }
+ withTimeout(15_000) { store.state.first { it.error?.contains(message) == true } }
+ assertNull(store.state.value.selectedBot)
+ assertEquals("local", store.state.value.contextId)
+ assertNull(store.state.value.account.userId)
+ }
+ reject(link(scope = "a".repeat(64)), "Switch to the account")
+ reject(link(cid = "AAAAAAAAAAAAAAAAAAAAAA"), "computer is no longer paired")
+ reject(link(id = "absent-" + UUID.randomUUID()), "bot is no longer available")
+ reject(Uri.parse(link().toString() + "&scope=local"), "invalid destination")
+ val parent = saved.getValue("parent").jsonPrimitive.content
+ // Usage opens from the State tab.
+ compose.onNode(hasText("State") and isSelectable()).performClick()
+ compose.onNodeWithContentDescription("Usage limits").performClick()
+ val usage = hasText("Usage") and isHeading()
+ compose.waitUntil(10_000) { compose.onAllNodes(usage).fetchSemanticsNodes().size == 1 }
+ instrumentation.runOnMainSync { store.openLink(link(id = parent)) }
+ withTimeout(10_000) { store.state.first { it.selectedBot == parent && it.error == null } }
+ compose.onNode(chatMenu).assertIsDisplayed()
+ // Recreating the Activity must retain the current navigation, not replay its original intent.
+ scenario.recreate()
+ scenario.onActivity { activity ->
+ val retained = ViewModelProvider(activity)[AppStore::class.java]
+ assertSame(store, retained)
+ assertEquals(parent, retained.state.value.selectedBot)
+ }
+ }
+ } finally { channel.call("deleteBot", body("botId" to bot)); metadata.delete() }
+ } finally { channel.close() }
+ }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveSettingsTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveSettingsTest.kt
new file mode 100644
index 00000000..c3a840ca
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveSettingsTest.kt
@@ -0,0 +1,84 @@
+package com.codync.android
+
+import android.os.Build
+import android.view.KeyEvent
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.lifecycle.ViewModelProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import java.util.UUID
+
+/** A disposable bot on the isolated fake-agent host; no actual agent work is started. */
+class LiveSettingsTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+ @Test fun botSettingsSaveAHostFolderAndTurnDefaultNotificationsOff() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("liveHost") == "true")
+ assumeTrue(Build.PRODUCT.startsWith("sdk"))
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ assertNull(PushPreferences.activeUser(context))
+ val local = LocalStore(context)
+ val computer = local.computers().single()
+ requireFixtureHost(computer.id)
+ val route = computer.copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly)
+ val channel = runBlocking { HostConnector.connect(route, local.identity()) }
+ var clone: String? = null
+ try {
+ val bots = runBlocking { HostClient.bots(channel) }
+ val parent = bots.single { it.name == "Android chat acceptance" }
+ val response = runBlocking { channel.call("createBot", BotDraft.from(parent).copy(id = null,
+ name = "Settings acceptance " + UUID.randomUUID().toString().take(6), cwd = "/tmp", notify = null).body()) }
+ val bot = HostClient.decode(response.jsonObject.getValue("bot").jsonObject)
+ clone = bot.id
+ val listingResponse = runBlocking { channel.call("listDirs", body("path" to "/tmp")) }
+ val listing = WireJson.decodeFromJsonElement<DirListing>(listingResponse)
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.bots.any { it.id == bot.id } && store.state.value.actualConnection is LinkState.Ready }
+ compose.runOnUiThread { store.openBot(bot.id) }
+ compose.chatAction("Edit profile")
+ compose.onNode(hasSetTextAction() and hasText(bot.name)).performTextReplacement("Unsaved draft")
+ compose.onNodeWithContentDescription("Workspace").performScrollTo().performClick()
+ compose.onNodeWithText("Choose project folder…").performClick()
+ val useFolder = "Use “${listing.path.trimEnd('/').substringAfterLast('/').ifEmpty { "/" }}”"
+ compose.waitUntil(15_000) { compose.onAllNodesWithText(useFolder).fetchSemanticsNodes().size == 1 }
+ InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)
+ compose.waitUntil(5_000) { compose.onAllNodesWithText(useFolder).fetchSemanticsNodes().isEmpty() }
+ compose.onNode(hasSetTextAction() and hasText("Unsaved draft")).performScrollTo().assertIsDisplayed()
+ compose.onNodeWithContentDescription("Close").performClick()
+ compose.waitUntil(5_000) { compose.onAllNodesWithText("Settings").fetchSemanticsNodes().isEmpty() }
+ val cancelledBots = runBlocking { HostClient.bots(channel) }
+ val cancelled = cancelledBots.single { it.id == bot.id }
+ assertEquals(bot.name, cancelled.name)
+ assertEquals(bot.cwd, cancelled.cwd)
+ assertNull(cancelled.notify)
+ compose.chatAction("Edit profile")
+ compose.onNodeWithContentDescription("Workspace").performScrollTo().performClick()
+ compose.onNodeWithText("Choose project folder…").performClick()
+ compose.waitUntil(15_000) { compose.onAllNodesWithText(useFolder).fetchSemanticsNodes().size == 1 }
+ compose.onNodeWithText(useFolder).performClick()
+ compose.waitUntil(5_000) { compose.onAllNodesWithText(useFolder).fetchSemanticsNodes().isEmpty() }
+ compose.onNodeWithContentDescription("Workspace").assert(hasText(listing.path.trimEnd('/').substringAfterLast('/')))
+ compose.onNode(hasText("Notifications") and isToggleable()).performScrollTo().assertIsOn().performClick().assertIsOff()
+ compose.onNodeWithContentDescription("Save").performClick()
+ compose.waitUntil(15_000) { store.state.value.bots.firstOrNull { it.id == bot.id }?.let { it.notify == false && it.cwd == listing.path } == true && "editor" !in store.state.value.busy }
+ val finalBots = runBlocking { HostClient.bots(channel) }
+ val saved = finalBots.single { it.id == bot.id }
+ assertEquals(listing.path, saved.cwd)
+ assertEquals(false, saved.notify)
+ assertEquals(parent.command, saved.command)
+ assertEquals(parent.backend, saved.backend)
+ assertEquals(parent.connectors, saved.connectors)
+ assertEquals(parent.skills, saved.skills)
+ assertNull(store.state.value.error)
+ } finally {
+ clone?.let { id -> runBlocking { channel.call("deleteBot", body("botId" to id)) } }
+ channel.close()
+ }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveTerminalTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveTerminalTest.kt
new file mode 100644
index 00000000..44780772
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveTerminalTest.kt
@@ -0,0 +1,134 @@
+package com.codync.android
+
+import android.view.View
+import android.view.ViewGroup
+import android.webkit.WebView
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.lifecycle.ViewModelProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.first
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import kotlin.coroutines.resume
+
+/** Opt-in inert ACP provider, real host PTY. Never starts a real provider's login. */
+class LiveTerminalTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+ @Test fun agentKeysStayOnTheHostAndCanBePreservedOrRemoved() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("liveSetupKeys") == "true")
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ assertNull(PushPreferences.activeUser(context))
+ val local = LocalStore(context)
+ val computer = local.computers().single()
+ requireFixtureHost(computer.id)
+ runBlocking {
+ val channel = HostConnector.connect(computer.copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly), local.identity())
+ val backend = "android-setup-fixture"
+ fun keys(values: Map<String, String>) = buildJsonObject { put("backend", backend); put("vars", WireJson.encodeToJsonElement(values)) }
+ try {
+ val before = channel.call("agentAuth", body("backend" to backend))
+ val initial = WireJson.decodeFromJsonElement<AgentAuth>(before)
+ assertEquals(false, initial.signedIn)
+ assertTrue(initial.savedEnv.isEmpty())
+ assertTrue(initial.methods.any { it.kind == "envVar" && it.vars.any { field -> field.name == "CODYNC_ACCEPTANCE_KEY" } })
+ val saved = channel.call("setAgentEnv", keys(mapOf("CODYNC_ACCEPTANCE_KEY" to "fixture-key")))
+ val status = WireJson.decodeFromJsonElement<AgentAuth>(saved)
+ assertEquals(true, status.signedIn)
+ assertEquals(listOf("CODYNC_ACCEPTANCE_KEY"), status.savedEnv)
+ assertFalse(saved.toString().contains("\"fixture-key\""))
+ assertFalse(status.detail.orEmpty().contains("fixture-key"))
+ val preserved = channel.call("setAgentEnv", keys(emptyMap()))
+ assertEquals(true, WireJson.decodeFromJsonElement<AgentAuth>(preserved).signedIn)
+ val removed = channel.call("setAgentEnv", keys(mapOf("CODYNC_ACCEPTANCE_KEY" to "")))
+ val final = WireJson.decodeFromJsonElement<AgentAuth>(removed)
+ assertEquals(false, final.signedIn)
+ assertTrue(final.savedEnv.isEmpty())
+ } finally {
+ try { channel.call("setAgentEnv", keys(mapOf("CODYNC_ACCEPTANCE_KEY" to "")), 2_000) }
+ finally { channel.close() }
+ }
+ }
+ }
+ @Test fun aRealSetupTerminalClosesOnBackAndSurvivesRotationBeforeSignIn() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("liveSetup") == "true")
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ val context = instrumentation.targetContext
+ assertNull(PushPreferences.activeUser(context))
+ val local = LocalStore(context); val computer = local.computers().single()
+ requireFixtureHost(computer.id)
+ val channel = runBlocking { HostConnector.connect(computer.copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly), local.identity()) }
+ val setup = buildJsonObject { put("backend", "android-setup-fixture"); put("step", "login"); put("method", "fixture-terminal"); put("cols", 80); put("rows", 24) }
+ var term: String? = null
+ fun find(view: View): WebView? {
+ if (view is WebView) return view
+ if (view is ViewGroup) for (i in 0 until view.childCount) { val found = find(view.getChildAt(i)); if (found != null) return found }
+ return null
+ }
+ fun terminalText(): String = runBlocking { withContext(Dispatchers.Main) {
+ val view = find(compose.activity.window.decorView) ?: return@withContext ""
+ withTimeout(5_000) { suspendCancellableCoroutine { reply -> view.evaluateJavascript("typeof codyncTerminal === 'undefined' ? '' : codyncTerminal.text()") {
+ if (reply.isActive) reply.resume(Json.parseToJsonElement(it).jsonPrimitive.content)
+ } } }
+ } }
+ try {
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.actualConnection is LinkState.Ready }
+ compose.runOnUiThread { store.openBot(null); store.refreshBackends() }
+ compose.waitUntil(15_000) { store.state.value.hello?.get("backends")?.jsonArray?.any { it.jsonObject["id"]?.jsonPrimitive?.content == "android-setup-fixture" } == true }
+ compose.openExtensions()
+ compose.onNode(hasSetTextAction() and hasText("Search agents, connectors and skills")).performTextInput("Android setup fixture")
+ compose.onNode(hasSetTextAction() and hasText("Android setup fixture")).performImeAction()
+ compose.onNode(hasText("Android setup fixture") and hasClickAction() and !hasSetTextAction()).performScrollTo().performClick()
+ compose.waitUntil(20_000) { compose.onAllNodesWithText("Fixture terminal sign-in").fetchSemanticsNodes().size == 1 }
+ compose.onNodeWithText("Fixture terminal sign-in").performScrollTo().performClick()
+ compose.waitUntil(20_000) { terminalText().contains("Fixture setup ready: café 🐈") }
+ val first = runBlocking { channel.call("agentSetup", setup) }
+ term = first.jsonObject.getValue("term").jsonPrimitive.content
+ compose.onNodeWithContentDescription("Back").assertIsDisplayed().performClick()
+ compose.waitUntil(5_000) { compose.onAllNodesWithContentDescription("Check again").fetchSemanticsNodes().size == 1 }
+ runBlocking { withTimeout(10_000) {
+ while (true) {
+ try { channel.call("termInput", body("term" to term, "data" to "")); delay(100) }
+ catch (error: HostError) { assertTrue(error.message.contains("gone")); break }
+ }
+ } }
+ compose.waitUntil(20_000) { compose.onAllNodesWithText("Fixture terminal sign-in").fetchSemanticsNodes().size == 1 }
+ compose.onNodeWithText("Fixture terminal sign-in").performScrollTo().performClick()
+ compose.waitUntil(20_000) { terminalText().contains("Fixture setup ready: café 🐈") }
+ val second = runBlocking { channel.call("agentSetup", setup) }
+ term = second.jsonObject.getValue("term").jsonPrimitive.content
+ assertNotEquals(first.jsonObject.getValue("term").jsonPrimitive.content, term)
+ compose.activityRule.scenario.recreate()
+ compose.waitUntil(20_000) { terminalText().contains("Fixture setup ready: café 🐈") }
+ val afterRotation = runBlocking { channel.call("agentSetup", setup) }
+ assertEquals(term, afterRotation.jsonObject.getValue("term").jsonPrimitive.content)
+ compose.onNodeWithText("Keyboard").performClick()
+ instrumentation.waitForIdleSync()
+ android.os.SystemClock.sleep(500) // Wait for native IME attach before requesting its connection.
+ val committed = CompletableDeferred<Boolean>()
+ compose.runOnUiThread {
+ val view = requireNotNull(find(compose.activity.window.decorView))
+ val connection = requireNotNull(view.onCreateInputConnection(android.view.inputmethod.EditorInfo()))
+ val handler = connection.handler ?: android.os.Handler(android.os.Looper.getMainLooper())
+ handler.post { committed.complete(connection.commitText("fixture-answer", 1)) }
+ }
+ val delivered = runBlocking { withTimeout(5_000) { committed.await() } }
+ assertTrue(delivered)
+ compose.waitUntil(5_000) { terminalText().contains("fixture-answer") }
+ instrumentation.sendKeyDownUpSync(android.view.KeyEvent.KEYCODE_ENTER)
+ compose.waitUntil(15_000) { compose.onAllNodesWithText("Finished.").fetchSemanticsNodes().size == 1 }
+ assertTrue(terminalText().contains("Fixture answer accepted"))
+ compose.onNodeWithText("Done").performClick()
+ compose.waitUntil(20_000) { compose.onAllNodesWithText("Signed in.").fetchSemanticsNodes().size == 1 }
+ } finally {
+ try { term?.let { id -> runBlocking { channel.call("termClose", body("term" to id), 2_000) } } }
+ finally { channel.close() }
+ }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveThreadTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveThreadTest.kt
new file mode 100644
index 00000000..90c00cb9
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveThreadTest.kt
@@ -0,0 +1,112 @@
+package com.codync.android
+
+import android.graphics.Bitmap
+import android.os.Build
+import android.view.KeyEvent
+import androidx.compose.ui.graphics.asAndroidBitmap
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.lifecycle.ViewModelProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import java.io.File
+import java.util.UUID
+
+/** Isolated emulator host only: exercise the real reply entry point, drafts and wire routing. */
+class LiveThreadTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+
+ @Test fun replyPopoverKeepsItsOriginalAndDraftsAndSendsToTheThread() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("liveHost") == "true")
+ assumeTrue(Build.PRODUCT.startsWith("sdk"))
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ val local = LocalStore(context)
+ requireFixtureHost(local.computers().single().id)
+ assertNull(PushPreferences.activeUser(context))
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.rosterLoaded &&
+ store.state.value.bots.any { it.name == "Android chat acceptance" } }
+ val bot = store.state.value.bots.single { it.name == "Android chat acceptance" }
+ compose.runOnUiThread { store.openBot(bot.id) }
+ compose.waitUntil(10_000) { compose.onAllNodes(chatMenu).fetchSemanticsNodes().size == 1 }
+ val originalText = "Thread original acceptance " + UUID.randomUUID()
+ compose.onNode(hasSetTextAction()).performTextReplacement(originalText)
+ compose.onNodeWithContentDescription("Send").performClick()
+ compose.waitUntil(30_000) { compose.onAllNodesWithText("Allow once").fetchSemanticsNodes().isNotEmpty() }
+ compose.onNodeWithText("Allow once").performScrollTo().performClick()
+ var original: Entry? = null
+ compose.waitUntil(30_000) {
+ original = store.state.value.entries.firstOrNull { it.botId == bot.id && it.kind == "user" && it.text == originalText }
+ val root = original
+ root != null && store.state.value.entries.any { it.botId == bot.id && it.turn == root.turn && it.threadId == null && it.kind == "agent" && it.isChat }
+ }
+ val root = requireNotNull(original)
+ val mainDraft = "Unsent main-chat draft " + UUID.randomUUID()
+ val replyDraft = "Unsent thread draft " + UUID.randomUUID()
+ // The thread is a sheet over the chat, which stays underneath: its own copies come last.
+ val threadOpen = hasContentDescription("Close thread")
+ fun threadComposer() = compose.onAllNodes(hasSetTextAction()).onLast()
+ try {
+ compose.onNode(hasSetTextAction()).performTextReplacement(mainDraft)
+ compose.waitUntil(10_000) { store.state.value.drafts[ComposerDraft.lane(bot.id, null)]?.text == mainDraft }
+ fun openThread() {
+ compose.onNode(hasText(originalText) and hasClickAction()).performScrollTo().performTouchInput { longClick() }
+ compose.onNodeWithText("Reply in thread").performClick()
+ compose.waitUntil(30_000) { store.state.value.thread == root.id && compose.onAllNodes(threadOpen).fetchSemanticsNodes().size == 1 }
+ compose.onNodeWithText("Thread").assertIsDisplayed()
+ compose.onAllNodesWithText(originalText).onLast().assertIsDisplayed()
+ }
+ openThread()
+ compose.onNodeWithText("No replies yet").assertIsDisplayed()
+ compose.onNode(hasSetTextAction() and hasText("Reply…")).performTextReplacement(replyDraft)
+ compose.waitUntil(10_000) { store.state.value.drafts[ComposerDraft.lane(bot.id, root.id)]?.text == replyDraft }
+ compose.onNodeWithContentDescription("Close thread").performClick()
+ compose.waitUntil(10_000) { store.state.value.thread == null && compose.onAllNodes(threadOpen).fetchSemanticsNodes().isEmpty() }
+ compose.onNode(hasSetTextAction() and hasText(mainDraft)).assertIsDisplayed()
+ openThread()
+ compose.onNode(hasSetTextAction() and hasText(replyDraft)).assertIsDisplayed()
+ val replyText = "Thread reply acceptance " + UUID.randomUUID()
+ threadComposer().performTextReplacement(replyText)
+ compose.onAllNodesWithContentDescription("Send").onLast().performClick()
+ compose.waitUntil(30_000) { store.state.value.entries.any { it.botId == bot.id && it.threadId == root.id && it.kind == "permission" && it.status == "pending" } }
+ compose.onAllNodesWithText("Allow once").onLast().performScrollTo().performClick()
+ compose.waitUntil(30_000) { store.state.value.entries.any { it.botId == bot.id && it.threadId == root.id && it.kind == "agent" && it.isChat } }
+ val sent = store.state.value.entries.single { it.botId == bot.id && it.kind == "user" && it.text == replyText }
+ assertEquals(root.id, sent.threadId)
+ compose.onNodeWithText(replyText).assertIsDisplayed()
+ compose.onNodeWithText("No replies yet").assertDoesNotExist()
+ compose.onNode(hasSetTextAction() and hasText("Reply…")).assertIsDisplayed()
+ val final = store.state.value.entries.last { it.botId == bot.id && it.threadId == root.id && it.kind == "agent" && it.isChat }
+ compose.onAllNodes(hasText(final.text) and hasClickAction()).onLast().performTouchInput { longClick() }
+ compose.onNodeWithText("Show what it did").performClick()
+ compose.onNodeWithText("Full conversation").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Close").performClick()
+ compose.waitUntil(10_000) { !store.state.value.trace && compose.onAllNodesWithText("Full conversation").fetchSemanticsNodes().isEmpty() }
+ assertEquals(root.id, store.state.value.thread)
+ compose.onNodeWithText("Thread").assertIsDisplayed()
+ if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") == "true") {
+ val bitmap = compose.onRoot().captureToImage().asAndroidBitmap()
+ File(context.cacheDir, "thread-live-preview.png").outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ }
+ // Native Back dismisses the sheet and restores the unchanged main-chat draft.
+ InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)
+ compose.waitUntil(10_000) { store.state.value.thread == null && compose.onAllNodes(threadOpen).fetchSemanticsNodes().isEmpty() }
+ compose.onNode(hasSetTextAction() and hasText(mainDraft)).assertIsDisplayed()
+ compose.onNodeWithText(replyText).assertDoesNotExist()
+ val count = store.state.value.entries.single { it.id == root.id }.data.getValue("thread").jsonObject.getValue("count").jsonPrimitive.int
+ compose.onNodeWithContentDescription("View thread, $count ${if (count == 1) "reply" else "replies"}", substring = true)
+ .performScrollTo().performClick()
+ compose.waitUntil(10_000) { store.state.value.thread == root.id }
+ compose.onAllNodesWithText(originalText).onLast().assertIsDisplayed()
+ compose.onNodeWithContentDescription("Close thread").performClick()
+ compose.waitUntil(10_000) { store.state.value.thread == null }
+ } finally {
+ compose.runOnUiThread { store.openBot(bot.id); store.editDraft(bot.id, null, ""); store.editDraft(bot.id, root.id, "") }
+ }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceSpeechTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceSpeechTest.kt
new file mode 100644
index 00000000..c4376c9a
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceSpeechTest.kt
@@ -0,0 +1,91 @@
+package com.codync.android
+
+import android.os.Build
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.ViewModelProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import java.io.File
+import java.util.UUID
+import kotlinx.coroutines.*
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+
+/** The external emulator controller injects public fixture PCM, never a host microphone. */
+class LiveVoiceSpeechTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+ @Test fun repeatedBackgroundSpeechReachesTheHostAndFinalRepliesFinishPlayback() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("liveVoiceSpeech") == "true")
+ assertTrue("Speech fixtures belong on emulators", Build.PRODUCT.contains("sdk"))
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ val context = instrumentation.targetContext
+ assertNull(PushPreferences.activeUser(context))
+ val local = LocalStore(context); val computer = local.computers().single()
+ requireFixtureHost(computer.id)
+ val channel = runBlocking { HostConnector.connect(computer.copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly), local.identity()) }
+ val marker = File(context.cacheDir, "voice-speech-stage")
+ check(marker.parentFile!!.isDirectory || marker.parentFile!!.mkdirs())
+ val observed = File(context.cacheDir, "voice-speech-observed")
+ val originalSettings = VoicePreferences.load(context)
+ var botId: String? = null; var model: AppStore? = null
+ try {
+ val parent = runBlocking { HostClient.bots(channel) }.single { it.name == "Android chat acceptance" }
+ val source = WireJson.encodeToJsonElement(parent).jsonObject
+ val draft = buildJsonObject {
+ for (key in listOf("backend", "command", "cwd", "model")) source[key]?.let { put(key, it) }
+ put("name", "Android speech acceptance " + UUID.randomUUID().toString().take(8))
+ put("permission", "auto"); put("notify", false); put("connectors", JsonArray(emptyList())); put("skills", JsonArray(emptyList()))
+ }
+ val created = runBlocking { channel.call("createBot", draft) }
+ val id = created.jsonObject.getValue("bot").jsonObject.getValue("id").jsonPrimitive.content
+ botId = id
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]; model = store
+ compose.waitUntil(30_000) { store.state.value.bots.any { it.id == id } && store.state.value.actualConnection is LinkState.Ready }
+ compose.runOnUiThread { store.voiceSettings(VoiceSettings(2_500)); store.openBot(id) }
+ compose.onNodeWithContentDescription("Call").performClick()
+ compose.waitUntil(45_000) { store.state.value.voice?.state?.phase == VoicePhase.Listening || store.state.value.error != null }
+ assertNull(store.state.value.error)
+ val callId = requireNotNull(store.state.value.voice).id
+ compose.activityRule.scenario.moveToState(Lifecycle.State.CREATED)
+ for (turn in 1..2) {
+ marker.writeText(turn.toString())
+ runBlocking { withTimeout(60_000) {
+ while (true) {
+ val history = channel.call("history", body("botId" to id))
+ val entries = history.jsonObject.getValue("entries").jsonArray.map { Entry.decode(it.jsonObject) }
+ val users = entries.filter { it.kind == "user" && it.text.contains("one zero zero zero one") }
+ assertTrue("Recognition must not duplicate a turn", users.size <= turn)
+ val sent = users.getOrNull(turn - 1)
+ val reply = entries.firstOrNull { it.kind == "agent" && it.isChat && it.seq > (sent?.seq ?: Long.MAX_VALUE) }
+ val voice = store.state.value.voice
+ assertNotNull("Backgrounding must preserve the call", voice)
+ observed.writeText(buildJsonObject {
+ put("phase", voice?.state?.phase?.name); put("muted", voice?.state?.muted)
+ put("level", voice?.state?.level); put("heard", voice?.state?.heard)
+ put("said", voice?.state?.said); put("users", JsonArray(users.map { JsonPrimitive(it.text) }))
+ put("finals", entries.count { it.kind == "agent" && it.isChat })
+ }.toString())
+ if (sent != null && reply != null && voice?.state?.said == SpokenText.from(reply.text) && voice.state.phase == VoicePhase.Listening) {
+ assertEquals(callId, voice.id); break
+ }
+ assertNull(store.state.value.error)
+ delay(100)
+ }
+ } }
+ }
+ compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
+ compose.onNodeWithContentDescription("End call").performClick()
+ compose.waitUntil(10_000) { store.state.value.voice == null }
+ } finally {
+ marker.delete(); observed.delete()
+ compose.runOnUiThread { model?.endVoice(); model?.voiceSettings(originalSettings) }
+ botId?.let { id -> runBlocking { channel.call("deleteBot", body("botId" to id)) } }
+ channel.close()
+ }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceTest.kt
new file mode 100644
index 00000000..19ebae0a
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceTest.kt
@@ -0,0 +1,87 @@
+package com.codync.android
+
+import android.app.NotificationManager
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.ViewModelProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import java.util.UUID
+
+/** Actual foreground audio and host transport; no real account or provider credentials. */
+class LiveVoiceTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+ @Test fun aCallSurvivesRotationAndBackgroundThenEndsFromItsNotification() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("liveVoice") == "true")
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ assertNull(PushPreferences.activeUser(context))
+ val local = LocalStore(context); val computer = local.computers().single()
+ requireFixtureHost(computer.id)
+ val channel = runBlocking { HostConnector.connect(computer.copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly), local.identity()) }
+ val originalSettings = VoicePreferences.load(context)
+ var botId: String? = null
+ var model: AppStore? = null
+ try {
+ val parent = runBlocking { HostClient.bots(channel) }.single { it.name == "Android chat acceptance" }
+ val source = WireJson.encodeToJsonElement(parent).jsonObject
+ val draft = buildJsonObject {
+ for (key in listOf("backend", "command", "cwd", "model")) source[key]?.let { put(key, it) }
+ put("name", "Android voice acceptance " + UUID.randomUUID().toString().take(8))
+ put("permission", "auto"); put("notify", false); put("connectors", JsonArray(emptyList())); put("skills", JsonArray(emptyList()))
+ }
+ val created = runBlocking { channel.call("createBot", draft) }
+ val id = created.jsonObject.getValue("bot").jsonObject.getValue("id").jsonPrimitive.content
+ botId = id
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]; model = store
+ compose.waitUntil(30_000) { store.state.value.bots.any { it.id == id } && store.state.value.actualConnection is LinkState.Ready }
+ compose.runOnUiThread { store.openBot(id) }
+ compose.onNodeWithContentDescription("Call").performClick()
+ compose.waitUntil(45_000) { store.state.value.voice?.state?.phase == VoicePhase.Listening || store.state.value.error != null }
+ assertNull(store.state.value.error)
+ val call = requireNotNull(store.state.value.voice)
+ assertEquals("Offline English · Vosk", call.state.engine)
+ compose.activityRule.scenario.recreate()
+ compose.waitUntil(10_000) { store.state.value.voice?.id == call.id && compose.onAllNodesWithContentDescription("End call").fetchSemanticsNodes().size == 1 }
+ compose.onNodeWithContentDescription("Call settings").performClick()
+ compose.onNodeWithContentDescription("Send after a pause of:", substring = true).performClick()
+ compose.onNodeWithText("1 s").performClick()
+ compose.onNodeWithContentDescription("Reading speed:", substring = true).performClick()
+ compose.onNodeWithText("Faster").performClick()
+ compose.waitUntil { store.state.value.voice?.state?.settings == VoiceSettings(1_000, 1.12f) }
+ InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(android.view.KeyEvent.KEYCODE_BACK)
+ compose.waitUntil(5_000) { compose.onAllNodesWithText("Voice chat").fetchSemanticsNodes().isEmpty() }
+ compose.onNodeWithContentDescription("Mute").performClick()
+ compose.waitUntil { store.state.value.voice?.state?.muted == true }
+ compose.activityRule.scenario.moveToState(Lifecycle.State.CREATED)
+ runBlocking { delay(1_000); withTimeout(5_000) { store.installedConnectors() } }
+ assertEquals(call.id, store.state.value.voice?.id)
+ val notifications = context.getSystemService(NotificationManager::class.java)
+ val active = notifications.activeNotifications.single { it.id == 308 }
+ active.notification.actions.last().actionIntent.send()
+ compose.waitUntil(10_000) { store.state.value.voice == null && notifications.activeNotifications.none { it.id == 308 } }
+ runBlocking { withTimeout(10_000) {
+ while (true) {
+ val history = channel.call("history", body("botId" to id))
+ val calls = history.jsonObject.getValue("entries").jsonArray.filter { it.jsonObject["data"]?.jsonObject?.get("callSeconds") != null }
+ if (calls.isNotEmpty()) {
+ assertEquals(1, calls.size)
+ assertTrue(calls.single().jsonObject.getValue("data").jsonObject.getValue("callSeconds").jsonPrimitive.long >= 1); break
+ }
+ delay(100)
+ }
+ } }
+ compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
+ } finally {
+ compose.runOnUiThread { model?.endVoice(); model?.voiceSettings(originalSettings) }
+ botId?.let { id -> runBlocking { channel.call("deleteBot", body("botId" to id)) } }
+ channel.close()
+ }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LocalStoreTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LocalStoreTest.kt
new file mode 100644
index 00000000..7624005d
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LocalStoreTest.kt
@@ -0,0 +1,45 @@
+package com.codync.android
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.DeviceIdentity
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotEquals
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+class LocalStoreTest {
+ @Test fun identitySurvivesRecreationIsScopedAndChangesAfterReset() {
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ val scope = "test-${java.util.UUID.randomUUID()}"
+ val store = LocalStore(context, scope)
+ try {
+ val identity = store.identity()
+ assertEquals(identity.publicKey, LocalStore(context, scope).identity().publicKey)
+ val other = LocalStore(context, "$scope-other")
+ try { assertNotEquals(identity.publicKey, other.identity().publicKey) } finally { other.erase() }
+ store.completeSetup()
+ store.erase()
+ assertFalse(store.setupComplete())
+ assertNotEquals(identity.publicKey, store.identity().publicKey)
+ } finally { store.erase() }
+ }
+
+ @Test fun cryptoOpensTheSharedPushVectorOnAndroidWithoutARegisteredProvider() {
+ val assets = InstrumentationRegistry.getInstrumentation().context.assets
+ val fixture = assets.open("remote-relay-vectors.json").bufferedReader().use { Json.parseToJsonElement(it.readText()).jsonObject }
+ val keys = fixture.getValue("keys").jsonObject
+ val push = fixture.getValue("push").jsonObject
+ val identity = DeviceIdentity(ByteArray(32) { 3 }, ByteArray(32) { 12 })
+ assertEquals(keys.getValue("deviceSignPub").jsonPrimitive.content, identity.publicKey)
+ assertEquals(push.getValue("pushPub").jsonPrimitive.content, identity.pushKey)
+ val result = identity.openPush(push.getValue("sealed").jsonPrimitive.content, keys.getValue("computerId").jsonPrimitive.content)
+ assertEquals(push.getValue("plaintext").jsonPrimitive.content, result.toString(Charsets.UTF_8))
+ }
+}
+
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/MessageActionsMenuTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/MessageActionsMenuTest.kt
new file mode 100644
index 00000000..df1e7d15
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/MessageActionsMenuTest.kt
@@ -0,0 +1,111 @@
+package com.codync.android
+
+import android.content.ClipboardManager
+import android.os.Build
+import android.view.KeyEvent
+import androidx.compose.foundation.layout.*
+import androidx.compose.material3.Text
+import androidx.compose.runtime.*
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalUriHandler
+import androidx.compose.ui.platform.UriHandler
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.viewmodel.compose.viewModel
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import com.codync.android.design.MenuItem
+import com.codync.android.design.ReactionPick
+import com.codync.android.design.contextActions
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+
+/** A message's long-press menu (`Modifier.contextActions`): reactions over copy, reply and trace. */
+class MessageActionsMenuTest {
+ @get:Rule val compose = createComposeRule()
+ private fun back() = InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)
+
+ @Before fun isolatedEmulatorOnly() { assumeTrue(Build.PRODUCT.startsWith("sdk")) }
+
+ @Test fun holdingAReplyOffersReactionsAndCopiesItsText() {
+ val bot = Bot("message-preview", "Scout")
+ val text = "Checked the connection. The saved route works."
+ val entry = Entry("reply", 1, bot.id, rev = 1, kind = "agent", data = buildJsonObject { put("text", text); put("final", true) })
+ val initial = AppState(loading = false, selectedBot = bot.id, bots = listOf(bot),
+ connection = LinkState.Ready(HostRoute.Direct), historyComplete = setOf(bot.id), entries = listOf(entry))
+ val state = mutableStateOf(initial)
+ compose.setContent { Hosted { ChatScreen(state.value, viewModel(), {}) } }
+ val bubble = compose.onNode(hasText(text, substring = true) and hasClickAction())
+ bubble.performTouchInput { longClick() }
+ compose.onNodeWithContentDescription("👍").assertIsDisplayed().assertIsNotSelected()
+ compose.onNodeWithText("Reply in thread").assertIsDisplayed()
+ compose.onNodeWithText("Show what it did").assertIsDisplayed()
+ compose.onNodeWithText("Copy").performClick()
+ compose.onNodeWithText("Copy").assertDoesNotExist()
+ val clipboard = InstrumentationRegistry.getInstrumentation().targetContext.getSystemService(ClipboardManager::class.java)
+ compose.runOnIdle { assertEquals(text, clipboard.primaryClip?.getItemAt(0)?.text?.toString()) }
+ bubble.performTouchInput { longClick() }
+ back()
+ compose.onNodeWithText("Copy").assertDoesNotExist()
+ // A retired account/session cannot keep the old message's actions alive.
+ bubble.performTouchInput { longClick() }
+ compose.onNodeWithText("Copy").assertIsDisplayed()
+ compose.runOnUiThread { state.value = initial.copy(generation = initial.generation + 1) }
+ compose.onNodeWithText("Copy").assertDoesNotExist()
+ compose.runOnUiThread { clipboard.clearPrimaryClip() }
+ }
+
+ @Test fun reactionsAndOptionsCloseTheMenuAndRunOnce() {
+ val invoked = mutableListOf<String>()
+ compose.setContent { Hosted {
+ Box(Modifier.fillMaxSize().safeDrawingPadding().padding(top = 80.dp)) {
+ Text("Action callback preview", Modifier.contextActions(ReactionPick(listOf("👍", "❤️"), listOf("👍")) { invoked.add(it) },
+ preview = { Text("Action callback preview") }) {
+ listOf(MenuItem("Reply in thread") { invoked.add("thread") }, MenuItem("Copy") { invoked.add("copy") })
+ })
+ }
+ } }
+ val bubble = compose.onNode(hasText("Action callback preview") and hasClickAction())
+ bubble.performTouchInput { longClick() }
+ compose.onNodeWithContentDescription("👍").assertIsSelected().performClick()
+ compose.onNodeWithText("Copy").assertDoesNotExist()
+ assertEquals(listOf("👍"), invoked)
+ for ((label, event) in listOf("Reply in thread" to "thread", "Copy" to "copy")) {
+ bubble.performTouchInput { longClick() }
+ compose.onNodeWithText(label).performClick()
+ compose.onNodeWithText(label).assertDoesNotExist()
+ assertEquals(event, invoked.last())
+ }
+ bubble.performClick()
+ compose.onNodeWithText("Copy").assertDoesNotExist()
+ bubble.performTouchInput { longClick() }
+ back()
+ compose.onNodeWithText("Copy").assertDoesNotExist()
+ assertEquals(3, invoked.size)
+ }
+
+ @Test fun linksKeepTheirTapAndHoldingOpensTheMenu() {
+ val urls = mutableListOf<String>()
+ compose.setContent { Hosted {
+ CompositionLocalProvider(LocalUriHandler provides object : UriHandler {
+ override fun openUri(uri: String) { urls.add(uri) }
+ }) {
+ Box(Modifier.safeDrawingPadding().contextActions { listOf(MenuItem("Copy")) }) {
+ MarkdownText("[Visit Codync](https://codync.dev)", selectable = false)
+ }
+ }
+ } }
+ val link = compose.onNodeWithText("Visit Codync", useUnmergedTree = true)
+ link.performTouchInput { click() }
+ compose.onNodeWithText("Copy").assertDoesNotExist()
+ assertEquals(listOf("https://codync.dev"), urls)
+ link.performTouchInput { longClick() }
+ compose.onNodeWithText("Copy").assertIsDisplayed()
+ assertEquals(1, urls.size)
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/MirrorDatabaseTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/MirrorDatabaseTest.kt
new file mode 100644
index 00000000..cfa516f8
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/MirrorDatabaseTest.kt
@@ -0,0 +1,120 @@
+package com.codync.android
+
+import androidx.test.platform.app.InstrumentationRegistry
+import android.database.sqlite.SQLiteDatabase
+import android.content.ContentValues
+import com.codync.android.core.*
+import java.io.File
+import java.util.UUID
+import kotlinx.serialization.json.*
+import kotlinx.serialization.encodeToString
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Test
+
+class MirrorDatabaseTest {
+ private val context = InstrumentationRegistry.getInstrumentation().targetContext
+ private val directory = File(context.noBackupFilesDir, "mirror-test-" + UUID.randomUUID()).apply { mkdirs() }
+ private val computer = "AAAAAAAAAAAAAAAAAAAAAA"
+ private var mirror = MirrorDatabase(context, directory, computer)
+ private fun entry(rev: Long, text: String = "new", nonce: String? = null): Entry = Entry("message", 1, "bot", rev = rev, kind = "user",
+ data = buildJsonObject { put("text", text); nonce?.let { put("clientNonce", it) } })
+
+ @After fun cleanup() { mirror.close(); directory.deleteRecursively() }
+
+ @Test fun rpcRepliesAndHelloCannotCheckpointPastUnseenEvents() {
+ mirror.apply(MirrorEvent.Hello("database", 100, JsonObject(emptyMap()), null))
+ mirror.receive(listOf(entry(90)))
+ assertEquals(0, mirror.snapshot().rev)
+ mirror.apply(MirrorEvent.EntryChanged(entry(2, "older")))
+ assertEquals(2, mirror.snapshot().rev)
+ assertEquals("new", mirror.snapshot().entries.single().text)
+ }
+
+ @Test fun anInitialRosterCannotSkipEarlierTranscriptEventsAndBatchesCommitTogether() {
+ mirror.receive(listOf(Bot("bot", "Current roster", rev = 500)))
+ assertEquals(0, mirror.snapshot().rev)
+ mirror.save(PendingSend("nonce", "bot", text = "message", createdAt = 1))
+ mirror.apply(listOf(MirrorEvent.BotChanged(Bot("bot", "Older roster", rev = 2)),
+ MirrorEvent.EntryChanged(entry(3, nonce = "nonce"))))
+ mirror.close()
+ mirror = MirrorDatabase(context, directory, computer)
+ val snapshot = mirror.snapshot()
+ assertEquals(3, snapshot.rev)
+ assertEquals("Current roster", snapshot.bots.single().name)
+ assertEquals("nonce", snapshot.entries.single().clientNonce)
+ assertTrue(snapshot.pending.isEmpty())
+ }
+
+ @Test fun cursorAndSendReconciliationSurviveReopeningTogether() {
+ mirror.save(PendingSend("nonce", "bot", text = "message", createdAt = 1))
+ mirror.apply(MirrorEvent.EntryChanged(entry(7, nonce = "nonce")))
+ mirror.close()
+ mirror = MirrorDatabase(context, directory, computer)
+ assertEquals(7, mirror.snapshot().rev)
+ assertTrue(mirror.snapshot().pending.isEmpty())
+ assertEquals("nonce", mirror.snapshot().entries.single().clientNonce)
+ }
+
+ @Test fun tombstonesCannotBeResurrectedByLateRepliesOrHistory() {
+ mirror.apply(MirrorEvent.BotChanged(Bot("bot", "Bot", rev = 2)))
+ mirror.apply(MirrorEvent.EntryChanged(entry(3)))
+ mirror.apply(MirrorEvent.BotChanged(Bot("bot", rev = 4, deleted = true)))
+ mirror.receive(Bot("bot", "Old", rev = 2))
+ mirror.receive(listOf(entry(3)))
+ assertTrue(mirror.snapshot().bots.isEmpty())
+ assertTrue(mirror.snapshot().entries.isEmpty())
+ assertEquals(4, mirror.snapshot().rev)
+ }
+
+ @Test fun incompatibleCacheAndDatabaseReplacementRewindSafely() {
+ mirror.setStamp("old", "2.4/2.4")
+ mirror.apply(MirrorEvent.EntryChanged(entry(9)))
+ mirror.setStamp("old", "2.5/2.4")
+ assertEquals(0, mirror.snapshot().rev)
+ assertEquals(1, mirror.snapshot().entries.size)
+ mirror.setStamp("new", "2.5/2.4")
+ assertEquals(0, mirror.snapshot().rev)
+ assertTrue(mirror.snapshot().entries.isEmpty())
+ }
+
+ @Test fun interruptedSendRetainsItsNonceAndRequiresAnExplicitRetry() {
+ mirror.save(PendingSend("stable", "bot", text = "message", createdAt = 1))
+ mirror.close()
+ mirror = MirrorDatabase(context, directory, computer)
+ mirror.recoverInterrupted()
+ assertEquals("stable", mirror.snapshot().pending.single().nonce)
+ assertEquals(SendStatus.Failed, mirror.snapshot().pending.single().status)
+ }
+
+ @Test fun aLateSendFailureCannotResurrectAnAlreadyConfirmedMessage() {
+ val send = PendingSend("stable", "bot", text = "message", createdAt = 1)
+ mirror.save(send)
+ mirror.apply(MirrorEvent.EntryChanged(entry(3, nonce = send.nonce)))
+ mirror.save(send.copy(status = SendStatus.Failed))
+ assertTrue(mirror.snapshot().pending.isEmpty())
+ assertEquals(1, mirror.snapshot().entries.size)
+ }
+
+ @Test fun upgradingTheMirrorRetainsMessagesAndBackfillsNonceReconciliation() {
+ mirror.close()
+ val path = File(directory, "mirror-$computer.db")
+ path.delete()
+ SQLiteDatabase.openOrCreateDatabase(path, null).use { db ->
+ db.execSQL("CREATE TABLE meta(k TEXT PRIMARY KEY, v TEXT NOT NULL)")
+ db.execSQL("CREATE TABLE bots(id TEXT PRIMARY KEY, rev INTEGER NOT NULL, deleted INTEGER NOT NULL, payload TEXT NOT NULL)")
+ db.execSQL("CREATE TABLE entries(id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, thread_id TEXT, seq INTEGER NOT NULL, rev INTEGER NOT NULL, payload TEXT NOT NULL)")
+ db.execSQL("CREATE TABLE pending(nonce TEXT PRIMARY KEY, created INTEGER NOT NULL, payload TEXT NOT NULL)")
+ db.execSQL("CREATE TABLE history(lane TEXT PRIMARY KEY)")
+ db.insertOrThrow("entries", null, ContentValues().apply {
+ put("id", "message"); put("bot_id", "bot"); put("seq", 1); put("rev", 3)
+ put("payload", WireJson.encodeToString(entry(3, nonce = "stable")))
+ })
+ db.version = 1
+ }
+ mirror = MirrorDatabase(context, directory, computer)
+ assertEquals("stable", mirror.snapshot().entries.single().clientNonce)
+ mirror.save(PendingSend("stable", "bot", text = "message", createdAt = 1))
+ assertTrue(mirror.snapshot().pending.isEmpty())
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/NativeVoiceTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/NativeVoiceTest.kt
new file mode 100644
index 00000000..ca825298
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/NativeVoiceTest.kt
@@ -0,0 +1,80 @@
+package com.codync.android
+
+import android.Manifest
+import android.content.pm.PackageManager
+import android.os.Build
+import androidx.core.content.ContextCompat
+import androidx.test.core.app.ActivityScenario
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+import java.security.MessageDigest
+import kotlinx.coroutines.*
+import org.json.JSONObject
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+import org.vosk.LibVosk
+import org.vosk.Model
+import org.vosk.Recognizer
+
+class NativeVoiceTest {
+ @Test fun theBundledLocalModelRecognizesThePinnedSpeechFixture() = runBlocking {
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ val wav = instrumentation.context.assets.open("voice-test.wav").use { it.readBytes() }
+ val digest = MessageDigest.getInstance("SHA-256").digest(wav).joinToString("") { "%02x".format(it) }
+ assertEquals("dcfea5712c43a43ba7ae8083afb39d36993e5a69c46e88b68aaa72b65cb615bb", digest)
+ val header = ByteBuffer.wrap(wav).order(ByteOrder.LITTLE_ENDIAN)
+ var offset = 12; var pcm: ByteArray? = null
+ while (offset + 8 <= wav.size) {
+ val kind = String(wav, offset, 4, Charsets.US_ASCII); val size = header.getInt(offset + 4)
+ require(size >= 0 && size <= wav.size - offset - 8)
+ if (kind == "fmt ") {
+ assertEquals(1, header.getShort(offset + 8).toInt()); assertEquals(1, header.getShort(offset + 10).toInt())
+ assertEquals(16_000, header.getInt(offset + 12)); assertEquals(16, header.getShort(offset + 22).toInt())
+ }
+ if (kind == "data") pcm = wav.copyOfRange(offset + 8, offset + 8 + size)
+ offset += 8 + size + size % 2
+ }
+ val samples = requireNotNull(pcm)
+ val text = withContext(Dispatchers.IO) {
+ LibVosk.vosk_set_log_level(-1)
+ val directory = VoiceModels.english(instrumentation.targetContext)
+ Model(directory.absolutePath).use { model -> Recognizer(model, 16_000f).use { recognizer ->
+ val results = mutableListOf<String>(); var position = 0
+ while (position < samples.size) {
+ val count = minOf(4_096, samples.size - position)
+ val chunk = samples.copyOfRange(position, position + count)
+ if (recognizer.acceptWaveForm(chunk, chunk.size)) results.add(JSONObject(recognizer.result).optString("text"))
+ position += count
+ }
+ results.add(JSONObject(recognizer.finalResult).optString("text")); results.joinToString(" ")
+ } }
+ }
+ assertTrue("The model must recognize the fixture's first spoken digits", text.contains("one zero zero zero one"))
+ assertTrue("The model must recognize the fixture's final spoken digits", text.contains("zero one eight zero three"))
+ }
+ @Test fun nativeMicrophoneCaptureStopsAndOfflinePlaybackCompletes() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("voiceAudio") == "true")
+ assertTrue("Microphone fixtures belong on emulators", Build.PRODUCT.contains("sdk"))
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ assertEquals(PackageManager.PERMISSION_GRANTED, ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO))
+ ActivityScenario.launch(MainActivity::class.java).use {
+ val engine = LocalVoiceAudio(context)
+ try { runBlocking { withContext(Dispatchers.Main) {
+ val name = engine.initialize(); assertEquals("Offline English · Vosk", name)
+ val capturing = CompletableDeferred<Unit>()
+ engine.listen(1) { event -> if (event is VoiceInput.Level) capturing.complete(Unit) }
+ withTimeout(10_000) { capturing.await() }
+ assertNotNull(engine.recordingSessionId)
+ engine.stopListening(); assertNull(engine.recordingSessionId)
+ val spoken = CompletableDeferred<String?>()
+ engine.speak(1, "This is the offline voice acceptance fixture.", 1f) { _, error -> spoken.complete(error) }
+ val error = withTimeout(30_000) { spoken.await() }
+ assertNull(error)
+ engine.stopSpeaking()
+ } } } finally { runBlocking { withContext(Dispatchers.Main + NonCancellable) { engine.close() } } }
+ }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/NavigationControls.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/NavigationControls.kt
new file mode 100644
index 00000000..0d8c2a93
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/NavigationControls.kt
@@ -0,0 +1,43 @@
+package com.codync.android
+
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.ComposeTestRule
+import com.codync.android.design.CodyncTheme
+import com.codync.android.design.OverlayRoot
+
+internal fun SemanticsNodeInteractionsProvider.onControl(label: String) = onNode(hasText(label) or hasContentDescription(label))
+
+/** A screen as the app hosts it: the theme, and the overlay its sheets, menus and dialogs draw in. */
+@Composable internal fun Hosted(content: @Composable () -> Unit) = CodyncTheme { OverlayRoot(content) }
+
+/** The roster header's computers menu ("Computers, 1 connected. Filter conversations"). */
+internal fun ComposeTestRule.computerAction(label: String) {
+ onNodeWithContentDescription("Computers,", substring = true).performClick()
+ onNodeWithText(label).performClick()
+}
+
+/** The button labeled [label] level with [text]: for list rows that merge no semantics of their own. */
+internal fun ComposeTestRule.onRowButton(label: String, text: String): SemanticsNodeInteraction {
+ val row = onNodeWithText(text).performScrollTo().fetchSemanticsNode().boundsInRoot
+ val buttons = onAllNodesWithContentDescription(label)
+ val index = buttons.fetchSemanticsNodes().indexOfFirst { it.boundsInRoot.top < row.bottom && it.boundsInRoot.bottom > row.top }
+ check(index >= 0) { "No $label button beside $text" }
+ return buttons[index]
+}
+
+/** Extensions opens from the paired computer's row in Computers & settings. */
+internal fun ComposeTestRule.openExtensions() {
+ computerAction("Manage computers")
+ waitUntil(10_000) { onAllNodesWithContentDescription("Extensions").fetchSemanticsNodes().size == 1 }
+ onNodeWithContentDescription("Extensions").performClick()
+}
+
+/** The open chat's title menu ("<bot> actions"). */
+internal val chatMenu = hasContentDescription(" actions", substring = true)
+
+internal fun ComposeTestRule.chatAction(label: String) {
+ waitUntil(10_000) { onAllNodes(chatMenu).fetchSemanticsNodes().size == 1 }
+ onNode(chatMenu).performClick()
+ onNodeWithText(label).performClick()
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt
new file mode 100644
index 00000000..b7e19c3b
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt
@@ -0,0 +1,54 @@
+package com.codync.android
+
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.lifecycle.viewmodel.compose.viewModel
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+
+/** Read-only: the store only receives taps that never pair, skip or sign in. */
+class OnboardingTest {
+ @get:Rule val compose = createComposeRule()
+
+ @Test fun welcomeLeadsToInstallAndBackReturnsToWelcome() {
+ compose.setContent { Hosted { CodyncApp(AppState(loading = false), viewModel()) } }
+ compose.onNodeWithText("Your coding agents", substring = true).assertIsDisplayed()
+ compose.onNodeWithText("Get started").performClick()
+ compose.onNodeWithText("Install Codync", substring = true).assertIsDisplayed()
+ compose.onNodeWithContentDescription("Step 1 of 2").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Back").performClick()
+ compose.onNodeWithText("Get started").assertIsDisplayed()
+ }
+
+ @Test fun installStepsFollowTheComputerAndScanKeepsTheChoice() {
+ var skipped = false
+ compose.setContent { Hosted { PairingView(AppState(loading = false), viewModel(), onSkip = { skipped = true }) } }
+ compose.onNodeWithText("Mac").assertIsSelected()
+ compose.onNodeWithText("brew install --cask leepokai/codync/codync").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithText("Linux").performClick().assertIsSelected()
+ compose.onNodeWithText("codync-host install keeps it running in the background.").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithText("brew install --cask leepokai/codync/codync").assertDoesNotExist()
+ compose.onNodeWithText("Skip").assertDoesNotExist()
+ compose.onNodeWithText("Continue").performClick()
+ compose.onNodeWithText("Scan the pairing code").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Step 2 of 2").assertIsDisplayed()
+ compose.onNodeWithText("codync-host pair").assertIsDisplayed()
+ compose.onNodeWithText("Or paste a ${BuildConfig.URL_SCHEME}://pair link").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithContentDescription("Pair").assertIsNotEnabled()
+ compose.onNode(hasSetTextAction()).performTextInput("draft-link")
+ compose.onNodeWithContentDescription("Pair").assertIsEnabled()
+ compose.onNodeWithContentDescription("Back").performClick()
+ compose.onNodeWithText("Linux").assertIsSelected()
+ compose.onNodeWithText("Continue").performClick()
+ compose.onNodeWithText("Skip").performClick()
+ assertTrue(skipped)
+ }
+
+ @Test fun macPairingPointsToTheMenuBarApp() {
+ compose.setContent { Hosted { PairingView(AppState(loading = false), viewModel()) } }
+ compose.onNodeWithText("Continue").performClick()
+ compose.onNodeWithText("On your Mac, click Codync in the menu bar, then Pair iPhone. The same code pairs this phone.").assertIsDisplayed()
+ compose.onNodeWithText("codync-host pair").assertDoesNotExist()
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/PushTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/PushTest.kt
new file mode 100644
index 00000000..ba297044
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/PushTest.kt
@@ -0,0 +1,117 @@
+package com.codync.android
+
+import android.Manifest
+import android.app.Notification
+import android.app.NotificationManager
+import android.content.pm.PackageManager
+import android.os.Build
+import android.os.SystemClock
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.Bot
+import com.codync.android.core.Computer
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Test
+import java.util.UUID
+
+class PushTest {
+ private val instrumentation = InstrumentationRegistry.getInstrumentation()
+ private val context = instrumentation.targetContext
+
+ private fun waitUntil(condition: () -> Boolean) {
+ val deadline = SystemClock.elapsedRealtime() + 3000
+ while (!condition() && SystemClock.elapsedRealtime() < deadline) SystemClock.sleep(10)
+ assertTrue(condition())
+ }
+
+ @Test fun sealedFallbackStaysGenericAndInactiveContextsCannotNotify() {
+ val previous = PushPreferences.activeUser(context)
+ val previousEnabled = PushPreferences.enabled(context)
+ val previousVisible = PushDelivery.foreground
+ val user = "push-test-${UUID.randomUUID()}"
+ val local = LocalStore(context, user)
+ val fixture = instrumentation.context.assets.open("remote-relay-vectors.json").bufferedReader().use {
+ Json.parseToJsonElement(it.readText()).jsonObject.getValue("keys").jsonObject
+ }
+ val computer = Computer(fixture.getValue("computerId").jsonPrimitive.content, "Fixture", fixture.getValue("hostSignPub").jsonPrimitive.content)
+ val manager = context.getSystemService(NotificationManager::class.java)
+ val bot = "test-${UUID.randomUUID()}"
+ val tag = "${local.referenceId}/${computer.id}/$bot"
+ val permission = Build.VERSION.SDK_INT >= 33 && context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
+ if (permission) instrumentation.uiAutomation.grantRuntimePermission(context.packageName, Manifest.permission.POST_NOTIFICATIONS)
+ try {
+ local.saveComputers(listOf(computer)); local.identity()
+ PushPreferences.active(context, user); PushPreferences.enabled(context, true); PushDelivery.foreground = false
+ val data = mapOf("kind" to "alert", "ctx" to local.referenceId, "computerId" to computer.id, "botId" to bot,
+ "sealed" to "invalid", "title" to "Never display unsealed private text", "body" to "private content")
+ PushService.receive(context, data + ("ctx" to "local"))
+ assertTrue(manager.activeNotifications.none { it.tag == tag })
+ PushService.receive(context, data)
+ waitUntil { manager.activeNotifications.any { it.tag == tag } }
+ val notification = manager.activeNotifications.single { it.tag == tag }.notification
+ assertEquals(context.getString(R.string.app_name), notification.extras.getString(Notification.EXTRA_TITLE))
+ assertEquals("A bot has an update.", notification.extras.getString(Notification.EXTRA_TEXT))
+ assertEquals(Notification.VISIBILITY_PRIVATE, notification.visibility)
+ manager.cancel(tag, 1)
+ waitUntil { manager.activeNotifications.none { it.tag == tag } }
+ PushDelivery.foreground = true
+ PushService.receive(context, data)
+ assertTrue(manager.activeNotifications.none { it.tag == tag })
+ PushDelivery.foreground = false
+ PushPreferences.enabled(context, false)
+ PushService.receive(context, data)
+ assertTrue(manager.activeNotifications.none { it.tag == tag })
+ } finally {
+ manager.cancel(tag, 1); local.erase()
+ PushPreferences.active(context, previous); PushPreferences.enabled(context, previousEnabled); PushDelivery.foreground = previousVisible
+ // Revoking this permission kills the test process on newer Android releases.
+ // These storage/identity tests run only on disposable emulator installations.
+ }
+ }
+
+ @Test fun delegatedTasksRejectStaleWrongGenerationAndPostCompletionUpdates() {
+ val local = LocalStore(context, "task-test-${UUID.randomUUID()}")
+ try {
+ val feed = TaskFeed(local.directory)
+ val watch = feed.start(Bot("bot", "Reviewer", rev = 1))
+ val now = System.currentTimeMillis() / 1000
+ val data = mapOf("taskId" to watch.taskId, "status" to "needsInput", "timestamp" to now.toString(), "staleDate" to (now + 900).toString(), "event" to "update")
+ assertNull(feed.remote(data + ("taskId" to "old-delegation"), "bot"))
+ assertEquals("needsInput", feed.remote(data, "bot")?.status)
+ assertNull(feed.remote(data + ("timestamp" to (now - 1).toString()), "bot"))
+ assertNull(feed.remote(data + ("staleDate" to (now - 1).toString()), "bot"))
+ assertNull(feed.remote(data + mapOf("event" to "end", "status" to "working"), "bot"))
+ val ended = feed.remote(data + mapOf("event" to "end", "status" to "idle"), "bot")
+ assertEquals(true, ended?.finished)
+ assertNull(feed.remote(data + ("timestamp" to (now + 1).toString()), "bot"))
+ val restarted = feed.start(Bot("bot", "Reviewer", rev = 2))
+ assertNotEquals(watch.taskId, restarted.taskId)
+ assertNull(feed.remote(data, "bot"))
+ } finally { local.erase() }
+ }
+
+ @Test fun aTaskAlreadyRunningWhenItsSendIsAcknowledgedCanFinishLocally() {
+ val local = LocalStore(context, "task-running-test-${UUID.randomUUID()}")
+ try {
+ val feed = TaskFeed(local.directory)
+ val started = feed.start(Bot("bot", "Reviewer", status = "needsInput", rev = 5))
+ assertTrue(started.seenRunning)
+ assertEquals("needsInput", started.status)
+ assertEquals(true, feed.local(Bot("bot", "Reviewer", status = "idle", rev = 6))?.finished)
+ } finally { local.erase() }
+ }
+
+ @Test fun delegatedTaskMarkersAreBoundedAndAnIdleAcknowledgementCannotFinishThem() {
+ val local = LocalStore(context, "task-limit-test-${UUID.randomUUID()}")
+ try {
+ val feed = TaskFeed(local.directory)
+ repeat(24) { feed.start(Bot("bot-$it", "Bot", rev = 1)) }
+ assertEquals(16, feed.all().size)
+ assertNull(feed.local(Bot("bot-23", "Bot", status = "idle", rev = 2)))
+ assertEquals(false, feed.local(Bot("bot-23", "Bot", status = "working", rev = 3))?.finished)
+ assertNull(feed.local(Bot("bot-23", "Bot", status = "idle", rev = 2)))
+ assertEquals(true, feed.local(Bot("bot-23", "Bot", status = "idle", rev = 4))?.finished)
+ feed.clear(); assertTrue(feed.all().isEmpty())
+ } finally { local.erase() }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/RepliesPopoverTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/RepliesPopoverTest.kt
new file mode 100644
index 00000000..aa4c0c85
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/RepliesPopoverTest.kt
@@ -0,0 +1,86 @@
+package com.codync.android
+
+import android.graphics.Bitmap
+import android.os.Build
+import android.view.KeyEvent
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.lifecycle.viewmodel.compose.viewModel
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import java.io.File
+
+/** A thread opens in a sheet over the chat, which stays put underneath. */
+class RepliesPopoverTest {
+ @get:Rule val compose = createComposeRule()
+ private val instrumentation get() = InstrumentationRegistry.getInstrumentation()
+ private val bot = Bot("thread-preview", "Scout")
+ private val root = entry("root", 1, "user", "Please check the connection.")
+
+ private fun entry(id: String, seq: Long, kind: String, text: String, thread: String? = null, replies: Int = 0) =
+ Entry(id, seq, bot.id, threadId = thread, rev = seq, kind = kind, data = buildJsonObject {
+ put("text", text); put("final", true)
+ if (replies > 0) put("thread", buildJsonObject { put("count", replies) })
+ })
+ private fun fixture(entries: List<Entry>) = AppState(loading = false,
+ selectedBot = bot.id, thread = root.id, bots = listOf(bot), entries = entries,
+ historyComplete = setOf(bot.id), connection = LinkState.Ready(HostRoute.Direct), actualConnection = LinkState.Ready(HostRoute.Direct))
+ private fun render(state: AppState) = compose.setContent { Hosted { ChatScreen(state, viewModel(), {}) } }
+
+ @Before fun isolatedEmulatorOnly() { assumeTrue(Build.PRODUCT.startsWith("sdk")) }
+
+ @Test fun emptyThreadShowsTheOriginalBeforeNoRepliesYet() {
+ render(fixture(listOf(root, entry("other-thread", 3, "agent", "A reply in a different thread.", "different-root"))))
+ compose.onNodeWithText("Thread").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Close thread").assertIsDisplayed()
+ compose.onNodeWithText("A reply in a different thread.").assertDoesNotExist()
+ val original = compose.onAllNodesWithText(root.text).onLast().assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ val label = compose.onNodeWithText("No replies yet").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ assertTrue(original.bottom <= label.top)
+ compose.onNode(hasSetTextAction() and hasText("Reply…")).assertIsDisplayed()
+ if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") == "true") {
+ val screen = instrumentation.uiAutomation.takeScreenshot()
+ File(instrumentation.targetContext.cacheDir, "thread-empty-screen.png").outputStream().use { screen.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ }
+ // In the thread the original offers no "Reply in thread" of its own.
+ compose.onAllNodes(hasText(root.text) and hasClickAction()).onLast().performTouchInput { longClick() }
+ compose.onNodeWithText("Copy").assertIsDisplayed()
+ compose.onNodeWithText("Reply in thread").assertDoesNotExist()
+ instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)
+ compose.onNodeWithText("Copy").assertDoesNotExist()
+ compose.onNodeWithContentDescription("Close thread").assertIsDisplayed()
+ }
+
+ @Test fun repliesFollowTheOriginalInOrder() {
+ val user = entry("reply-user", 2, "user", "Try the saved connection.", root.id)
+ val agent = entry("reply-agent", 3, "agent", "The saved connection works.", root.id)
+ render(fixture(listOf(entry(root.id, 1, "user", root.text, replies = 2), user, agent)))
+ val original = compose.onAllNodesWithText(root.text).onLast().assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ val label = compose.onNodeWithText("2 replies").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ val reply = compose.onNodeWithText(user.text).assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ assertTrue(original.bottom <= label.top)
+ assertTrue(label.bottom <= reply.top)
+ compose.onNodeWithText(agent.text).assertIsDisplayed()
+ compose.onNodeWithText("No replies yet").assertDoesNotExist()
+ }
+
+ @Test fun longOriginalScrollsWhileTheTitleAndReplyComposerStayVisibleWithTheKeyboard() {
+ val text = (1..40).joinToString("\n\n") { "Original paragraph $it: Keep the original reply context available." }
+ render(fixture(listOf(entry(root.id, 1, "agent", text))))
+ compose.onNodeWithText("No replies yet").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithText("Thread").assertIsDisplayed()
+ val composer = compose.onNode(hasSetTextAction() and hasText("Reply…"))
+ val before = composer.fetchSemanticsNode().layoutInfo.coordinates.localToScreen(Offset.Zero).y
+ composer.performTouchInput { click() }
+ compose.waitUntil(10_000) { composer.fetchSemanticsNode().layoutInfo.coordinates.localToScreen(Offset.Zero).y < before - 100f }
+ compose.onNodeWithText("Thread").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Close thread").assertIsDisplayed()
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/ScreenPresentationTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/ScreenPresentationTest.kt
new file mode 100644
index 00000000..472d33a9
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/ScreenPresentationTest.kt
@@ -0,0 +1,102 @@
+package com.codync.android
+
+import android.graphics.Bitmap
+import android.os.Build
+import android.view.KeyEvent
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.unit.Density
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.lifecycle.viewmodel.compose.viewModel
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import com.codync.android.design.CodyncSheet
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import java.io.File
+
+/** The real root's sheets and Android Back dispatch, on read-only fixtures. */
+class ScreenPresentationTest {
+ @get:Rule val compose = createComposeRule()
+ private val bot = Bot("presentation-fixture", "Scout")
+ private fun fixture() = AppState(contextId = "presentation-fixture", loading = false,
+ setupComplete = true, rosterLoaded = true, bots = listOf(bot),
+ computers = listOf(Computer("fixture-computer", "Fixture computer", "fixture-key")),
+ account = AccountState(ready = true, configured = true, multiple = true, userId = "fixture-account",
+ accounts = listOf(SavedAccount("fixture-account", "fixture-session", "[email protected]", null))))
+
+ @Before fun isolatedEmulatorOnly() { assumeTrue(Build.PRODUCT.startsWith("sdk")) }
+
+ @Test fun backPopsAccountSettingsAndNestedPairingOneLayerAtATime() {
+ compose.setContent { Hosted { CodyncApp(fixture(), viewModel()) } }
+ compose.onNodeWithContentDescription("Switch account").performClick()
+ compose.onNodeWithText("Account").assertIsDisplayed()
+ snapshot("account-sheet")
+ compose.onNodeWithText("Computers").performClick()
+ compose.onNodeWithText("Computers & settings").assertIsDisplayed()
+ back()
+ compose.onNodeWithText("Computers & settings").assertDoesNotExist()
+ compose.onNodeWithText("Account").assertIsDisplayed()
+ compose.onNodeWithText("Computers").performClick()
+ compose.onNodeWithText("Pair a computer").performScrollTo().performClick()
+ compose.onNodeWithText("Install Codync", substring = true).assertIsDisplayed()
+ back()
+ compose.onNodeWithText("Install Codync", substring = true).assertDoesNotExist()
+ compose.onNodeWithText("Computers & settings").assertIsDisplayed()
+ back()
+ compose.onNodeWithText("Account").assertIsDisplayed()
+ back()
+ compose.onNodeWithText("Account").assertDoesNotExist()
+ compose.onNodeWithText(bot.name).assertIsDisplayed()
+ }
+
+ @Test fun closingTheEditorDropsItsDraftAndANewGenerationRetiresIt() {
+ val state = mutableStateOf(fixture().copy(selectedBot = bot.id, historyComplete = setOf(bot.id)))
+ compose.setContent { Hosted { CodyncApp(state.value, viewModel()) } }
+ compose.chatAction("Edit profile")
+ compose.onNodeWithText("Settings").assertIsDisplayed()
+ compose.onNodeWithContentDescription("Save").assertIsNotEnabled()
+ compose.onNode(hasSetTextAction() and hasText(bot.name)).performTextReplacement("Discard this draft")
+ snapshot("bot-settings-sheet")
+ compose.onNodeWithContentDescription("Close").performClick()
+ compose.onNodeWithText("Settings").assertDoesNotExist()
+ compose.chatAction("Edit profile")
+ compose.onNode(hasSetTextAction() and hasText(bot.name)).assertIsDisplayed()
+ compose.runOnUiThread { state.value = state.value.copy(generation = state.value.generation + 1) }
+ compose.onNodeWithText("Settings").assertDoesNotExist()
+ }
+
+ @Test fun largeTextKeepsSettingsActionsAndCompactOptionsWithinTheSheet() {
+ val draft = BotDraft(id = bot.id, name = bot.name, cwd = "/projects/A-long-project-name")
+ compose.setContent {
+ val density = LocalDensity.current
+ CompositionLocalProvider(LocalDensity provides Density(density.density, 1.5f)) {
+ Hosted { CodyncSheet(true, {}) { BotEditor(fixture(), draft, viewModel()) } }
+ }
+ }
+ val title = compose.onNodeWithText("Settings").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ val save = compose.onNodeWithContentDescription("Save").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ val close = compose.onNodeWithContentDescription("Close").assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ assertTrue(title.right < save.left && save.right <= close.left)
+ val screen = compose.onRoot().fetchSemanticsNode().boundsInRoot
+ listOf("Agent: Claude", "Workspace", "Permissions: Approve automatically").forEach { label ->
+ val row = compose.onNodeWithContentDescription(label).performScrollTo().assertIsDisplayed().fetchSemanticsNode().boundsInRoot
+ assertTrue(row.left >= screen.left && row.right <= screen.right)
+ }
+ compose.onNode(hasText("Notifications") and isToggleable()).performScrollTo().assertIsOn().performClick().assertIsOff()
+ snapshot("bot-settings-large-text")
+ }
+
+ private fun back() = InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)
+ private fun snapshot(name: String) {
+ if (InstrumentationRegistry.getArguments().getString("layoutSnapshots") != "true") return
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ val screenshot = instrumentation.uiAutomation.takeScreenshot()
+ File(instrumentation.targetContext.cacheDir, "$name.png").outputStream().use { screenshot.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/TerminalSurfaceTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/TerminalSurfaceTest.kt
new file mode 100644
index 00000000..25b967e4
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/TerminalSurfaceTest.kt
@@ -0,0 +1,250 @@
+package com.codync.android
+
+import android.view.KeyEvent
+import androidx.compose.foundation.layout.*
+import androidx.compose.runtime.*
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.compose.ui.test.onNodeWithText
+import androidx.compose.ui.test.assertIsDisplayed
+import androidx.compose.ui.unit.dp
+import androidx.test.platform.app.InstrumentationRegistry
+import kotlinx.coroutines.*
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Rule
+import org.junit.Test
+import java.util.concurrent.CopyOnWriteArrayList
+import java.util.concurrent.atomic.AtomicInteger
+import java.util.concurrent.atomic.AtomicReference
+import kotlin.coroutines.resume
+
+class TerminalSurfaceTest {
+ @get:Rule val compose = createComposeRule()
+ private val ready = AtomicReference<TerminalRenderer>()
+ private val created = AtomicReference<TerminalRenderer>()
+ private val failures = AtomicInteger()
+ private val inputs = CopyOnWriteArrayList<ByteArray>()
+ private val sizes = CopyOnWriteArrayList<Pair<Int, Int>>()
+
+ private fun show(height: State<Int> = mutableStateOf(400), visible: State<Boolean> = mutableStateOf(true)): TerminalRenderer {
+ compose.setContent {
+ if (visible.value) TerminalSurface(Modifier.fillMaxWidth().height(height.value.dp), ready::set,
+ inputs::add, { cols, rows -> sizes.add(cols to rows) }, { failures.incrementAndGet() }, created = created::set)
+ }
+ compose.waitUntil(15_000) { ready.get() != null || failures.get() != 0 }
+ if (failures.get() != 0) fail("Bundled terminal must load: " + script(requireNotNull(created.get()),
+ "JSON.stringify({viewport:[innerWidth,innerHeight],main:document.getElementById('terminal').getBoundingClientRect().toJSON(),body:getComputedStyle(document.body).height,html:getComputedStyle(document.documentElement).height,mainPosition:getComputedStyle(document.getElementById('terminal')).position,sheets:Array.from(document.styleSheets,s=>({href:s.href,rules:s.cssRules.length}))})"))
+ return requireNotNull(ready.get())
+ }
+
+ private fun script(renderer: TerminalRenderer, source: String): JsonElement = runBlocking {
+ withContext(Dispatchers.Main) {
+ withTimeout(10_000) {
+ suspendCancellableCoroutine { reply -> renderer.view.evaluateJavascript(source) { value ->
+ if (reply.isActive) reply.resume(Json.parseToJsonElement(value))
+ } }
+ }
+ }
+ }
+
+ private fun write(renderer: TerminalRenderer, bytes: ByteArray) = runBlocking {
+ withContext(Dispatchers.Main) { renderer.write(bytes) }
+ }
+ private fun editor(renderer: TerminalRenderer): android.view.inputmethod.InputConnection {
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ compose.waitUntil(5_000) { renderer.view.hasWindowFocus() }
+ instrumentation.waitForIdleSync()
+ android.os.SystemClock.sleep(500) // Native IME attach/restart is asynchronous after WebView focus.
+ val connection = AtomicReference<android.view.inputmethod.InputConnection>()
+ compose.waitUntil(5_000) {
+ compose.runOnUiThread {
+ val info = android.view.inputmethod.EditorInfo()
+ val candidate = renderer.view.onCreateInputConnection(info)
+ if (candidate != null && info.inputType != android.text.InputType.TYPE_NULL) connection.set(candidate)
+ }
+ connection.get() != null
+ }
+ return requireNotNull(connection.get())
+ }
+
+ @Test fun ansiAndSplitUtf8RenderAsTextWithoutExecutingOutput() {
+ val renderer = show()
+ write(renderer, "before\r\u001b[2K\u001b[31mred\u001b[0m\r\n".toByteArray())
+ val unicode = "café 🐈\r\n".toByteArray()
+ write(renderer, unicode.copyOfRange(0, 4))
+ write(renderer, unicode.copyOfRange(4, 8))
+ write(renderer, unicode.copyOfRange(8, unicode.size))
+ write(renderer, "<script>window.outputExecuted=true</script>".toByteArray())
+ val text = script(renderer, "codyncTerminal.text()").jsonPrimitive.content
+ assertTrue(text.contains("red\ncafé 🐈"))
+ assertFalse(text.contains("before"))
+ assertTrue(text.contains("<script>window.outputExecuted=true</script>"))
+ assertEquals("undefined", script(renderer, "typeof window.outputExecuted").jsonPrimitive.content)
+ assertEquals(0, failures.get())
+ }
+
+ @Test fun hardwareKeysReachTheHostInOrderAndTheTerminalFitsAfterResize() {
+ val height = mutableStateOf(400)
+ val renderer = show(height)
+ compose.waitUntil(5_000) { renderer.view.hasWindowFocus() }
+ compose.runOnIdle { renderer.focus() }
+ script(renderer, "window.fixtureKeys = []; for (const type of ['keydown', 'keyup', 'input']) document.addEventListener(type, e => window.fixtureKeys.push([type,e.key,e.keyCode,e.inputType,e.target.value]), true)")
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ compose.runOnUiThread {
+ renderer.view.context.getSystemService(android.view.inputmethod.InputMethodManager::class.java)
+ .hideSoftInputFromWindow(renderer.view.windowToken, 0)
+ }
+ instrumentation.waitForIdleSync()
+ android.os.SystemClock.sleep(500) // Wait for the IME hide animation before injecting physical keys.
+ val keyboard = android.view.InputDevice.getDeviceIds().toList().mapNotNull(android.view.InputDevice::getDevice)
+ .firstOrNull { !it.isVirtual && it.keyboardType == android.view.InputDevice.KEYBOARD_TYPE_ALPHABETIC &&
+ it.keyCharacterMap.get(KeyEvent.KEYCODE_A, 0) == 'a'.code }
+ assertNotNull("The emulator needs an alphabetic hardware keyboard for this gate", keyboard)
+ for ((key, scan) in listOf(KeyEvent.KEYCODE_A to 30, KeyEvent.KEYCODE_B to 48, KeyEvent.KEYCODE_C to 46, KeyEvent.KEYCODE_ENTER to 28)) {
+ val time = android.os.SystemClock.uptimeMillis()
+ val down = KeyEvent(time, time, KeyEvent.ACTION_DOWN, key, 0, 0, requireNotNull(keyboard).id, scan, KeyEvent.FLAG_FROM_SYSTEM, android.view.InputDevice.SOURCE_KEYBOARD)
+ instrumentation.sendKeySync(down); instrumentation.sendKeySync(KeyEvent.changeAction(down, KeyEvent.ACTION_UP))
+ instrumentation.waitForIdleSync()
+ android.os.SystemClock.sleep(100)
+ }
+ repeat(100) { if (inputs.sumOf { it.size } < 4) android.os.SystemClock.sleep(50) }
+ if (inputs.sumOf { it.size } < 4) fail("Fixture keyboard events: " + script(renderer, "[window.fixtureKeys, document.activeElement.tagName,document.hasFocus(),document.visibilityState]") + "; received: " + inputs.flatMap { it.toList() }.toByteArray().toString(Charsets.UTF_8) + "; native focus: " + renderer.view.hasFocus() + "; window focus: " + renderer.view.hasWindowFocus())
+ assertEquals("Fixture keyboard events: " + script(renderer, "window.fixtureKeys"), "abc\r", inputs.flatMap { it.toList() }.toByteArray().toString(Charsets.UTF_8))
+ compose.waitUntil(5_000) { sizes.isNotEmpty() }
+ val originalRows = sizes.last().second
+ compose.runOnIdle { height.value = 200 }
+ compose.waitUntil(5_000) { sizes.last().second < originalRows }
+ assertTrue(sizes.last().first >= 20)
+ assertEquals(0, failures.get())
+ }
+
+ @Test fun imeCommitSendsUnicodeAndPastedTextAsUtf8() {
+ val renderer = show()
+ compose.waitUntil(5_000) { renderer.view.hasWindowFocus() }
+ compose.runOnIdle {
+ renderer.focus(showKeyboard = true)
+ }
+ script(renderer, "codyncTerminal.focus()")
+ val active = editor(renderer)
+ val committed = CompletableDeferred<Boolean>()
+ compose.runOnIdle {
+ val handler = active.handler ?: android.os.Handler(android.os.Looper.getMainLooper())
+ handler.post { committed.complete(active.commitText("café 🐈", 1)) }
+ }
+ val delivered = runBlocking { withTimeout(5_000) { committed.await() } }
+ assertTrue(delivered)
+ repeat(100) { if (inputs.sumOf { it.size } < "café 🐈".toByteArray().size) android.os.SystemClock.sleep(50) }
+ if (inputs.sumOf { it.size } < "café 🐈".toByteArray().size) fail("Fixture IME state: " + script(renderer,
+ "[document.activeElement.value,document.hasFocus(),document.visibilityState]") + "; connection: " + active.javaClass.name + "; received: " + inputs.sumOf { it.size })
+ assertEquals("café 🐈", inputs.flatMap { it.toList() }.toByteArray().toString(Charsets.UTF_8))
+ }
+
+ @Test fun imeCommitThenEnterDoesNotSendADuplicateCharacterOrBackspace() {
+ val renderer = show()
+ compose.waitUntil(5_000) { renderer.view.hasWindowFocus() }
+ compose.runOnIdle { renderer.focus(showKeyboard = true) }
+ script(renderer, "codyncTerminal.focus()")
+ val active = editor(renderer)
+ script(renderer, "window.fixtureKeys = []; for (const type of ['keydown', 'keyup', 'input', 'compositionend']) document.addEventListener(type, e => window.fixtureKeys.push([type,e.key,e.keyCode,e.inputType,e.data,e.target.value]), true)")
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ for (text in listOf("café 🐈", "next")) {
+ val committed = CompletableDeferred<Boolean>()
+ compose.runOnUiThread {
+ val handler = active.handler ?: android.os.Handler(android.os.Looper.getMainLooper())
+ handler.post { committed.complete(active.commitText(text, 1)) }
+ }
+ val delivered = runBlocking { withTimeout(5_000) { committed.await() } }
+ assertTrue(delivered)
+ script(renderer, "true")
+ instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER)
+ instrumentation.waitForIdleSync()
+ android.os.SystemClock.sleep(200)
+ }
+ android.os.SystemClock.sleep(1_000)
+ assertEquals("Fixture input events: " + script(renderer, "window.fixtureKeys"), "café 🐈\rnext\r", inputs.flatMap { it.toList() }.toByteArray().toString(Charsets.UTF_8))
+ }
+
+ @Test fun anImeCompositionSendsOnlyItsFinalUnicodeText() {
+ val renderer = show()
+ compose.waitUntil(5_000) { renderer.view.hasWindowFocus() }
+ compose.runOnIdle { renderer.focus(showKeyboard = true) }
+ script(renderer, "codyncTerminal.focus()")
+ val active = editor(renderer)
+ val composed = CompletableDeferred<Boolean>()
+ script(renderer, "window.fixtureKeys = []; for (const type of ['keydown', 'keyup', 'input', 'compositionstart', 'compositionupdate', 'compositionend']) document.addEventListener(type, e => window.fixtureKeys.push([type,e.key,e.keyCode,e.inputType,e.data,e.target.value]), true)")
+ compose.runOnUiThread {
+ val handler = active.handler ?: android.os.Handler(android.os.Looper.getMainLooper())
+ handler.post { composed.complete(active.setComposingText("cafe", 1) &&
+ active.setComposingText("café 🐈", 1) && active.finishComposingText()) }
+ }
+ val delivered = runBlocking { withTimeout(5_000) { composed.await() } }
+ assertTrue(delivered)
+ compose.waitUntil(5_000) { inputs.sumOf { it.size } >= "café 🐈".toByteArray().size }
+ assertEquals("café 🐈", inputs.flatMap { it.toList() }.toByteArray().toString(Charsets.UTF_8))
+ // The JS bridge reports committed bytes before WebView has necessarily
+ // acknowledged its cleared editor to Android's IME. Await that boundary
+ // before mixing this synthetic composition with a hardware delete.
+ runBlocking { withTimeout(5_000) {
+ while (true) {
+ val empty = CompletableDeferred<Boolean>()
+ compose.runOnUiThread {
+ val handler = active.handler ?: android.os.Handler(android.os.Looper.getMainLooper())
+ handler.post { empty.complete(active.getTextBeforeCursor(256, 0)?.isEmpty() == true &&
+ active.getTextAfterCursor(256, 0)?.isEmpty() == true) }
+ }
+ val acknowledged = empty.await()
+ if (acknowledged) break
+ kotlinx.coroutines.delay(50)
+ }
+ } }
+ InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_DEL)
+ android.os.SystemClock.sleep(1_000)
+ assertEquals("Fixture input events: " + script(renderer, "window.fixtureKeys"), "café 🐈\u007f", inputs.flatMap { it.toList() }.toByteArray().toString(Charsets.UTF_8))
+ }
+
+ @Test fun leavingTheSurfaceCancelsAnUnacknowledgedWrite() {
+ val visible = mutableStateOf(true)
+ val renderer = show(visible = visible)
+ script(renderer, "codyncTerminal.write = function() {}")
+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
+ val write = scope.async { renderer.write("pending".toByteArray()) }
+ script(renderer, "true") // Drain the posted write before removing its view.
+ compose.runOnIdle { visible.value = false }
+ compose.waitUntil { renderer.disposed }
+ runBlocking {
+ try { write.await(); fail("A removed renderer must cancel its waiting writer") }
+ catch (_: CancellationException) { }
+ }
+ scope.cancel()
+ }
+
+ @Test fun onlyHttpLinksOpenAndOutputCannotWriteTheClipboardByItself() {
+ val links = CopyOnWriteArrayList<String>(); val copies = CopyOnWriteArrayList<String>()
+ compose.setContent { TerminalSurface(Modifier.fillMaxWidth().height(400.dp), ready::set, {}, { _, _ -> },
+ { failures.incrementAndGet() }, { links.add(it.toString()) }, copies::add) }
+ compose.waitUntil(15_000) { ready.get() != null || failures.get() != 0 }
+ val renderer = requireNotNull(ready.get())
+ script(renderer, "CodyncTerminal.openLink('javascript:alert(1)'); CodyncTerminal.openLink('file:///private'); CodyncTerminal.openLink('https://user:[email protected]/'); CodyncTerminal.openLink('https://example.com/setup')")
+ compose.waitUntil { links.isNotEmpty() }
+ assertEquals(listOf("https://example.com/setup"), links)
+ write(renderer, "\u001b]52;c;ZmFrZQ==\u0007".toByteArray())
+ assertTrue(copies.isEmpty())
+ }
+
+ @Test fun aTerminatedRendererReleasesItsViewWithoutTerminatingTheActivity() {
+ org.junit.Assume.assumeTrue(android.os.Build.HARDWARE in listOf("ranchu", "goldfish"))
+ var visible by mutableStateOf(true)
+ compose.setContent {
+ if (visible) TerminalSurface(Modifier.fillMaxWidth().height(400.dp), ready::set, {}, { _, _ -> }, {
+ failures.incrementAndGet(); visible = false
+ }) else androidx.compose.material3.Text("Terminal failed safely")
+ }
+ compose.waitUntil(15_000) { ready.get() != null || failures.get() != 0 }
+ val renderer = requireNotNull(ready.get())
+ compose.runOnIdle { assertTrue(requireNotNull(renderer.view.webViewRenderProcess).terminate()) }
+ compose.waitUntil(5_000) { failures.get() == 1 }
+ compose.onNodeWithText("Terminal failed safely").assertIsDisplayed()
+ assertTrue(renderer.disposed)
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt
new file mode 100644
index 00000000..bfe0af5d
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt
@@ -0,0 +1,55 @@
+package com.codync.android
+
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createComposeRule
+import com.codync.android.core.*
+import com.codync.android.design.LocalDismissModal
+import kotlinx.serialization.json.jsonObject
+import org.junit.Assert.*
+import org.junit.Rule
+import org.junit.Test
+
+class UsageScreenTest {
+ @get:Rule val compose = createComposeRule()
+
+ @Test fun unavailableWindowsAndOldReportsNeverBecomeZeroUsage() {
+ val raw = WireJson.parseToJsonElement("""{"providers":[{"id":"future","name":"Future provider","source":"future-source","updatedAt":1,"windows":[{"id":"month","label":"Monthly"}]}]}""")
+ val state = mutableStateOf(AppState(loading = false, setupComplete = true,
+ computers = listOf(Computer("fixture", "Acceptance computer", "fixture")), usage = raw.jsonObject,
+ actualConnection = LinkState.ComputerOffline(null)))
+ val refreshes = mutableListOf<Boolean>()
+ var closed = false
+ compose.setContent { Hosted { CompositionLocalProvider(LocalDismissModal provides { closed = true }) {
+ UsageScreen(state.value) { refreshes.add(it) }
+ } } }
+ compose.onNodeWithText("Future provider").assertIsDisplayed()
+ compose.onNodeWithText("Monthly").assertIsDisplayed()
+ compose.onNodeWithText("—").assertIsDisplayed()
+ compose.onNodeWithText("0%").assertDoesNotExist()
+ compose.onNodeWithText("future-source").assertIsDisplayed()
+ compose.onNodeWithText("Not reported").assertDoesNotExist()
+ assertEquals(emptyList<Boolean>(), refreshes)
+ compose.onNodeWithContentDescription("Collapse").performClick()
+ compose.onNodeWithText("Monthly").assertDoesNotExist()
+ compose.onNodeWithContentDescription("Expand").performClick()
+ compose.onNodeWithText("Monthly").assertIsDisplayed()
+ // Coming online asks for a current report, from cache when the computer has one.
+ compose.runOnUiThread { state.value = state.value.copy(actualConnection = LinkState.Ready(HostRoute.Direct)) }
+ compose.waitForIdle()
+ assertEquals(listOf(false), refreshes)
+ compose.onNodeWithContentDescription("Close").performClick()
+ assertTrue(closed)
+ }
+
+ @Test fun usageExplainsWhenThereIsNoComputerOrNoReportYet() {
+ val state = mutableStateOf(AppState(loading = false))
+ compose.setContent { Hosted { UsageScreen(state.value) {} } }
+ compose.onNodeWithText("No computer yet").assertIsDisplayed()
+ compose.onNodeWithText("Usage shows up once a computer is connected.").assertIsDisplayed()
+ compose.runOnUiThread { state.value = state.value.copy(computers = listOf(Computer("fixture", "Acceptance computer", "fixture"))) }
+ compose.onNodeWithText("No usage yet").assertIsDisplayed()
+ compose.onNodeWithText("Your computer reads the limits from Claude Code and Codex.").assertIsDisplayed()
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetStoreTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetStoreTest.kt
new file mode 100644
index 00000000..fe5b0750
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetStoreTest.kt
@@ -0,0 +1,66 @@
+package com.codync.android
+
+import android.os.Build
+import android.util.AtomicFile
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+import java.io.File
+import java.util.UUID
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+
+class WidgetStoreTest {
+ @Test fun reconnectingDoesNotFreshenCachedActivityUntilTheMirrorCatchesUp() {
+ val cached = AppState(loading = false, rosterLoaded = true, mirrorRevision = 9,
+ actualConnection = LinkState.Ready(HostRoute.Direct), hello = buildJsonObject { put("rev", 10) })
+ assertFalse(cached.widgetBotsCurrent)
+ val caughtUp = cached.copy(mirrorRevision = 10)
+ assertTrue(caughtUp.widgetBotsCurrent)
+ assertFalse(caughtUp.copy(actualConnection = LinkState.Connecting).widgetBotsCurrent)
+ assertFalse(caughtUp.copy(hello = null).widgetBotsCurrent)
+ assertFalse(caughtUp.copy(loading = true).widgetBotsCurrent)
+ }
+
+ @Test fun accountChangesRejectLateResponsesAndForgettingHidesTheirSavedReport() {
+ assumeTrue(Build.PRODUCT.startsWith("sdk"))
+ val context = InstrumentationRegistry.getInstrumentation().targetContext
+ assertNull(PushPreferences.activeUser(context))
+ val originalFile = AtomicFile(File(context.noBackupFilesDir, "widget-owner.json"))
+ val original = if (originalFile.baseFile.exists()) originalFile.readFully() else null
+ val computer = LocalStore(context).computers().single()
+ val first = LocalStore(context, "widget-test-a-" + UUID.randomUUID())
+ val second = LocalStore(context, "widget-test-b-" + UUID.randomUUID())
+ try {
+ first.saveComputers(listOf(computer)); second.saveComputers(listOf(computer))
+ val a = WidgetStore.activate(context, first.contextId)
+ assertTrue(WidgetStore.publish(context, a, computer, listOf(Bot("shared", "Account A", lastMessage = "Private chat")), UsageReport(), true, false))
+ val b = WidgetStore.activate(context, second.contextId)
+ assertTrue(WidgetStore.publish(context, b, computer, listOf(Bot("shared", "Account B")), UsageReport(), true, false))
+ assertFalse(WidgetStore.publish(context, a, computer, listOf(Bot("shared", "Late Account A")), UsageReport(), true, false))
+ assertEquals("Account B", WidgetStore.feed(context).bots.single().name)
+ val revision = WidgetStore.changes.value
+ WidgetStore.publish(context, b, computer, listOf(Bot("shared", "Newer Account B")), UsageReport(), true, false)
+ assertFalse(WidgetStore.publish(context, b, computer, listOf(Bot("shared", "Old background B")), UsageReport(), true, false,
+ expectedRevision = revision))
+ assertEquals("Newer Account B", WidgetStore.feed(context).bots.single().name)
+ val persisted = File(second.directory, "widget-feed.json").readText()
+ assertFalse(persisted.contains("Private chat")); assertFalse(persisted.contains("lastMessage"))
+ second.saveComputers(emptyList())
+ assertNull(WidgetStore.feed(context).computerId)
+ assertTrue(WidgetStore.feed(context).bots.isEmpty())
+ WidgetStore.retire(context, b)
+ assertNull(WidgetStore.owner(context))
+ } finally {
+ val active = WidgetStore.owner(context)
+ if (active?.context in setOf(first.contextId, second.contextId)) WidgetStore.retire(context, active)
+ first.erase(); second.erase()
+ if (original == null) originalFile.delete() else {
+ val output = originalFile.startWrite(); output.write(original); originalFile.finishWrite(output)
+ }
+ WidgetStore.changes.value++
+ }
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetSystemTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetSystemTest.kt
new file mode 100644
index 00000000..900aa84a
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetSystemTest.kt
@@ -0,0 +1,176 @@
+package com.codync.android
+
+import android.appwidget.*
+import android.content.ComponentName
+import android.net.Uri
+import android.graphics.Bitmap
+import android.os.Build
+import android.os.Bundle
+import android.util.AtomicFile
+import android.view.View
+import android.view.ViewGroup
+import android.widget.FrameLayout
+import android.widget.TextView
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.compose.ui.test.onNodeWithContentDescription
+import androidx.compose.ui.test.assertIsDisplayed
+import androidx.compose.ui.test.hasText
+import androidx.compose.ui.test.isHeading
+import androidx.glance.appwidget.GlanceAppWidgetManager
+import androidx.lifecycle.ViewModelProvider
+import androidx.core.view.drawToBitmap
+import androidx.test.platform.app.InstrumentationRegistry
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Rule
+import org.junit.Test
+import java.io.File
+import java.util.UUID
+
+/** Opt-in real AppWidgetHost and encrypted fixture queries; never a user's phone. */
+class WidgetSystemTest {
+ @get:Rule val compose = createAndroidComposeRule<MainActivity>()
+ private val instrumentation get() = InstrumentationRegistry.getInstrumentation()
+
+ @Test fun installedWidgetsRenderResizeSelectProvidersAndClearOnAccountChange() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("widgetHost") == "true")
+ assumeTrue(Build.PRODUCT.startsWith("sdk"))
+ val context = instrumentation.targetContext
+ assertNull(PushPreferences.activeUser(context))
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ compose.waitUntil(30_000) { !store.state.value.loading }
+ val computer = LocalStore(context).computers().single()
+ requireFixtureHost(computer.id)
+ val originalFile = AtomicFile(File(context.noBackupFilesDir, "widget-owner.json"))
+ val original = if (originalFile.baseFile.exists()) originalFile.readFully() else null
+ val local = LocalStore(context, "widget-host-" + UUID.randomUUID())
+ val manager = AppWidgetManager.getInstance(context)
+ val host = AppWidgetHost(context, 49371)
+ val ids = mutableListOf<Int>()
+ var container: FrameLayout? = null
+ try {
+ local.saveComputers(listOf(computer))
+ val owner = WidgetStore.activate(context, local.contextId)
+ val usage = UsageReport(listOf(UsageProvider("claude", "Claude", listOf(UsageWindow("session", "Session", 97.0))),
+ UsageProvider("codex", "Codex", listOf(UsageWindow("daily", "Daily", 24.0)))))
+ WidgetStore.publish(context, owner, computer, (1..6).map { Bot("sample-$it", "Widget bot $it", status = if (it == 1) "needsInput" else "working") }, usage, true, true)
+ instrumentation.runOnMainSync {
+ container = FrameLayout(compose.activity).apply { setPadding(16, 16, 16, 16) }
+ compose.activity.setContentView(container)
+ host.startListening()
+ }
+ for ((receiver, expected) in listOf(BotsWidgetReceiver::class.java to "Widget bot 6",
+ TeamWidgetReceiver::class.java to "Widget bot 1", ProviderWidgetReceiver::class.java to "Session")) {
+ val id = host.allocateAppWidgetId(); ids.add(id)
+ instrumentation.uiAutomation.adoptShellPermissionIdentity(android.Manifest.permission.BIND_APPWIDGET)
+ try { assertTrue("Widget binding was refused", manager.bindAppWidgetIdIfAllowed(id, ComponentName(context, receiver))) }
+ finally { instrumentation.uiAutomation.dropShellPermissionIdentity() }
+ manager.updateAppWidgetOptions(id, Bundle().apply {
+ putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 320); putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, 320)
+ putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, 300); putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, 300)
+ })
+ val info = requireNotNull(manager.getAppWidgetInfo(id))
+ instrumentation.runOnMainSync {
+ val view = host.createView(compose.activity, id, info)
+ container!!.removeAllViews()
+ container!!.addView(view, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
+ (320 * context.resources.displayMetrics.density).toInt()))
+ }
+ val glance = GlanceAppWidgetManager(context).getGlanceIdBy(id)
+ runBlocking { when (receiver) { BotsWidgetReceiver::class.java -> BotsWidget().update(context, glance)
+ TeamWidgetReceiver::class.java -> TeamWidget().update(context, glance); else -> ProviderWidget().update(context, glance) } }
+ waitFor(container!!, expected)
+ assertTrue(CodyncWidgets.installed(context) >= ids.size)
+ if (receiver == ProviderWidgetReceiver::class.java) {
+ WidgetStore.selectProvider(context, id, "codex")
+ runBlocking { ProviderWidget().update(context, glance) }
+ waitFor(container!!, "Daily"); assertTrue(texts(container!!).contains("24%"))
+ manager.updateAppWidgetOptions(id, Bundle().apply {
+ putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 160); putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, 160)
+ putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, 120); putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, 120)
+ })
+ runBlocking { ProviderWidget().update(context, glance) }; waitFor(container!!, "Daily")
+ }
+ snapshot(receiver.simpleName, container!!)
+ }
+ WidgetStore.retire(context, owner)
+ runBlocking { CodyncWidgets.update(context) }
+ waitFor(container!!, "Connect a computer in Codync.")
+ assertFalse(texts(container!!).contains("Daily"))
+ } finally {
+ instrumentation.uiAutomation.dropShellPermissionIdentity()
+ val active = WidgetStore.owner(context)
+ if (active?.context == local.contextId) WidgetStore.retire(context, active)
+ ids.forEach(host::deleteAppWidgetId); host.stopListening(); host.deleteHost()
+ runBlocking { WidgetRefreshWorker.stop(context) }
+ local.erase()
+ if (original == null) originalFile.delete() else {
+ val output = originalFile.startWrite(); output.write(original); originalFile.finishWrite(output)
+ }
+ WidgetStore.changes.value++
+ }
+ }
+
+ @Test fun aBoundedWidgetRefreshReadsTheRealFixtureWithoutChangingItsBots() {
+ assumeTrue(InstrumentationRegistry.getArguments().getString("widgetHost") == "true")
+ assumeTrue(Build.PRODUCT.startsWith("sdk"))
+ val context = instrumentation.targetContext
+ assertNull(PushPreferences.activeUser(context))
+ val store = ViewModelProvider(compose.activity)[AppStore::class.java]
+ compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.rosterLoaded }
+ requireFixtureHost(LocalStore(context).computers().single().id)
+ val started = System.currentTimeMillis()
+ val written = runBlocking { WidgetRefreshWorker.refresh(context) }
+ val feed = WidgetStore.feed(context)
+ // A concurrent foreground report supersedes the slower background read.
+ assertTrue(written || feed.botsAt >= started)
+ assertEquals("local", feed.scope)
+ assertTrue(feed.bots.any { it.name == "Android chat acceptance" })
+ assertTrue(feed.botsAt > System.currentTimeMillis() - 30_000)
+ val link = requireNotNull(widgetIntent(context, feed, usage = true).data)
+ compose.runOnUiThread { store.openLink(link) }
+ compose.waitUntil(10_000) { store.state.value.navigationUsage && store.state.value.selectedBot == null }
+ // The usage sheet's title (it refreshes on its own and on pull).
+ val refresh = hasText("Usage") and isHeading()
+ compose.waitUntil(10_000) { compose.onAllNodes(refresh).fetchSemanticsNodes().size == 1 }
+ compose.onNode(refresh).assertIsDisplayed()
+ compose.activityRule.scenario.recreate()
+ compose.waitUntil(10_000) { compose.onAllNodes(refresh).fetchSemanticsNodes().size == 1 }
+ compose.onNode(refresh).assertIsDisplayed()
+ val request = store.state.value.navigationRequest
+ val foreign = Uri.Builder().scheme("codync").authority("usage").appendQueryParameter("scope", "a".repeat(64))
+ .appendQueryParameter("computer", feed.computerId).build()
+ compose.runOnUiThread { store.openLink(foreign) }
+ compose.waitUntil(10_000) { store.state.value.error?.contains("Switch to the account") == true }
+ assertEquals(request, store.state.value.navigationRequest)
+ }
+
+ private fun texts(root: View): List<String> {
+ var values = emptyList<String>()
+ instrumentation.runOnMainSync {
+ fun visit(view: View): List<String> = buildList {
+ if (view is TextView) add(view.text.toString())
+ if (view is ViewGroup) for (i in 0 until view.childCount) addAll(visit(view.getChildAt(i)))
+ }
+ values = visit(root)
+ }
+ return values
+ }
+ private fun waitFor(root: View, expected: String) = runBlocking {
+ withTimeout(30_000) { while (expected !in texts(root)) delay(100) }
+ }
+ private fun snapshot(name: String, container: ViewGroup) {
+ if (InstrumentationRegistry.getArguments().getString("widgetSnapshots") != "true") return
+ instrumentation.waitForIdleSync()
+ // Layout follows the RemoteViews text update; wait for the drawn frame too.
+ val frame = java.util.concurrent.CountDownLatch(1)
+ instrumentation.runOnMainSync { container.postOnAnimation { container.postOnAnimation { frame.countDown() } } }
+ assertTrue(frame.await(3, java.util.concurrent.TimeUnit.SECONDS))
+ instrumentation.runOnMainSync {
+ val bitmap = container.getChildAt(0).drawToBitmap()
+ File(instrumentation.targetContext.cacheDir, "widget-$name.png").outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/AndroidManifest.xml b/apps/android/app/src/main/AndroidManifest.xml
new file mode 100644
index 00000000..85f02e8a
--- /dev/null
+++ b/apps/android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,89 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+ <uses-permission android:name="android.permission.POST_PROMOTED_NOTIFICATIONS" />
+ <uses-permission android:name="android.permission.CAMERA" />
+ <uses-permission android:name="android.permission.RECORD_AUDIO" />
+ <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
+ <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
+ <uses-feature android:name="android.hardware.microphone" android:required="false" />
+ <queries><intent><action android:name="android.intent.action.TTS_SERVICE" /></intent></queries>
+ <uses-feature android:name="android.hardware.camera" android:required="false" />
+ <uses-feature android:name="android.hardware.camera.any" android:required="false" />
+ <uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
+ <application
+ android:enableOnBackInvokedCallback="true"
+ android:allowBackup="false"
+ android:fullBackupContent="false"
+ android:dataExtractionRules="@xml/data_extraction_rules"
+ android:label="@string/app_name"
+ android:icon="@mipmap/ic_launcher"
+ android:roundIcon="@mipmap/ic_launcher_round"
+ android:supportsRtl="true"
+ android:theme="@style/Theme.Codync"
+ android:usesCleartextTraffic="true">
+ <provider android:name="androidx.core.content.FileProvider"
+ android:authorities="${applicationId}.files" android:exported="false" android:grantUriPermissions="true">
+ <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/shared_file_paths" />
+ </provider>
+ <meta-data android:name="firebase_messaging_installation_id_enabled" android:value="true" />
+ <meta-data android:name="firebase_messaging_notification_delegation_enabled" android:value="false" />
+ <service android:name=".PushService" android:exported="false">
+ <intent-filter><action android:name="com.google.firebase.MESSAGING_EVENT" /></intent-filter>
+ </service>
+ <service android:name=".VoiceService" android:exported="false"
+ android:foregroundServiceType="microphone|mediaPlayback" android:stopWithTask="false" />
+ <receiver android:name=".BotsWidgetReceiver" android:exported="true" android:label="Bots">
+ <intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter>
+ <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_bots" />
+ </receiver>
+ <receiver android:name=".TeamWidgetReceiver" android:exported="true" android:label="Team">
+ <intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter>
+ <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_team" />
+ </receiver>
+ <receiver android:name=".ProviderWidgetReceiver" android:exported="true" android:label="Provider usage">
+ <intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter>
+ <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_provider" />
+ </receiver>
+ <activity android:name=".WidgetConfigurationActivity" android:exported="true">
+ <intent-filter><action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" /></intent-filter>
+ </activity>
+ <!-- Direct ws:// channels already encrypt every inner request with Codync E2E.
+ Core accepts HTTP only for validated direct candidates; cloud remains HTTPS. -->
+ <activity android:name=".MainActivity" android:exported="true" android:launchMode="singleTop"
+ android:windowSoftInputMode="adjustResize">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:scheme="${urlScheme}" android:host="pair" />
+ </intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:scheme="${urlScheme}" android:host="bot" />
+ </intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:scheme="${urlScheme}" android:host="oauth" />
+ </intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:scheme="${urlScheme}" android:host="usage" />
+ </intent-filter>
+ </activity>
+ </application>
+</manifest>
diff --git a/apps/android/app/src/main/assets/licenses/inter-OFL.txt b/apps/android/app/src/main/assets/licenses/inter-OFL.txt
new file mode 100644
index 00000000..9b2ca37b
--- /dev/null
+++ b/apps/android/app/src/main/assets/licenses/inter-OFL.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/apps/android/app/src/main/assets/licenses/jna-APACHE-2.0.txt b/apps/android/app/src/main/assets/licenses/jna-APACHE-2.0.txt
new file mode 100644
index 00000000..f433b1a5
--- /dev/null
+++ b/apps/android/app/src/main/assets/licenses/jna-APACHE-2.0.txt
@@ -0,0 +1,177 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/apps/android/app/src/main/assets/licenses/jna-NOTICE.txt b/apps/android/app/src/main/assets/licenses/jna-NOTICE.txt
new file mode 100644
index 00000000..9d95afbe
--- /dev/null
+++ b/apps/android/app/src/main/assets/licenses/jna-NOTICE.txt
@@ -0,0 +1,26 @@
+SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
+
+Java Native Access (JNA) is licensed under the LGPL, version 2.1
+or later, or (from version 4.0 onward) the Apache License,
+version 2.0.
+
+You can freely decide which license you want to apply to the project.
+
+You may obtain a copy of the LGPL License at:
+
+http://www.gnu.org/licenses/licenses.html
+
+A copy is also included in the downloadable source code package
+containing JNA, in file "LGPL2.1", under the same directory
+as this file.
+
+You may obtain a copy of the Apache License at:
+
+http://www.apache.org/licenses/
+
+A copy is also included in the downloadable source code package
+containing JNA, in file "AL2.0", under the same directory
+as this file.
+
+Commercial support may be available, please e-mail
+twall[at]users[dot]sf[dot]net.
diff --git a/apps/android/app/src/main/assets/licenses/thinking-orbs-LICENSE.txt b/apps/android/app/src/main/assets/licenses/thinking-orbs-LICENSE.txt
new file mode 100644
index 00000000..0e9405a2
--- /dev/null
+++ b/apps/android/app/src/main/assets/licenses/thinking-orbs-LICENSE.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Jakub Antalik
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/apps/android/app/src/main/assets/licenses/voice-manifest.json b/apps/android/app/src/main/assets/licenses/voice-manifest.json
new file mode 100644
index 00000000..cc8aab13
--- /dev/null
+++ b/apps/android/app/src/main/assets/licenses/voice-manifest.json
@@ -0,0 +1,35 @@
+[
+ {
+ "component": "Vosk Android",
+ "version": "0.3.75",
+ "source": "https://github.com/alphacep/vosk-api",
+ "license": "Apache-2.0",
+ "licenseFile": "vosk-APACHE-2.0.txt",
+ "files": {
+ "vosk-APACHE-2.0.txt": "bb618af833c817ab01c1564bd3ec75ba4b4f9cf30910a4a2168e30a674ee8cc6"
+ }
+ },
+ {
+ "component": "Java Native Access",
+ "version": "5.18.1",
+ "source": "https://github.com/java-native-access/jna/tree/5.18.1",
+ "license": "Apache-2.0",
+ "licenseFile": "jna-APACHE-2.0.txt",
+ "noticeFile": "jna-NOTICE.txt",
+ "files": {
+ "jna-APACHE-2.0.txt": "0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594",
+ "jna-NOTICE.txt": "07c938b23950ab7d47a24ef35f9f5da3a05ae164278dc959ad6994135ed59ff1"
+ }
+ },
+ {
+ "component": "Vosk offline English model",
+ "version": "vosk-model-small-en-us-0.15",
+ "source": "https://alphacephei.com/vosk/models/vosk-model-small-en-us-0.15.zip",
+ "license": "Apache-2.0",
+ "licenseFile": "vosk-APACHE-2.0.txt",
+ "sha256": "30f26242c4eb449f948e42cb302dd7a686cb29a3423a8367f99ff41780942498",
+ "files": {
+ "vosk-APACHE-2.0.txt": "bb618af833c817ab01c1564bd3ec75ba4b4f9cf30910a4a2168e30a674ee8cc6"
+ }
+ }
+]
diff --git a/apps/android/app/src/main/assets/licenses/vosk-APACHE-2.0.txt b/apps/android/app/src/main/assets/licenses/vosk-APACHE-2.0.txt
new file mode 100644
index 00000000..ab6497f4
--- /dev/null
+++ b/apps/android/app/src/main/assets/licenses/vosk-APACHE-2.0.txt
@@ -0,0 +1,176 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. this License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
diff --git a/apps/android/app/src/main/assets/terminal/LICENSE.addon-fit b/apps/android/app/src/main/assets/terminal/LICENSE.addon-fit
new file mode 100644
index 00000000..8f178925
--- /dev/null
+++ b/apps/android/app/src/main/assets/terminal/LICENSE.addon-fit
@@ -0,0 +1,19 @@
+Copyright (c) 2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/apps/android/app/src/main/assets/terminal/LICENSE.addon-web-links b/apps/android/app/src/main/assets/terminal/LICENSE.addon-web-links
new file mode 100644
index 00000000..e597698c
--- /dev/null
+++ b/apps/android/app/src/main/assets/terminal/LICENSE.addon-web-links
@@ -0,0 +1,19 @@
+Copyright (c) 2017, The xterm.js authors (https://github.com/xtermjs/xterm.js)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/apps/android/app/src/main/assets/terminal/LICENSE.xterm b/apps/android/app/src/main/assets/terminal/LICENSE.xterm
new file mode 100644
index 00000000..4472336c
--- /dev/null
+++ b/apps/android/app/src/main/assets/terminal/LICENSE.xterm
@@ -0,0 +1,21 @@
+Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
+Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
+Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/apps/android/app/src/main/assets/terminal/addon-fit.js b/apps/android/app/src/main/assets/terminal/addon-fit.js
new file mode 100644
index 00000000..2d391c53
--- /dev/null
+++ b/apps/android/app/src/main/assets/terminal/addon-fit.js
@@ -0,0 +1 @@
+(function(r,t){typeof exports=="object"&&typeof module=="object"?module.exports=t():typeof define=="function"&&define.amd?define([],t):typeof exports=="object"?exports.FitAddon=t():r.FitAddon=t()})(globalThis,(()=>(()=>{"use strict";var r={};return(()=>{var t=r;Object.defineProperty(t,"__esModule",{value:!0}),t.FitAddon=void 0,t.FitAddon=class{activate(e){this._terminal=e}dispose(){}fit(){const e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;const o=this._terminal._core;this._terminal.rows===e.rows&&this._terminal.cols===e.cols||(o._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var n;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;const o=this._terminal.options.scrollback===0?0:((n=this._terminal.options.overviewRuler)==null?void 0:n.width)||14,s=window.getComputedStyle(this._terminal.element.parentElement),l=parseInt(s.getPropertyValue("height")),a=Math.max(0,parseInt(s.getPropertyValue("width"))),i=window.getComputedStyle(this._terminal.element),d=l-(parseInt(i.getPropertyValue("padding-top"))+parseInt(i.getPropertyValue("padding-bottom"))),p=a-(parseInt(i.getPropertyValue("padding-right"))+parseInt(i.getPropertyValue("padding-left")))-o;return{cols:Math.max(2,Math.floor(p/e.css.cell.width)),rows:Math.max(1,Math.floor(d/e.css.cell.height))}}}})(),r})()));
diff --git a/apps/android/app/src/main/assets/terminal/addon-web-links.js b/apps/android/app/src/main/assets/terminal/addon-web-links.js
new file mode 100644
index 00000000..a9de649d
--- /dev/null
+++ b/apps/android/app/src/main/assets/terminal/addon-web-links.js
@@ -0,0 +1 @@
+(function(_,h){typeof exports=="object"&&typeof module=="object"?module.exports=h():typeof define=="function"&&define.amd?define([],h):typeof exports=="object"?exports.WebLinksAddon=h():_.WebLinksAddon=h()})(globalThis,(()=>(()=>{"use strict";var _={490:(d,l)=>{function u(r){try{const e=new URL(r),t=e.password&&e.username?`${e.protocol}//${e.username}:${e.password}@${e.host}`:e.username?`${e.protocol}//${e.username}@${e.host}`:`${e.protocol}//${e.host}`;return r.toLocaleLowerCase().startsWith(t.toLocaleLowerCase())}catch{return!1}}Object.defineProperty(l,"__esModule",{value:!0}),l.LinkComputer=l.WebLinkProvider=void 0,l.WebLinkProvider=class{constructor(r,e,t,n={}){this._terminal=r,this._regex=e,this._handler=t,this._options=n}provideLinks(r,e){const t=p.computeLink(r,this._regex,this._terminal,this._handler);e(this._addCallbacks(t))}_addCallbacks(r){return r.map((e=>(e.leave=this._options.leave,e.hover=(t,n)=>{if(this._options.hover){const{range:c}=e;this._options.hover(t,n,c)}},e)))}};class p{static computeLink(e,t,n,c){const f=new RegExp(t.source,(t.flags||"")+"g"),[i,o]=p._getWindowedLineStrings(e-1,n),s=i.join("");let a;const v=[];for(;a=f.exec(s);){const g=a[0];if(!u(g))continue;const[L,x]=p._mapStrIdx(n,o,0,a.index),[k,W]=p._mapStrIdx(n,L,x,g.length);if(L===-1||x===-1||k===-1||W===-1)continue;const w={start:{x:x+1,y:L+1},end:{x:W,y:k+1}};v.push({range:w,text:g,activate:c})}return v}static _getWindowedLineStrings(e,t){let n,c=e,f=e,i=0,o="";const s=[];if(n=t.buffer.active.getLine(e)){const a=n.translateToString(!0);if(n.isWrapped&&a[0]!==" "){for(i=0;(n=t.buffer.active.getLine(--c))&&i<2048&&(o=n.translateToString(!0),i+=o.length,s.push(o),n.isWrapped&&o.indexOf(" ")===-1););s.reverse()}for(s.push(a),i=0;(n=t.buffer.active.getLine(++f))&&n.isWrapped&&i<2048&&(o=n.translateToString(!0),i+=o.length,s.push(o),o.indexOf(" ")===-1););}return[s,c]}static _mapStrIdx(e,t,n,c){const f=e.buffer.active,i=f.getNullCell();let o=n;for(;c;){const s=f.getLine(t);if(!s)return[-1,-1];for(let a=o;a<s.length;++a){s.getCell(a,i);const v=i.getChars();if(i.getWidth()&&(c-=v.length||1,a===s.length-1&&v==="")){const g=f.getLine(t+1);g&&g.isWrapped&&(g.getCell(0,i),i.getWidth()===2&&(c+=1))}if(c<0)return[t,a]}t++,o=0}return[t,o]}}l.LinkComputer=p}},h={};function b(d){var l=h[d];if(l!==void 0)return l.exports;var u=h[d]={exports:{}};return _[d](u,u.exports,b),u.exports}var m={};return(()=>{var d=m;Object.defineProperty(d,"__esModule",{value:!0}),d.WebLinksAddon=void 0;const l=b(490),u=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function p(r,e){const t=window.open();if(t){try{t.opener=null}catch{}t.location.href=e}else console.warn("Opening link blocked as opener could not be cleared")}d.WebLinksAddon=class{constructor(r=p,e={}){this._handler=r,this._options=e}activate(r){this._terminal=r;const e=this._options,t=e.urlRegex||u;this._linkProvider=this._terminal.registerLinkProvider(new l.WebLinkProvider(this._terminal,t,this._handler,e))}dispose(){var r;(r=this._linkProvider)==null||r.dispose()}}})(),m})()));
diff --git a/apps/android/app/src/main/assets/terminal/bridge.js b/apps/android/app/src/main/assets/terminal/bridge.js
new file mode 100644
index 00000000..108725ab
--- /dev/null
+++ b/apps/android/app/src/main/assets/terminal/bridge.js
@@ -0,0 +1,88 @@
+'use strict';
+(() => {
+ const terminal = new Terminal({fontSize: 13, scrollback: 2000, screenReaderMode: CodyncTerminal.screenReaderEnabled(),
+ theme: {background: '#111111', foreground: '#eeeeee'}, allowProposedApi: false,
+ linkHandler: {activate: (_event, uri) => CodyncTerminal.openLink(uri)}});
+ const fit = new FitAddon.FitAddon();
+ terminal.loadAddon(fit);
+ terminal.loadAddon(new WebLinksAddon.WebLinksAddon((_event, uri) => CodyncTerminal.openLink(uri)));
+ terminal.open(document.getElementById('terminal'));
+ // Modern Android WebView commits text after key 229 without a composition.
+ // Xterm's delayed textarea diff can race Enter's clear and emit a false DEL.
+ // Handle committed input through its public API; actual compositions and
+ // accessibility continue through xterm's composition/screen-reader path.
+ let composing = false;
+ let imeKey = false;
+ const editor = terminal.textarea;
+ editor.addEventListener('compositionstart', () => { composing = true; imeKey = false; }, true);
+ editor.addEventListener('compositionend', () => { composing = false; }, true);
+ terminal.attachCustomKeyEventHandler(event => {
+ if (event.type !== 'keydown') return true;
+ imeKey = event.keyCode === 229 && !composing && !terminal.options.screenReaderMode;
+ return !imeKey;
+ });
+ terminal.element.addEventListener('input', event => {
+ if (event.target !== editor || !imeKey || composing || event.isComposing || terminal.options.screenReaderMode) return;
+ if (event.inputType === 'insertText' && event.data) {
+ event.stopImmediatePropagation();
+ terminal.input(event.data, true);
+ editor.value = '';
+ imeKey = false;
+ } else if (event.inputType === 'deleteContentBackward' || event.inputType === 'deleteContentForward') {
+ event.stopImmediatePropagation();
+ terminal.input(event.inputType === 'deleteContentBackward' ? '\x7f' : '\x1b[3~', true);
+ editor.value = '';
+ imeKey = false;
+ }
+ }, true);
+ function encode(bytes) {
+ let value = '';
+ for (let i = 0; i < bytes.length; i++) value += String.fromCharCode(bytes[i]);
+ return btoa(value);
+ }
+ let started = false;
+ function fitSize() {
+ const size = fit.proposeDimensions();
+ // WebView can attach before xterm has measured its first cell. Retry after render.
+ if (!size || size.cols < 20 || size.rows < 4) return;
+ terminal.resize(Math.min(500, size.cols), Math.min(500, size.rows));
+ CodyncTerminal.resized(terminal.cols, terminal.rows);
+ if (!started) { started = true; CodyncTerminal.ready(); terminal.focus(); }
+ }
+ terminal.onData(value => {
+ CodyncTerminal.input(encode(new TextEncoder().encode(value)));
+ // The remote PTY owns committed text. Retaining it in the local editor
+ // lets Android reopen an earlier word as a new autocorrect composition.
+ if (!composing && !terminal.options.screenReaderMode) editor.value = '';
+ });
+ terminal.onBinary(value => {
+ const bytes = Uint8Array.from(value, char => char.charCodeAt(0) & 255);
+ CodyncTerminal.input(encode(bytes));
+ });
+ terminal.onResize(size => CodyncTerminal.resized(size.cols, size.rows));
+ new ResizeObserver(fitSize).observe(document.getElementById('terminal'));
+ window.codyncTerminal = {
+ write(id, encoded) {
+ const bytes = Uint8Array.from(atob(encoded), char => char.charCodeAt(0));
+ terminal.write(bytes, () => CodyncTerminal.written(id));
+ },
+ reset() { terminal.reset(); },
+ input(enabled) { terminal.options.disableStdin = !enabled; },
+ screenReader(enabled) { terminal.options.screenReaderMode = enabled; },
+ focus() { terminal.focus(); },
+ copySelection() { CodyncTerminal.copy(terminal.getSelection()); },
+ text() {
+ let result = '';
+ const buffer = terminal.buffer.active;
+ for (let i = 0; i < buffer.length; i++) result += buffer.getLine(i).translateToString(true) + '\n';
+ return result;
+ }
+ };
+ let frames = 0;
+ function initialFit() {
+ fitSize();
+ if (!started && ++frames < 600) requestAnimationFrame(initialFit);
+ else if (!started) CodyncTerminal.failed();
+ }
+ requestAnimationFrame(initialFit);
+})();
diff --git a/apps/android/app/src/main/assets/terminal/guard.js b/apps/android/app/src/main/assets/terminal/guard.js
new file mode 100644
index 00000000..fd3f6154
--- /dev/null
+++ b/apps/android/app/src/main/assets/terminal/guard.js
@@ -0,0 +1,3 @@
+'use strict';
+window.addEventListener('error', () => CodyncTerminal.failed());
+window.addEventListener('unhandledrejection', () => CodyncTerminal.failed());
diff --git a/apps/android/app/src/main/assets/terminal/index.html b/apps/android/app/src/main/assets/terminal/index.html
new file mode 100644
index 00000000..e4cbd582
--- /dev/null
+++ b/apps/android/app/src/main/assets/terminal/index.html
@@ -0,0 +1,17 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'none'; frame-src 'none'; img-src data:">
+<link rel="stylesheet" href="xterm.css">
+<link rel="stylesheet" href="terminal.css">
+<script src="guard.js"></script>
+<script src="xterm.js"></script>
+<script src="addon-fit.js"></script>
+<script src="addon-web-links.js"></script>
+<script src="bridge.js" defer></script>
+<title>Agent setup terminal</title>
+</head>
+<body><main id="terminal" aria-label="Agent setup terminal"></main></body>
+</html>
diff --git a/apps/android/app/src/main/assets/terminal/terminal.css b/apps/android/app/src/main/assets/terminal/terminal.css
new file mode 100644
index 00000000..ab44f5d3
--- /dev/null
+++ b/apps/android/app/src/main/assets/terminal/terminal.css
@@ -0,0 +1,2 @@
+html, body { width: 100%; height: 100vh; padding: 0; margin: 0; overflow: hidden; background: #111; color: #eee; }
+#terminal { position: absolute; inset: 0; padding: 0; margin: 0; }
diff --git a/apps/android/app/src/main/assets/terminal/vendor-manifest.json b/apps/android/app/src/main/assets/terminal/vendor-manifest.json
new file mode 100644
index 00000000..31595af8
--- /dev/null
+++ b/apps/android/app/src/main/assets/terminal/vendor-manifest.json
@@ -0,0 +1,76 @@
+[
+ {
+ "package": "@xterm/xterm",
+ "version": "6.0.0",
+ "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==",
+ "license": "MIT",
+ "source": "https://github.com/xtermjs/xterm.js/tree/6.0.0",
+ "files": {
+ "xterm.js": "d2c5cc040dcd2c51cb10d6b7bbdc5712ffc79b0a51d0d309fd70b40badcc2013",
+ "xterm.css": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
+ "LICENSE.xterm": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
+ },
+ "originalFiles": {
+ "xterm.js": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972",
+ "xterm.css": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6",
+ "LICENSE.xterm": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd"
+ },
+ "transform": {
+ "tool": "esbuild",
+ "version": "0.28.2",
+ "target": "chrome83",
+ "options": [
+ "--minify",
+ "--legal-comments=inline"
+ ]
+ }
+ },
+ {
+ "package": "@xterm/addon-fit",
+ "version": "0.11.0",
+ "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==",
+ "license": "MIT",
+ "source": "https://github.com/xtermjs/xterm.js/tree/6.0.0",
+ "files": {
+ "addon-fit.js": "75e9d8ddfc9220281210ee13e2d18f7f0b1c065356456ed3bb2b1dd714911001",
+ "LICENSE.addon-fit": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
+ },
+ "originalFiles": {
+ "addon-fit.js": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527",
+ "LICENSE.addon-fit": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f"
+ },
+ "transform": {
+ "tool": "esbuild",
+ "version": "0.28.2",
+ "target": "chrome83",
+ "options": [
+ "--minify",
+ "--legal-comments=inline"
+ ]
+ }
+ },
+ {
+ "package": "@xterm/addon-web-links",
+ "version": "0.12.0",
+ "integrity": "sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw==",
+ "license": "MIT",
+ "source": "https://github.com/xtermjs/xterm.js/tree/6.0.0",
+ "files": {
+ "addon-web-links.js": "056279a93e1819c06f3b88563bdee135502c2cf128ea0a1f0ccee432c7a2e2c0",
+ "LICENSE.addon-web-links": "689ceb10716bd7a87a804c14951d7c2b818cbd60aab83d540902470ce3b13444"
+ },
+ "originalFiles": {
+ "addon-web-links.js": "b74864125ef3889753b94e61eb4dabb99b2a27f920f0c9a7bd53cbe6d10f032a",
+ "LICENSE.addon-web-links": "689ceb10716bd7a87a804c14951d7c2b818cbd60aab83d540902470ce3b13444"
+ },
+ "transform": {
+ "tool": "esbuild",
+ "version": "0.28.2",
+ "target": "chrome83",
+ "options": [
+ "--minify",
+ "--legal-comments=inline"
+ ]
+ }
+ }
+]
diff --git a/apps/android/app/src/main/assets/terminal/xterm.css b/apps/android/app/src/main/assets/terminal/xterm.css
new file mode 100644
index 00000000..819654e4
--- /dev/null
+++ b/apps/android/app/src/main/assets/terminal/xterm.css
@@ -0,0 +1,285 @@
+/**
+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.
+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
+ * https://github.com/chjj/term.js
+ * @license MIT
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * Originally forked from (with the author's permission):
+ * Fabrice Bellard's javascript vt100 for jslinux:
+ * http://bellard.org/jslinux/
+ * Copyright (c) 2011 Fabrice Bellard
+ * The original design remains. The terminal itself
+ * has been extended to include xterm CSI codes, among
+ * other features.
+ */
+
+/**
+ * Default styles for xterm.js
+ */
+
+.xterm {
+ cursor: text;
+ position: relative;
+ user-select: none;
+ -ms-user-select: none;
+ -webkit-user-select: none;
+}
+
+.xterm.focus,
+.xterm:focus {
+ outline: none;
+}
+
+.xterm .xterm-helpers {
+ position: absolute;
+ top: 0;
+ /**
+ * The z-index of the helpers must be higher than the canvases in order for
+ * IMEs to appear on top.
+ */
+ z-index: 5;
+}
+
+.xterm .xterm-helper-textarea {
+ padding: 0;
+ border: 0;
+ margin: 0;
+ /* Move textarea out of the screen to the far left, so that the cursor is not visible */
+ position: absolute;
+ opacity: 0;
+ left: -9999em;
+ top: 0;
+ width: 0;
+ height: 0;
+ z-index: -5;
+ /** Prevent wrapping so the IME appears against the textarea at the correct position */
+ white-space: nowrap;
+ overflow: hidden;
+ resize: none;
+}
+
+.xterm .composition-view {
+ /* TODO: Composition position got messed up somewhere */
+ background: #000;
+ color: #FFF;
+ display: none;
+ position: absolute;
+ white-space: nowrap;
+ z-index: 1;
+}
+
+.xterm .composition-view.active {
+ display: block;
+}
+
+.xterm .xterm-viewport {
+ /* On OS X this is required in order for the scroll bar to appear fully opaque */
+ background-color: #000;
+ overflow-y: scroll;
+ cursor: default;
+ position: absolute;
+ right: 0;
+ left: 0;
+ top: 0;
+ bottom: 0;
+}
+
+.xterm .xterm-screen {
+ position: relative;
+}
+
+.xterm .xterm-screen canvas {
+ position: absolute;
+ left: 0;
+ top: 0;
+}
+
+.xterm-char-measure-element {
+ display: inline-block;
+ visibility: hidden;
+ position: absolute;
+ top: 0;
+ left: -9999em;
+ line-height: normal;
+}
+
+.xterm.enable-mouse-events {
+ /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
+ cursor: default;
+}
+
+.xterm.xterm-cursor-pointer,
+.xterm .xterm-cursor-pointer {
+ cursor: pointer;
+}
+
+.xterm.column-select.focus {
+ /* Column selection mode */
+ cursor: crosshair;
+}
+
+.xterm .xterm-accessibility:not(.debug),
+.xterm .xterm-message {
+ position: absolute;
+ left: 0;
+ top: 0;
+ bottom: 0;
+ right: 0;
+ z-index: 10;
+ color: transparent;
+ pointer-events: none;
+}
+
+.xterm .xterm-accessibility-tree:not(.debug) *::selection {
+ color: transparent;
+}
+
+.xterm .xterm-accessibility-tree {
+ font-family: monospace;
+ user-select: text;
+ white-space: pre;
+}
+
+.xterm .xterm-accessibility-tree > div {
+ transform-origin: left;
+ width: fit-content;
+}
+
+.xterm .live-region {
+ position: absolute;
+ left: -9999px;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+}
+
+.xterm-dim {
+ /* Dim should not apply to background, so the opacity of the foreground color is applied
+ * explicitly in the generated class and reset to 1 here */
+ opacity: 1 !important;
+}
+
+.xterm-underline-1 { text-decoration: underline; }
+.xterm-underline-2 { text-decoration: double underline; }
+.xterm-underline-3 { text-decoration: wavy underline; }
+.xterm-underline-4 { text-decoration: dotted underline; }
+.xterm-underline-5 { text-decoration: dashed underline; }
+
+.xterm-overline {
+ text-decoration: overline;
+}
+
+.xterm-overline.xterm-underline-1 { text-decoration: overline underline; }
+.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; }
+.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; }
+.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; }
+.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; }
+
+.xterm-strikethrough {
+ text-decoration: line-through;
+}
+
+.xterm-screen .xterm-decoration-container .xterm-decoration {
+ z-index: 6;
+ position: absolute;
+}
+
+.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer {
+ z-index: 7;
+}
+
+.xterm-decoration-overview-ruler {
+ z-index: 8;
+ position: absolute;
+ top: 0;
+ right: 0;
+ pointer-events: none;
+}
+
+.xterm-decoration-top {
+ z-index: 2;
+ position: relative;
+}
+
+
+
+/* Derived from vs/base/browser/ui/scrollbar/media/scrollbar.css */
+
+/* xterm.js customization: Override xterm's cursor style */
+.xterm .xterm-scrollable-element > .scrollbar {
+ cursor: default;
+}
+
+/* Arrows */
+.xterm .xterm-scrollable-element > .scrollbar > .scra {
+ cursor: pointer;
+ font-size: 11px !important;
+}
+
+.xterm .xterm-scrollable-element > .visible {
+ opacity: 1;
+
+ /* Background rule added for IE9 - to allow clicks on dom node */
+ background:rgba(0,0,0,0);
+
+ transition: opacity 100ms linear;
+ /* In front of peek view */
+ z-index: 11;
+}
+.xterm .xterm-scrollable-element > .invisible {
+ opacity: 0;
+ pointer-events: none;
+}
+.xterm .xterm-scrollable-element > .invisible.fade {
+ transition: opacity 800ms linear;
+}
+
+/* Scrollable Content Inset Shadow */
+.xterm .xterm-scrollable-element > .shadow {
+ position: absolute;
+ display: none;
+}
+.xterm .xterm-scrollable-element > .shadow.top {
+ display: block;
+ top: 0;
+ left: 3px;
+ height: 3px;
+ width: 100%;
+ box-shadow: var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset;
+}
+.xterm .xterm-scrollable-element > .shadow.left {
+ display: block;
+ top: 3px;
+ left: 0;
+ height: 100%;
+ width: 3px;
+ box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset;
+}
+.xterm .xterm-scrollable-element > .shadow.top-left-corner {
+ display: block;
+ top: 0;
+ left: 0;
+ height: 3px;
+ width: 3px;
+}
+.xterm .xterm-scrollable-element > .shadow.top.left {
+ box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset;
+}
diff --git a/apps/android/app/src/main/assets/terminal/xterm.js b/apps/android/app/src/main/assets/terminal/xterm.js
new file mode 100644
index 00000000..56953c3a
--- /dev/null
+++ b/apps/android/app/src/main/assets/terminal/xterm.js
@@ -0,0 +1,34 @@
+(function(Oe,De){if(typeof exports=="object"&&typeof module=="object")module.exports=De();else if(typeof define=="function"&&define.amd)define([],De);else{var de=De();for(var Re in de)(typeof exports=="object"?exports:Oe)[Re]=de[Re]}})(globalThis,(()=>(()=>{"use strict";var Oe={2840:function(K,t,_){var i=this&&this.__decorate||function(s,e,l,o){var d,c=arguments.length,a=c<3?e:o===null?o=Object.getOwnPropertyDescriptor(e,l):o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(s,e,l,o);else for(var m=s.length-1;m>=0;m--)(d=s[m])&&(a=(c<3?d(a):c>3?d(e,l,a):d(e,l))||a);return c>3&&a&&Object.defineProperty(e,l,a),a},v=this&&this.__param||function(s,e){return function(l,o){e(l,o,s)}};Object.defineProperty(t,"__esModule",{value:!0}),t.AccessibilityManager=void 0;const n=_(7721),f=_(4292),g=_(7150),p=_(7098),u=_(6501),r=_(7093);let h=class extends g.Disposable{constructor(s,e,l,o){super(),this._terminal=s,this._coreBrowserService=l,this._renderService=o,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";const d=this._coreBrowserService.mainDocument;this._accessibilityContainer=d.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=d.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let c=0;c<this._terminal.rows;c++)this._rowElements[c]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[c]);if(this._topBoundaryFocusListener=c=>this._handleBoundaryFocus(c,0),this._bottomBoundaryFocusListener=c=>this._handleBoundaryFocus(c,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=d.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new f.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize((c=>this._handleResize(c.rows)))),this._register(this._terminal.onRender((c=>this._refreshRows(c.start,c.end)))),this._register(this._terminal.onScroll((()=>this._refreshRows()))),this._register(this._terminal.onA11yChar((c=>this._handleChar(c)))),this._register(this._terminal.onLineFeed((()=>this._handleChar(`
+`)))),this._register(this._terminal.onA11yTab((c=>this._handleTab(c)))),this._register(this._terminal.onKey((c=>this._handleKey(c.key)))),this._register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this._register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this._register((0,r.addDisposableListener)(d,"selectionchange",(()=>this._handleSelectionChange()))),this._register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRowsDimensions(),this._refreshRows(),this._register((0,g.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(s){for(let e=0;e<s;e++)this._handleChar(" ")}_handleChar(s){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==s&&(this._charsToAnnounce+=s):this._charsToAnnounce+=s,s===`
+`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=n.tooMuchOutput.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(s){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(s)||this._charsToConsume.push(s)}_refreshRows(s,e){this._liveRegionDebouncer.refresh(s,e,this._terminal.rows)}_renderRows(s,e){const l=this._terminal.buffer,o=l.lines.length.toString();for(let d=s;d<=e;d++){const c=l.lines.get(l.ydisp+d),a=[],m=(c==null?void 0:c.translateToString(!0,void 0,void 0,a))||"",b=(l.ydisp+d+1).toString(),R=this._rowElements[d];R&&(m.length===0?(R.textContent="\xA0",this._rowColumns.set(R,[0,1])):(R.textContent=m,this._rowColumns.set(R,a)),R.setAttribute("aria-posinset",b),R.setAttribute("aria-setsize",o),this._alignRowWidth(R))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(s,e){const l=s.target,o=this._rowElements[e===0?1:this._rowElements.length-2];if(l.getAttribute("aria-posinset")===(e===0?"1":`${this._terminal.buffer.lines.length}`)||s.relatedTarget!==o)return;let d,c;if(e===0?(d=l,c=this._rowElements.pop(),this._rowContainer.removeChild(c)):(d=this._rowElements.shift(),c=l,this._rowContainer.removeChild(d)),d.removeEventListener("focus",this._topBoundaryFocusListener),c.removeEventListener("focus",this._bottomBoundaryFocusListener),e===0){const a=this._createAccessibilityTreeNode();this._rowElements.unshift(a),this._rowContainer.insertAdjacentElement("afterbegin",a)}else{const a=this._createAccessibilityTreeNode();this._rowElements.push(a),this._rowContainer.appendChild(a)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(e===0?-1:1),this._rowElements[e===0?1:this._rowElements.length-2].focus(),s.preventDefault(),s.stopImmediatePropagation()}_handleSelectionChange(){var m;if(this._rowElements.length===0)return;const s=this._coreBrowserService.mainDocument.getSelection();if(!s)return;if(s.isCollapsed)return void(this._rowContainer.contains(s.anchorNode)&&this._terminal.clearSelection());if(!s.anchorNode||!s.focusNode)return void console.error("anchorNode and/or focusNode are null");let e={node:s.anchorNode,offset:s.anchorOffset},l={node:s.focusNode,offset:s.focusOffset};if((e.node.compareDocumentPosition(l.node)&Node.DOCUMENT_POSITION_PRECEDING||e.node===l.node&&e.offset>l.offset)&&([e,l]=[l,e]),e.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(e={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(e.node))return;const o=this._rowElements.slice(-1)[0];if(l.node.compareDocumentPosition(o)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(l={node:o,offset:((m=o.textContent)==null?void 0:m.length)??0}),!this._rowContainer.contains(l.node))return;const d=({node:b,offset:R})=>{const T=b instanceof Text?b.parentNode:b;let C=parseInt(T==null?void 0:T.getAttribute("aria-posinset"),10)-1;if(isNaN(C))return console.warn("row is invalid. Race condition?"),null;const E=this._rowColumns.get(T);if(!E)return console.warn("columns is null. Race condition?"),null;let A=R<E.length?E[R]:E.slice(-1)[0]+1;return A>=this._terminal.cols&&(++C,A=0),{row:C,column:A}},c=d(e),a=d(l);if(c&&a){if(c.row>a.row||c.row===a.row&&c.column>=a.column)throw new Error("invalid range");this._terminal.select(c.column,c.row,(a.row-c.row)*this._terminal.cols-c.column+a.column)}}_handleResize(s){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>s;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const s=this._coreBrowserService.mainDocument.createElement("div");return s.setAttribute("role","listitem"),s.tabIndex=-1,this._refreshRowDimensions(s),s}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let s=0;s<this._terminal.rows;s++)this._refreshRowDimensions(this._rowElements[s]),this._alignRowWidth(this._rowElements[s])}}_refreshRowDimensions(s){s.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(s){var d,c;s.style.transform="";const e=s.getBoundingClientRect().width,l=(c=(d=this._rowColumns.get(s))==null?void 0:d.slice(-1))==null?void 0:c[0];if(!l)return;const o=l*this._renderService.dimensions.css.cell.width;s.style.transform=`scaleX(${o/e})`}};t.AccessibilityManager=h,t.AccessibilityManager=h=i([v(1,u.IInstantiationService),v(2,p.ICoreBrowserService),v(3,p.IRenderService)],h)},7861:(K,t)=>{function _(f){return f.replace(/\r?\n/g,"\r")}function i(f,g){return g?"\x1B[200~"+f+"\x1B[201~":f}function v(f,g,p,u){f=i(f=_(f),p.decPrivateModes.bracketedPasteMode&&u.rawOptions.ignoreBracketedPasteMode!==!0),p.triggerDataEvent(f,!0),g.value=""}function n(f,g,p){const u=p.getBoundingClientRect(),r=f.clientX-u.left-10,h=f.clientY-u.top-10;g.style.width="20px",g.style.height="20px",g.style.left=`${r}px`,g.style.top=`${h}px`,g.style.zIndex="1000",g.focus()}Object.defineProperty(t,"__esModule",{value:!0}),t.prepareTextForTerminal=_,t.bracketTextForPaste=i,t.copyHandler=function(f,g){f.clipboardData&&f.clipboardData.setData("text/plain",g.selectionText),f.preventDefault()},t.handlePasteEvent=function(f,g,p,u){f.stopPropagation(),f.clipboardData&&v(f.clipboardData.getData("text/plain"),g,p,u)},t.paste=v,t.moveTextAreaUnderMouseCursor=n,t.rightClickHandler=function(f,g,p,u,r){n(f,g,p),r&&u.rightClickSelect(f),g.value=u.selectionText,g.select()}},7174:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorContrastCache=void 0;const i=_(7710);t.ColorContrastCache=class{constructor(){this._color=new i.TwoKeyMap,this._css=new i.TwoKeyMap}setCss(v,n,f){this._css.set(v,n,f)}getCss(v,n){return this._css.get(v,n)}setColor(v,n,f){this._color.set(v,n,f)}getColor(v,n){return this._color.get(v,n)}clear(){this._color.clear(),this._css.clear()}}},1718:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreBrowserTerminal=void 0;const i=_(7861),v=_(7721),n=_(3285),f=_(4017),g=_(4196),p=_(9925),u=_(3618),r=_(3955),h=_(4792),s=_(945),e=_(9574),l=_(9820),o=_(9784),d=_(5783),c=_(2079),a=_(7098),m=_(9078),b=_(4103),R=_(5777),T=_(701),C=_(6107),E=_(3534),A=_(706),N=_(8693),P=_(4720),W=_(6501),w=_(2486),y=_(2840),S=_(8906),D=_(802),M=_(7093),I=_(7150);class F extends R.CoreTerminal{get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(B={}){super(B),this._linkifier=this._register(new I.MutableDisposable),this.browser=T,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new I.MutableDisposable),this._onCursorMove=this._register(new D.Emitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new D.Emitter),this.onKey=this._onKey.event,this._onRender=this._register(new D.Emitter),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new D.Emitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new D.Emitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new D.Emitter),this.onBell=this._onBell.event,this._onFocus=this._register(new D.Emitter),this._onBlur=this._register(new D.Emitter),this._onA11yCharEmitter=this._register(new D.Emitter),this._onA11yTabEmitter=this._register(new D.Emitter),this._onWillOpen=this._register(new D.Emitter),this._setup(),this._decorationService=this._instantiationService.createInstance(P.DecorationService),this._instantiationService.setService(W.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(l.LinkProviderService),this._instantiationService.setService(a.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(n.OscLinkProvider)),this._register(this._inputHandler.onRequestBell((()=>this._onBell.fire()))),this._register(this._inputHandler.onRequestRefreshRows((k=>this.refresh((k==null?void 0:k.start)??0,(k==null?void 0:k.end)??this.rows-1)))),this._register(this._inputHandler.onRequestSendFocus((()=>this._reportFocus()))),this._register(this._inputHandler.onRequestReset((()=>this.reset()))),this._register(this._inputHandler.onRequestWindowsOptionsReport((k=>this._reportWindowsOptions(k)))),this._register(this._inputHandler.onColor((k=>this._handleColorEvent(k)))),this._register(D.Event.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(D.Event.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(D.Event.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(D.Event.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize((k=>this._afterResize(k.cols,k.rows)))),this._register((0,I.toDisposable)((()=>{var k,j;this._customKeyEventHandler=void 0,(j=(k=this.element)==null?void 0:k.parentNode)==null||j.removeChild(this.element)})))}_handleColorEvent(B){if(this._themeService)for(const k of B){let j,$="";switch(k.index){case 256:j="foreground",$="10";break;case 257:j="background",$="11";break;case 258:j="cursor",$="12";break;default:j="ansi",$="4;"+k.index}switch(k.type){case 0:const X=b.color.toColorRGB(j==="ansi"?this._themeService.colors.ansi[k.index]:this._themeService.colors[j]);this.coreService.triggerDataEvent(`${E.C0.ESC}]${$};${(0,N.toRgbString)(X)}${E.C1_ESCAPED.ST}`);break;case 1:if(j==="ansi")this._themeService.modifyColors((V=>V.ansi[k.index]=b.channels.toColor(...k.color)));else{const V=j;this._themeService.modifyColors((Z=>Z[V]=b.channels.toColor(...k.color)))}break;case 2:this._themeService.restoreColor(k.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(B){B?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(y.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(B){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(E.C0.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var B;return(B=this.textarea)==null?void 0:B.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(E.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const B=this.buffer.ybase+this.buffer.y,k=this.buffer.lines.get(B);if(!k)return;const j=Math.min(this.buffer.x,this.cols-1),$=this._renderService.dimensions.css.cell.height,X=k.getWidth(j),V=this._renderService.dimensions.css.cell.width*X,Z=this.buffer.y*this._renderService.dimensions.css.cell.height,se=j*this._renderService.dimensions.css.cell.width;this.textarea.style.left=se+"px",this.textarea.style.top=Z+"px",this.textarea.style.width=V+"px",this.textarea.style.height=$+"px",this.textarea.style.lineHeight=$+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register((0,M.addDisposableListener)(this.element,"copy",(k=>{this.hasSelection()&&(0,i.copyHandler)(k,this._selectionService)})));const B=k=>(0,i.handlePasteEvent)(k,this.textarea,this.coreService,this.optionsService);this._register((0,M.addDisposableListener)(this.textarea,"paste",B)),this._register((0,M.addDisposableListener)(this.element,"paste",B)),T.isFirefox?this._register((0,M.addDisposableListener)(this.element,"mousedown",(k=>{k.button===2&&(0,i.rightClickHandler)(k,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))):this._register((0,M.addDisposableListener)(this.element,"contextmenu",(k=>{(0,i.rightClickHandler)(k,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))),T.isLinux&&this._register((0,M.addDisposableListener)(this.element,"auxclick",(k=>{k.button===1&&(0,i.moveTextAreaUnderMouseCursor)(k,this.textarea,this.screenElement)})))}_bindKeys(){this._register((0,M.addDisposableListener)(this.textarea,"keyup",(B=>this._keyUp(B)),!0)),this._register((0,M.addDisposableListener)(this.textarea,"keydown",(B=>this._keyDown(B)),!0)),this._register((0,M.addDisposableListener)(this.textarea,"keypress",(B=>this._keyPress(B)),!0)),this._register((0,M.addDisposableListener)(this.textarea,"compositionstart",(()=>this._compositionHelper.compositionstart()))),this._register((0,M.addDisposableListener)(this.textarea,"compositionupdate",(B=>this._compositionHelper.compositionupdate(B)))),this._register((0,M.addDisposableListener)(this.textarea,"compositionend",(()=>this._compositionHelper.compositionend()))),this._register((0,M.addDisposableListener)(this.textarea,"input",(B=>this._inputEvent(B)),!0)),this._register(this.onRender((()=>this._compositionHelper.updateCompositionElements())))}open(B){var X;if(!B)throw new Error("Terminal requires a parent element.");if(B.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((X=this.element)==null?void 0:X.ownerDocument.defaultView)&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=B.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),B.appendChild(this.element);const k=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),k.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register((0,M.addDisposableListener)(this.screenElement,"mousemove",(V=>this.updateCursorStyle(V)))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),k.appendChild(this.screenElement);const j=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",v.promptLabel.get()),T.isChromeOS||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",(()=>j.readOnly=this.optionsService.rawOptions.disableStdin))),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(e.CoreBrowserService,this.textarea,B.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(a.ICoreBrowserService,this._coreBrowserService),this._register((0,M.addDisposableListener)(this.textarea,"focus",(V=>this._handleTextAreaFocus(V)))),this._register((0,M.addDisposableListener)(this.textarea,"blur",(()=>this._handleTextAreaBlur()))),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(h.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(a.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(m.ThemeService),this._instantiationService.setService(a.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(s.CharacterJoinerService),this._instantiationService.setService(a.ICharacterJoinerService,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(d.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(a.IRenderService,this._renderService),this._register(this._renderService.onRenderedViewportChange((V=>this._onRender.fire(V)))),this.onResize((V=>this._renderService.resize(V.cols,V.rows))),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(u.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(o.MouseService),this._instantiationService.setService(a.IMouseService,this._mouseService);const $=this._linkifier.value=this._register(this._instantiationService.createInstance(S.Linkifier,this.screenElement));this.element.appendChild(k);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove((()=>{this._renderService.handleCursorMove(),this._syncTextArea()}))),this._register(this.onResize((()=>this._renderService.handleResize(this.cols,this.rows)))),this._register(this.onBlur((()=>this._renderService.handleBlur()))),this._register(this.onFocus((()=>this._renderService.handleFocus()))),this._viewport=this._register(this._instantiationService.createInstance(f.Viewport,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines((V=>{super.scrollLines(V,!1),this.refresh(0,this.rows-1)}))),this._selectionService=this._register(this._instantiationService.createInstance(c.SelectionService,this.element,this.screenElement,$)),this._instantiationService.setService(a.ISelectionService,this._selectionService),this._register(this._selectionService.onRequestScrollLines((V=>this.scrollLines(V.amount,V.suppressScrollEvent)))),this._register(this._selectionService.onSelectionChange((()=>this._onSelectionChange.fire()))),this._register(this._selectionService.onRequestRedraw((V=>this._renderService.handleSelectionChanged(V.start,V.end,V.columnSelectMode)))),this._register(this._selectionService.onLinuxMouseSelection((V=>{this.textarea.value=V,this.textarea.focus(),this.textarea.select()}))),this._register(D.Event.any(this._onScroll.event,this._inputHandler.onScroll)((()=>{var V;this._selectionService.refresh(),(V=this._viewport)==null||V.queueSync()}))),this._register(this._instantiationService.createInstance(g.BufferDecorationRenderer,this.screenElement)),this._register((0,M.addDisposableListener)(this.element,"mousedown",(V=>this._selectionService.handleMouseDown(V)))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(y.AccessibilityManager,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",(V=>this._handleScreenReaderModeOptionChange(V)))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(p.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",(V=>{!this._overviewRulerRenderer&&V&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(p.OverviewRulerRenderer,this._viewportElement,this.screenElement)))})),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(r.DomRenderer,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){const B=this,k=this.element;function j(V){var re,ne,oe,ve,ee;const Z=B._mouseService.getMouseReportCoords(V,B.screenElement);if(!Z)return!1;let se,te;switch(V.overrideType||V.type){case"mousemove":te=32,V.buttons===void 0?(se=3,V.button!==void 0&&(se=V.button<3?V.button:3)):se=1&V.buttons?0:4&V.buttons?1:2&V.buttons?2:3;break;case"mouseup":te=0,se=V.button<3?V.button:3;break;case"mousedown":te=1,se=V.button<3?V.button:3;break;case"wheel":if(B._customWheelEventHandler&&B._customWheelEventHandler(V)===!1)return!1;const ue=V.deltaY;if(ue===0||B.coreMouseService.consumeWheelEvent(V,(ve=(oe=(ne=(re=B._renderService)==null?void 0:re.dimensions)==null?void 0:ne.device)==null?void 0:oe.cell)==null?void 0:ve.height,(ee=B._coreBrowserService)==null?void 0:ee.dpr)===0)return!1;te=ue<0?0:1,se=4;break;default:return!1}return!(te===void 0||se===void 0||se>4)&&B.coreMouseService.triggerMouseEvent({col:Z.col,row:Z.row,x:Z.x,y:Z.y,button:se,action:te,ctrl:V.ctrlKey,alt:V.altKey,shift:V.shiftKey})}const $={mouseup:null,wheel:null,mousedrag:null,mousemove:null},X={mouseup:V=>(j(V),V.buttons||(this._document.removeEventListener("mouseup",$.mouseup),$.mousedrag&&this._document.removeEventListener("mousemove",$.mousedrag)),this.cancel(V)),wheel:V=>(j(V),this.cancel(V,!0)),mousedrag:V=>{V.buttons&&j(V)},mousemove:V=>{V.buttons||j(V)}};this._register(this.coreMouseService.onProtocolChange((V=>{V?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(V)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&V?$.mousemove||(k.addEventListener("mousemove",X.mousemove),$.mousemove=X.mousemove):(k.removeEventListener("mousemove",$.mousemove),$.mousemove=null),16&V?$.wheel||(k.addEventListener("wheel",X.wheel,{passive:!1}),$.wheel=X.wheel):(k.removeEventListener("wheel",$.wheel),$.wheel=null),2&V?$.mouseup||($.mouseup=X.mouseup):(this._document.removeEventListener("mouseup",$.mouseup),$.mouseup=null),4&V?$.mousedrag||($.mousedrag=X.mousedrag):(this._document.removeEventListener("mousemove",$.mousedrag),$.mousedrag=null)}))),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register((0,M.addDisposableListener)(k,"mousedown",(V=>{if(V.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(V))return j(V),$.mouseup&&this._document.addEventListener("mouseup",$.mouseup),$.mousedrag&&this._document.addEventListener("mousemove",$.mousedrag),this.cancel(V)}))),this._register((0,M.addDisposableListener)(k,"wheel",(V=>{var Z,se,te,re,ne;if(!$.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(V)===!1)return!1;if(!this.buffer.hasScrollback){if(V.deltaY===0)return!1;if(B.coreMouseService.consumeWheelEvent(V,(re=(te=(se=(Z=B._renderService)==null?void 0:Z.dimensions)==null?void 0:se.device)==null?void 0:te.cell)==null?void 0:re.height,(ne=B._coreBrowserService)==null?void 0:ne.dpr)===0)return this.cancel(V,!0);const oe=E.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(V.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(oe,!0),this.cancel(V,!0)}}}),{passive:!1}))}refresh(B,k){var j;(j=this._renderService)==null||j.refreshRows(B,k)}updateCursorStyle(B){var k;(k=this._selectionService)!=null&&k.shouldColumnSelect(B)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(B,k){this._viewport?this._viewport.scrollLines(B):super.scrollLines(B,k),this.refresh(0,this.rows-1)}scrollPages(B){this.scrollLines(B*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(B){B&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(B){const k=B-this._bufferService.buffer.ydisp;k!==0&&this.scrollLines(k)}paste(B){(0,i.paste)(B,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(B){this._customKeyEventHandler=B}attachCustomWheelEventHandler(B){this._customWheelEventHandler=B}registerLinkProvider(B){return this._linkProviderService.registerLinkProvider(B)}registerCharacterJoiner(B){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const k=this._characterJoinerService.register(B);return this.refresh(0,this.rows-1),k}deregisterCharacterJoiner(B){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(B)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(B){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+B)}registerDecoration(B){return this._decorationService.registerDecoration(B)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(B,k,j){this._selectionService.setSelection(B,k,j)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var B;(B=this._selectionService)==null||B.clearSelection()}selectAll(){var B;(B=this._selectionService)==null||B.selectAll()}selectLines(B,k){var j;(j=this._selectionService)==null||j.selectLines(B,k)}_keyDown(B){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(B)===!1)return!1;const k=this.browser.isMac&&this.options.macOptionIsMeta&&B.altKey;if(!k&&!this._compositionHelper.keydown(B))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;k||B.key!=="Dead"&&B.key!=="AltGraph"||(this._unprocessedDeadKey=!0);const j=(0,A.evaluateKeyboardEvent)(B,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(B),j.type===3||j.type===2){const $=this.rows-1;return this.scrollLines(j.type===2?-$:$),this.cancel(B,!0)}return j.type===1&&this.selectAll(),!!this._isThirdLevelShift(this.browser,B)||(j.cancel&&this.cancel(B,!0),!j.key||!!(B.key&&!B.ctrlKey&&!B.altKey&&!B.metaKey&&B.key.length===1&&B.key.charCodeAt(0)>=65&&B.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(j.key!==E.C0.ETX&&j.key!==E.C0.CR||(this.textarea.value=""),this._onKey.fire({key:j.key,domEvent:B}),this._showCursor(),this.coreService.triggerDataEvent(j.key,!0),!this.optionsService.rawOptions.screenReaderMode||B.altKey||B.ctrlKey?this.cancel(B,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(B,k){const j=B.isMac&&!this.options.macOptionIsMeta&&k.altKey&&!k.ctrlKey&&!k.metaKey||B.isWindows&&k.altKey&&k.ctrlKey&&!k.metaKey||B.isWindows&&k.getModifierState("AltGraph");return k.type==="keypress"?j:j&&(!k.keyCode||k.keyCode>47)}_keyUp(B){this._keyDownSeen=!1,this._customKeyEventHandler&&this._customKeyEventHandler(B)===!1||((function(k){return k.keyCode===16||k.keyCode===17||k.keyCode===18})(B)||this.focus(),this.updateCursorStyle(B),this._keyPressHandled=!1)}_keyPress(B){let k;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(B)===!1)return!1;if(this.cancel(B),B.charCode)k=B.charCode;else if(B.which===null||B.which===void 0)k=B.keyCode;else{if(B.which===0||B.charCode===0)return!1;k=B.which}return!(!k||(B.altKey||B.ctrlKey||B.metaKey)&&!this._isThirdLevelShift(this.browser,B)||(k=String.fromCharCode(k),this._onKey.fire({key:k,domEvent:B}),this._showCursor(),this.coreService.triggerDataEvent(k,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(B){if(B.data&&B.inputType==="insertText"&&(!B.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const k=B.data;return this.coreService.triggerDataEvent(k,!0),this.cancel(B),!0}return!1}resize(B,k){B!==this.cols||k!==this.rows?super.resize(B,k):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(B,k){var j;(j=this._charSizeService)==null||j.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let B=1;B<this.rows;B++)this.buffer.lines.push(this.buffer.getBlankLine(C.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){var k;this.options.rows=this.rows,this.options.cols=this.cols;const B=this._customKeyEventHandler;this._setup(),super.reset(),(k=this._selectionService)==null||k.reset(),this._decorationService.reset(),this._customKeyEventHandler=B,this.refresh(0,this.rows-1)}clearTextureAtlas(){var B;(B=this._renderService)==null||B.clearTextureAtlas()}_reportFocus(){var B;(B=this.element)!=null&&B.classList.contains("focus")?this.coreService.triggerDataEvent(E.C0.ESC+"[I"):this.coreService.triggerDataEvent(E.C0.ESC+"[O")}_reportWindowsOptions(B){if(this._renderService)switch(B){case w.WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:const k=this._renderService.dimensions.css.canvas.width.toFixed(0),j=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${E.C0.ESC}[4;${j};${k}t`);break;case w.WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:const $=this._renderService.dimensions.css.cell.width.toFixed(0),X=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${E.C0.ESC}[6;${X};${$}t`)}}cancel(B,k){if(this.options.cancelEvents||k)return B.preventDefault(),B.stopPropagation(),!1}}t.CoreBrowserTerminal=F},8906:function(K,t,_){var i=this&&this.__decorate||function(h,s,e,l){var o,d=arguments.length,c=d<3?s:l===null?l=Object.getOwnPropertyDescriptor(s,e):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")c=Reflect.decorate(h,s,e,l);else for(var a=h.length-1;a>=0;a--)(o=h[a])&&(c=(d<3?o(c):d>3?o(s,e,c):o(s,e))||c);return d>3&&c&&Object.defineProperty(s,e,c),c},v=this&&this.__param||function(h,s){return function(e,l){s(e,l,h)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Linkifier=void 0;const n=_(7150),f=_(6501),g=_(7098),p=_(802),u=_(7093);let r=class extends n.Disposable{get currentLink(){return this._currentLink}constructor(h,s,e,l,o){super(),this._element=h,this._mouseService=s,this._renderService=e,this._bufferService=l,this._linkProviderService=o,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new p.Emitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new p.Emitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register((0,n.toDisposable)((()=>{var d;(0,n.dispose)(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(d=this._activeProviderReplies)==null||d.clear()}))),this._register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this._register((0,u.addDisposableListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this._register((0,u.addDisposableListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register((0,u.addDisposableListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register((0,u.addDisposableListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(h){this._lastMouseEvent=h;const s=this._positionFromMouseEvent(h,this._element,this._mouseService);if(!s)return;this._isMouseOut=!1;const e=h.composedPath();for(let l=0;l<e.length;l++){const o=e[l];if(o.classList.contains("xterm"))break;if(o.classList.contains("xterm-hover"))return}this._lastBufferCell&&s.x===this._lastBufferCell.x&&s.y===this._lastBufferCell.y||(this._handleHover(s),this._lastBufferCell=s)}_handleHover(h){if(this._activeLine!==h.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(h,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,h)||(this._clearCurrentLink(),this._askForLink(h,!0))}_askForLink(h,s){var l,o;this._activeProviderReplies&&s||((l=this._activeProviderReplies)==null||l.forEach((d=>{d==null||d.forEach((c=>{c.link.dispose&&c.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=h.y);let e=!1;for(const[d,c]of this._linkProviderService.linkProviders.entries())s?(o=this._activeProviderReplies)!=null&&o.get(d)&&(e=this._checkLinkProviderResult(d,h,e)):c.provideLinks(h.y,(a=>{var b,R;if(this._isMouseOut)return;const m=a==null?void 0:a.map((T=>({link:T})));(b=this._activeProviderReplies)==null||b.set(d,m),e=this._checkLinkProviderResult(d,h,e),((R=this._activeProviderReplies)==null?void 0:R.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(h.y,this._activeProviderReplies)}))}_removeIntersectingLinks(h,s){const e=new Set;for(let l=0;l<s.size;l++){const o=s.get(l);if(o)for(let d=0;d<o.length;d++){const c=o[d],a=c.link.range.start.y<h?0:c.link.range.start.x,m=c.link.range.end.y>h?this._bufferService.cols:c.link.range.end.x;for(let b=a;b<=m;b++){if(e.has(b)){o.splice(d--,1);break}e.add(b)}}}}_checkLinkProviderResult(h,s,e){var d;if(!this._activeProviderReplies)return e;const l=this._activeProviderReplies.get(h);let o=!1;for(let c=0;c<h;c++)this._activeProviderReplies.has(c)&&!this._activeProviderReplies.get(c)||(o=!0);if(!o&&l){const c=l.find((a=>this._linkAtPosition(a.link,s)));c&&(e=!0,this._handleNewLink(c))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!e)for(let c=0;c<this._activeProviderReplies.size;c++){const a=(d=this._activeProviderReplies.get(c))==null?void 0:d.find((m=>this._linkAtPosition(m.link,s)));if(a){e=!0,this._handleNewLink(a);break}}return e}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(h){if(!this._currentLink)return;const s=this._positionFromMouseEvent(h,this._element,this._mouseService);var e,l;s&&this._mouseDownLink&&(e=this._mouseDownLink.link,l=this._currentLink.link,e.text===l.text&&e.range.start.x===l.range.start.x&&e.range.start.y===l.range.start.y&&e.range.end.x===l.range.end.x&&e.range.end.y===l.range.end.y)&&this._linkAtPosition(this._currentLink.link,s)&&this._currentLink.link.activate(h,this._currentLink.link.text)}_clearCurrentLink(h,s){this._currentLink&&this._lastMouseEvent&&(!h||!s||this._currentLink.link.range.start.y>=h&&this._currentLink.link.range.end.y<=s)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,n.dispose)(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(h){if(!this._lastMouseEvent)return;const s=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);s&&this._linkAtPosition(h.link,s)&&(this._currentLink=h,this._currentLink.state={decorations:{underline:h.link.decorations===void 0||h.link.decorations.underline,pointerCursor:h.link.decorations===void 0||h.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,h.link,this._lastMouseEvent),h.link.decorations={},Object.defineProperties(h.link.decorations,{pointerCursor:{get:()=>{var e,l;return(l=(e=this._currentLink)==null?void 0:e.state)==null?void 0:l.decorations.pointerCursor},set:e=>{var l;(l=this._currentLink)!=null&&l.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",e))}},underline:{get:()=>{var e,l;return(l=(e=this._currentLink)==null?void 0:e.state)==null?void 0:l.decorations.underline},set:e=>{var l,o,d;(l=this._currentLink)!=null&&l.state&&((d=(o=this._currentLink)==null?void 0:o.state)==null?void 0:d.decorations.underline)!==e&&(this._currentLink.state.decorations.underline=e,this._currentLink.state.isHovered&&this._fireUnderlineEvent(h.link,e))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((e=>{if(!this._currentLink)return;const l=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,o=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=l&&this._currentLink.link.range.end.y<=o&&(this._clearCurrentLink(l,o),this._lastMouseEvent)){const d=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);d&&this._askForLink(d,!1)}}))))}_linkHover(h,s,e){var l;(l=this._currentLink)!=null&&l.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(s,!0),this._currentLink.state.decorations.pointerCursor&&h.classList.add("xterm-cursor-pointer")),s.hover&&s.hover(e,s.text)}_fireUnderlineEvent(h,s){const e=h.range,l=this._bufferService.buffer.ydisp,o=this._createLinkUnderlineEvent(e.start.x-1,e.start.y-l-1,e.end.x,e.end.y-l-1,void 0);(s?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(o)}_linkLeave(h,s,e){var l;(l=this._currentLink)!=null&&l.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(s,!1),this._currentLink.state.decorations.pointerCursor&&h.classList.remove("xterm-cursor-pointer")),s.leave&&s.leave(e,s.text)}_linkAtPosition(h,s){const e=h.range.start.y*this._bufferService.cols+h.range.start.x,l=h.range.end.y*this._bufferService.cols+h.range.end.x,o=s.y*this._bufferService.cols+s.x;return e<=o&&o<=l}_positionFromMouseEvent(h,s,e){const l=e.getCoords(h,s,this._bufferService.cols,this._bufferService.rows);if(l)return{x:l[0],y:l[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(h,s,e,l,o){return{x1:h,y1:s,x2:e,y2:l,cols:this._bufferService.cols,fg:o}}};t.Linkifier=r,t.Linkifier=r=i([v(1,g.IMouseService),v(2,g.IRenderService),v(3,f.IBufferService),v(4,g.ILinkProviderService)],r)},7721:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.tooMuchOutput=t.promptLabel=void 0;let _="Terminal input";const i={get:()=>_,set:f=>_=f};t.promptLabel=i;let v="Too much output to announce, navigate to rows manually to read";const n={get:()=>v,set:f=>v=f};t.tooMuchOutput=n},3285:function(K,t,_){var i=this&&this.__decorate||function(u,r,h,s){var e,l=arguments.length,o=l<3?r:s===null?s=Object.getOwnPropertyDescriptor(r,h):s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(u,r,h,s);else for(var d=u.length-1;d>=0;d--)(e=u[d])&&(o=(l<3?e(o):l>3?e(r,h,o):e(r,h))||o);return l>3&&o&&Object.defineProperty(r,h,o),o},v=this&&this.__param||function(u,r){return function(h,s){r(h,s,u)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OscLinkProvider=void 0;const n=_(3055),f=_(6501);let g=class{constructor(u,r,h){this._bufferService=u,this._optionsService=r,this._oscLinkService=h}provideLinks(u,r){var m;const h=this._bufferService.buffer.lines.get(u-1);if(!h)return void r(void 0);const s=[],e=this._optionsService.rawOptions.linkHandler,l=new n.CellData,o=h.getTrimmedLength();let d=-1,c=-1,a=!1;for(let b=0;b<o;b++)if(c!==-1||h.hasContent(b)){if(h.loadCell(b,l),l.hasExtendedAttrs()&&l.extended.urlId){if(c===-1){c=b,d=l.extended.urlId;continue}a=l.extended.urlId!==d}else c!==-1&&(a=!0);if(a||c!==-1&&b===o-1){const R=(m=this._oscLinkService.getLinkData(d))==null?void 0:m.uri;if(R){const T={start:{x:c+1,y:u},end:{x:b+(a||b!==o-1?0:1),y:u}};let C=!1;if(!(e!=null&&e.allowNonHttpProtocols))try{const E=new URL(R);["http:","https:"].includes(E.protocol)||(C=!0)}catch{C=!0}C||s.push({text:R,range:T,activate:(E,A)=>e?e.activate(E,A,T):p(0,A),hover:(E,A)=>{var N;return(N=e==null?void 0:e.hover)==null?void 0:N.call(e,E,A,T)},leave:(E,A)=>{var N;return(N=e==null?void 0:e.leave)==null?void 0:N.call(e,E,A,T)}})}a=!1,l.hasExtendedAttrs()&&l.extended.urlId?(c=b,d=l.extended.urlId):(c=-1,d=-1)}}r(s)}};function p(u,r){if(confirm(`Do you want to navigate to ${r}?
+
+WARNING: This link could potentially be dangerous`)){const h=window.open();if(h){try{h.opener=null}catch{}h.location.href=r}else console.warn("Opening link blocked as opener could not be cleared")}}t.OscLinkProvider=g,t.OscLinkProvider=g=i([v(0,f.IBufferService),v(1,f.IOptionsService),v(2,f.IOscLinkService)],g)},4852:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RenderDebouncer=void 0,t.RenderDebouncer=class{constructor(_,i){this._renderCallback=_,this._coreBrowserService=i,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(_){return this._refreshCallbacks.push(_),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh()))),this._animationFrame}refresh(_,i,v){this._rowCount=v,_=_!==void 0?_:0,i=i!==void 0?i:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,_):_,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,i):i,this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return void this._runRefreshCallbacks();const _=Math.max(this._rowStart,0),i=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(_,i),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const _ of this._refreshCallbacks)_(0);this._refreshCallbacks=[]}}},4292:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeBasedDebouncer=void 0,t.TimeBasedDebouncer=class{constructor(_,i=1e3){this._renderCallback=_,this._debounceThresholdMS=i,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(_,i,v){this._rowCount=v,_=_!==void 0?_:0,i=i!==void 0?i:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,_):_,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,i):i;const n=performance.now();if(n-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=n,this._innerRefresh();else if(!this._additionalRefreshRequested){const f=n-this._lastRefreshMs,g=this._debounceThresholdMS-f;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout((()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0}),g)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;const _=Math.max(this._rowStart,0),i=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(_,i)}}},9302:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_ANSI_COLORS=void 0;const i=_(4103);t.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const v=[i.css.toColor("#2e3436"),i.css.toColor("#cc0000"),i.css.toColor("#4e9a06"),i.css.toColor("#c4a000"),i.css.toColor("#3465a4"),i.css.toColor("#75507b"),i.css.toColor("#06989a"),i.css.toColor("#d3d7cf"),i.css.toColor("#555753"),i.css.toColor("#ef2929"),i.css.toColor("#8ae234"),i.css.toColor("#fce94f"),i.css.toColor("#729fcf"),i.css.toColor("#ad7fa8"),i.css.toColor("#34e2e2"),i.css.toColor("#eeeeec")],n=[0,95,135,175,215,255];for(let f=0;f<216;f++){const g=n[f/36%6|0],p=n[f/6%6|0],u=n[f%6];v.push({css:i.channels.toCss(g,p,u),rgba:i.channels.toRgba(g,p,u)})}for(let f=0;f<24;f++){const g=8+10*f;v.push({css:i.channels.toCss(g,g,g),rgba:i.channels.toRgba(g,g,g)})}return v})())},4017:function(K,t,_){var i=this&&this.__decorate||function(e,l,o,d){var c,a=arguments.length,m=a<3?l:d===null?d=Object.getOwnPropertyDescriptor(l,o):d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")m=Reflect.decorate(e,l,o,d);else for(var b=e.length-1;b>=0;b--)(c=e[b])&&(m=(a<3?c(m):a>3?c(l,o,m):c(l,o))||m);return a>3&&m&&Object.defineProperty(l,o,m),m},v=this&&this.__param||function(e,l){return function(o,d){l(o,d,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Viewport=void 0;const n=_(7098),f=_(7150),g=_(6501),p=_(7093),u=_(8234),r=_(802),h=_(9881);let s=class extends f.Disposable{constructor(e,l,o,d,c,a,m,b){super(),this._bufferService=o,this._optionsService=m,this._renderService=b,this._onRequestScrollLines=this._register(new r.Emitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;const R=this._register(new h.Scrollable({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:T=>(0,p.scheduleAtNextAnimationFrame)(d.window,T)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",(()=>{R.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)}))),this._scrollableElement=this._register(new u.SmoothScrollableElement(l,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},R)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],(()=>this._scrollableElement.updateOptions(this._getChangeOptions())))),this._register(c.onProtocolChange((T=>{this._scrollableElement.updateOptions({handleMouseWheel:!(16&T)})}))),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(r.Event.runAndSubscribe(a.onChangeColors,(()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css}))),e.appendChild(this._scrollableElement.getDomNode()),this._register((0,f.toDisposable)((()=>this._scrollableElement.getDomNode().remove()))),this._styleElement=d.mainDocument.createElement("style"),l.appendChild(this._styleElement),this._register((0,f.toDisposable)((()=>this._styleElement.remove()))),this._register(r.Event.runAndSubscribe(a.onChangeColors,(()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${a.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${a.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${a.colors.scrollbarSliderActiveBackground.css};`,"}"].join(`
+`)}))),this._register(this._bufferService.onResize((()=>this.queueSync()))),this._register(this._bufferService.buffers.onBufferActivate((()=>{this._latestYDisp=void 0,this.queueSync()}))),this._register(this._bufferService.onScroll((()=>this._sync()))),this._register(this._scrollableElement.onScroll((T=>this._handleScroll(T))))}scrollLines(e){const l=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:l.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,l){l&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!l,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.width)||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback((()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)})))}_sync(e=this._bufferService.buffer.ydisp){this._renderService&&!this._isSyncing&&(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;const l=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),o=l-this._bufferService.buffer.ydisp;o!==0&&(this._latestYDisp=l,this._onRequestScrollLines.fire(o)),this._isHandlingScroll=!1}};t.Viewport=s,t.Viewport=s=i([v(2,g.IBufferService),v(3,n.ICoreBrowserService),v(4,g.ICoreMouseService),v(5,n.IThemeService),v(6,g.IOptionsService),v(7,n.IRenderService)],s)},4196:function(K,t,_){var i=this&&this.__decorate||function(u,r,h,s){var e,l=arguments.length,o=l<3?r:s===null?s=Object.getOwnPropertyDescriptor(r,h):s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(u,r,h,s);else for(var d=u.length-1;d>=0;d--)(e=u[d])&&(o=(l<3?e(o):l>3?e(r,h,o):e(r,h))||o);return l>3&&o&&Object.defineProperty(r,h,o),o},v=this&&this.__param||function(u,r){return function(h,s){r(h,s,u)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferDecorationRenderer=void 0;const n=_(7098),f=_(7150),g=_(6501);let p=class extends f.Disposable{constructor(u,r,h,s,e){super(),this._screenElement=u,this._bufferService=r,this._coreBrowserService=h,this._decorationService=s,this._renderService=e,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange((()=>this._doRefreshDecorations()))),this._register(this._renderService.onDimensionsChange((()=>{this._dimensionsChanged=!0,this._queueRefresh()}))),this._register(this._coreBrowserService.onDprChange((()=>this._queueRefresh()))),this._register(this._bufferService.buffers.onBufferActivate((()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt}))),this._register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh()))),this._register(this._decorationService.onDecorationRemoved((l=>this._removeDecoration(l)))),this._register((0,f.toDisposable)((()=>{this._container.remove(),this._decorationElements.clear()})))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback((()=>{this._doRefreshDecorations(),this._animationFrame=void 0})))}_doRefreshDecorations(){for(const u of this._decorationService.decorations)this._renderDecoration(u);this._dimensionsChanged=!1}_renderDecoration(u){this._refreshStyle(u),this._dimensionsChanged&&this._refreshXPosition(u)}_createElement(u){var s;const r=this._coreBrowserService.mainDocument.createElement("div");r.classList.add("xterm-decoration"),r.classList.toggle("xterm-decoration-top-layer",((s=u==null?void 0:u.options)==null?void 0:s.layer)==="top"),r.style.width=`${Math.round((u.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,r.style.height=(u.options.height||1)*this._renderService.dimensions.css.cell.height+"px",r.style.top=(u.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",r.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const h=u.options.x??0;return h&&h>this._bufferService.cols&&(r.style.display="none"),this._refreshXPosition(u,r),r}_refreshStyle(u){const r=u.marker.line-this._bufferService.buffers.active.ydisp;if(r<0||r>=this._bufferService.rows)u.element&&(u.element.style.display="none",u.onRenderEmitter.fire(u.element));else{let h=this._decorationElements.get(u);h||(h=this._createElement(u),u.element=h,this._decorationElements.set(u,h),this._container.appendChild(h),u.onDispose((()=>{this._decorationElements.delete(u),h.remove()}))),h.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(h.style.width=`${Math.round((u.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,h.style.height=(u.options.height||1)*this._renderService.dimensions.css.cell.height+"px",h.style.top=r*this._renderService.dimensions.css.cell.height+"px",h.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),u.onRenderEmitter.fire(h)}}_refreshXPosition(u,r=u.element){if(!r)return;const h=u.options.x??0;(u.options.anchor||"left")==="right"?r.style.right=h?h*this._renderService.dimensions.css.cell.width+"px":"":r.style.left=h?h*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(u){var r;(r=this._decorationElements.get(u))==null||r.remove(),this._decorationElements.delete(u),u.dispose()}};t.BufferDecorationRenderer=p,t.BufferDecorationRenderer=p=i([v(1,g.IBufferService),v(2,n.ICoreBrowserService),v(3,g.IDecorationService),v(4,n.IRenderService)],p)},957:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorZoneStore=void 0,t.ColorZoneStore=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(_){if(_.options.overviewRulerOptions){for(const i of this._zones)if(i.color===_.options.overviewRulerOptions.color&&i.position===_.options.overviewRulerOptions.position){if(this._lineIntersectsZone(i,_.marker.line))return;if(this._lineAdjacentToZone(i,_.marker.line,_.options.overviewRulerOptions.position))return void this._addLineToZone(i,_.marker.line)}if(this._zonePoolIndex<this._zonePool.length)return this._zonePool[this._zonePoolIndex].color=_.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=_.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=_.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=_.marker.line,void this._zones.push(this._zonePool[this._zonePoolIndex++]);this._zones.push({color:_.options.overviewRulerOptions.color,position:_.options.overviewRulerOptions.position,startBufferLine:_.marker.line,endBufferLine:_.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(_){this._linePadding=_}_lineIntersectsZone(_,i){return i>=_.startBufferLine&&i<=_.endBufferLine}_lineAdjacentToZone(_,i,v){return i>=_.startBufferLine-this._linePadding[v||"full"]&&i<=_.endBufferLine+this._linePadding[v||"full"]}_addLineToZone(_,i){_.startBufferLine=Math.min(_.startBufferLine,i),_.endBufferLine=Math.max(_.endBufferLine,i)}}},9925:function(K,t,_){var i=this&&this.__decorate||function(e,l,o,d){var c,a=arguments.length,m=a<3?l:d===null?d=Object.getOwnPropertyDescriptor(l,o):d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")m=Reflect.decorate(e,l,o,d);else for(var b=e.length-1;b>=0;b--)(c=e[b])&&(m=(a<3?c(m):a>3?c(l,o,m):c(l,o))||m);return a>3&&m&&Object.defineProperty(l,o,m),m},v=this&&this.__param||function(e,l){return function(o,d){l(o,d,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OverviewRulerRenderer=void 0;const n=_(957),f=_(7098),g=_(7150),p=_(6501),u={full:0,left:0,center:0,right:0},r={full:0,left:0,center:0,right:0},h={full:0,left:0,center:0,right:0};let s=class extends g.Disposable{get _width(){var e;return((e=this._optionsService.options.overviewRuler)==null?void 0:e.width)||0}constructor(e,l,o,d,c,a,m,b){var T;super(),this._viewportElement=e,this._screenElement=l,this._bufferService=o,this._decorationService=d,this._renderService=c,this._optionsService=a,this._themeService=m,this._coreBrowserService=b,this._colorZoneStore=new n.ColorZoneStore,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(T=this._viewportElement.parentElement)==null||T.insertBefore(this._canvas,this._viewportElement),this._register((0,g.toDisposable)((()=>{var C;return(C=this._canvas)==null?void 0:C.remove()})));const R=this._canvas.getContext("2d");if(!R)throw new Error("Ctx cannot be null");this._ctx=R,this._register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh(void 0,!0)))),this._register(this._decorationService.onDecorationRemoved((()=>this._queueRefresh(void 0,!0)))),this._register(this._renderService.onRenderedViewportChange((()=>this._queueRefresh()))),this._register(this._bufferService.buffers.onBufferActivate((()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"}))),this._register(this._bufferService.onScroll((()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())}))),this._register(this._renderService.onRender((()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)}))),this._register(this._coreBrowserService.onDprChange((()=>this._queueRefresh(!0)))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",(()=>this._queueRefresh(!0)))),this._register(this._themeService.onChangeColors((()=>this._queueRefresh()))),this._queueRefresh(!0)}_refreshDrawConstants(){const e=Math.floor((this._canvas.width-1)/3),l=Math.ceil((this._canvas.width-1)/3);r.full=this._canvas.width,r.left=e,r.center=l,r.right=e,this._refreshDrawHeightConstants(),h.full=1,h.left=1,h.center=1+r.left,h.right=1+r.left+r.center}_refreshDrawHeightConstants(){u.full=Math.round(2*this._coreBrowserService.dpr);const e=this._canvas.height/this._bufferService.buffer.lines.length,l=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);u.left=l,u.center=l,u.right=l}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*u.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*u.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*u.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*u.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(const l of this._decorationService.decorations)this._colorZoneStore.addDecoration(l);this._ctx.lineWidth=1,this._renderRulerOutline();const e=this._colorZoneStore.zones;for(const l of e)l.position!=="full"&&this._renderColorZone(l);for(const l of e)l.position==="full"&&this._renderColorZone(l);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(h[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-u[e.position||"full"]/2),r[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+u[e.position||"full"]))}_queueRefresh(e,l){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=l||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>{this._refreshDecorations(),this._animationFrame=void 0})))}};t.OverviewRulerRenderer=s,t.OverviewRulerRenderer=s=i([v(2,p.IBufferService),v(3,p.IDecorationService),v(4,f.IRenderService),v(5,p.IOptionsService),v(6,f.IThemeService),v(7,f.ICoreBrowserService)],s)},3618:function(K,t,_){var i=this&&this.__decorate||function(u,r,h,s){var e,l=arguments.length,o=l<3?r:s===null?s=Object.getOwnPropertyDescriptor(r,h):s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(u,r,h,s);else for(var d=u.length-1;d>=0;d--)(e=u[d])&&(o=(l<3?e(o):l>3?e(r,h,o):e(r,h))||o);return l>3&&o&&Object.defineProperty(r,h,o),o},v=this&&this.__param||function(u,r){return function(h,s){r(h,s,u)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CompositionHelper=void 0;const n=_(7098),f=_(6501),g=_(3534);let p=class{get isComposing(){return this._isComposing}constructor(u,r,h,s,e,l){this._textarea=u,this._compositionView=r,this._bufferService=h,this._optionsService=s,this._coreService=e,this._renderService=l,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(u){this._compositionView.textContent=u.data,this.updateCompositionElements(),setTimeout((()=>{this._compositionPosition.end=this._textarea.value.length}),0)}compositionend(){this._finalizeComposition(!0)}keydown(u){if(this._isComposing||this._isSendingComposition){if(u.keyCode===20||u.keyCode===229||u.keyCode===16||u.keyCode===17||u.keyCode===18)return!1;this._finalizeComposition(!1)}return u.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(u){if(this._compositionView.classList.remove("active"),this._isComposing=!1,u){const r={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout((()=>{if(this._isSendingComposition){let h;this._isSendingComposition=!1,r.start+=this._dataAlreadySent.length,h=this._isComposing?this._textarea.value.substring(r.start,this._compositionPosition.start):this._textarea.value.substring(r.start),h.length>0&&this._coreService.triggerDataEvent(h,!0)}}),0)}else{this._isSendingComposition=!1;const r=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(r,!0)}}_handleAnyTextareaChanges(){const u=this._textarea.value;setTimeout((()=>{if(!this._isComposing){const r=this._textarea.value,h=r.replace(u,"");this._dataAlreadySent=h,r.length>u.length?this._coreService.triggerDataEvent(h,!0):r.length<u.length?this._coreService.triggerDataEvent(`${g.C0.DEL}`,!0):r.length===u.length&&r!==u&&this._coreService.triggerDataEvent(r,!0)}}),0)}updateCompositionElements(u){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){const r=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),h=this._renderService.dimensions.css.cell.height,s=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,e=r*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=e+"px",this._compositionView.style.top=s+"px",this._compositionView.style.height=h+"px",this._compositionView.style.lineHeight=h+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";const l=this._compositionView.getBoundingClientRect();this._textarea.style.left=e+"px",this._textarea.style.top=s+"px",this._textarea.style.width=Math.max(l.width,1)+"px",this._textarea.style.height=Math.max(l.height,1)+"px",this._textarea.style.lineHeight=l.height+"px"}u||setTimeout((()=>this.updateCompositionElements(!0)),0)}}};t.CompositionHelper=p,t.CompositionHelper=p=i([v(2,f.IBufferService),v(3,f.IOptionsService),v(4,f.ICoreService),v(5,n.IRenderService)],p)},5251:(K,t)=>{function _(i,v,n){const f=n.getBoundingClientRect(),g=i.getComputedStyle(n),p=parseInt(g.getPropertyValue("padding-left")),u=parseInt(g.getPropertyValue("padding-top"));return[v.clientX-f.left-p,v.clientY-f.top-u]}Object.defineProperty(t,"__esModule",{value:!0}),t.getCoordsRelativeToElement=_,t.getCoords=function(i,v,n,f,g,p,u,r,h){if(!p)return;const s=_(i,v,n);return s?(s[0]=Math.ceil((s[0]+(h?u/2:0))/u),s[1]=Math.ceil(s[1]/r),s[0]=Math.min(Math.max(s[0],1),f+(h?1:0)),s[1]=Math.min(Math.max(s[1],1),g),s):void 0}},9686:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.moveToCellSequence=function(r,h,s,e){const l=s.buffer.x,o=s.buffer.y;if(!s.buffer.hasScrollback)return(function(a,m,b,R,T,C){return v(m,R,T,C).length===0?"":u(g(a,m,a,m-n(m,T),!1,T).length,p("D",C))})(l,o,0,h,s,e)+v(o,h,s,e)+(function(a,m,b,R,T,C){let E;E=v(m,R,T,C).length>0?R-n(R,T):m;const A=R,N=(function(P,W,w,y,S,D){let M;return M=v(w,y,S,D).length>0?y-n(y,S):W,P<w&&M<=y||P>=w&&M<y?"C":"D"})(a,m,b,R,T,C);return u(g(a,E,b,A,N==="C",T).length,p(N,C))})(l,o,r,h,s,e);let d;if(o===h)return d=l>r?"D":"C",u(Math.abs(l-r),p(d,e));d=o>h?"D":"C";const c=Math.abs(o-h);return u((function(a,m){return m.cols-a})(o>h?r:l,s)+(c-1)*s.cols+1+((o>h?l:r)-1),p(d,e))};const i=_(3534);function v(r,h,s,e){const l=r-n(r,s),o=h-n(h,s),d=Math.abs(l-o)-(function(c,a,m){let b=0;const R=c-n(c,m),T=a-n(a,m);for(let C=0;C<Math.abs(R-T);C++){const E=f(c,a)==="A"?-1:1,A=m.buffer.lines.get(R+E*C);A!=null&&A.isWrapped&&b++}return b})(r,h,s);return u(d,p(f(r,h),e))}function n(r,h){let s=0,e=h.buffer.lines.get(r),l=e==null?void 0:e.isWrapped;for(;l&&r>=0&&r<h.rows;)s++,e=h.buffer.lines.get(--r),l=e==null?void 0:e.isWrapped;return s}function f(r,h){return r>h?"A":"B"}function g(r,h,s,e,l,o){let d=r,c=h,a="";for(;(d!==s||c!==e)&&c>=0&&c<o.buffer.lines.length;)d+=l?1:-1,l&&d>o.cols-1?(a+=o.buffer.translateBufferLineToString(c,!1,r,d),d=0,r=0,c++):!l&&d<0&&(a+=o.buffer.translateBufferLineToString(c,!1,0,r+1),d=o.cols-1,r=d,c--);return a+o.buffer.translateBufferLineToString(c,!1,r,d)}function p(r,h){const s=h?"O":"[";return i.C0.ESC+s+r}function u(r,h){r=Math.floor(r);let s="";for(let e=0;e<r;e++)s+=h;return s}},3955:function(K,t,_){var i=this&&this.__decorate||function(C,E,A,N){var P,W=arguments.length,w=W<3?E:N===null?N=Object.getOwnPropertyDescriptor(E,A):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")w=Reflect.decorate(C,E,A,N);else for(var y=C.length-1;y>=0;y--)(P=C[y])&&(w=(W<3?P(w):W>3?P(E,A,w):P(E,A))||w);return W>3&&w&&Object.defineProperty(E,A,w),w},v=this&&this.__param||function(C,E){return function(A,N){E(A,N,C)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRenderer=void 0;const n=_(1433),f=_(2744),g=_(9176),p=_(6181),u=_(2274),r=_(7098),h=_(4103),s=_(7150),e=_(6501),l=_(802),o="xterm-dom-renderer-owner-",d="xterm-rows",c="xterm-fg-",a="xterm-bg-",m="xterm-focus",b="xterm-selection";let R=1,T=class extends s.Disposable{constructor(C,E,A,N,P,W,w,y,S,D,M,I,F,H){super(),this._terminal=C,this._document=E,this._element=A,this._screenElement=N,this._viewportElement=P,this._helperContainer=W,this._linkifier2=w,this._charSizeService=S,this._optionsService=D,this._bufferService=M,this._coreService=I,this._coreBrowserService=F,this._themeService=H,this._terminalClass=R++,this._rowElements=[],this._selectionRenderModel=(0,u.createSelectionRenderModel)(),this.onRequestRedraw=this._register(new l.Emitter).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(d),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(b),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,p.createRenderDimensions)(),this._updateDimensions(),this._register(this._optionsService.onOptionChange((()=>this._handleOptionsChanged()))),this._register(this._themeService.onChangeColors((B=>this._injectCss(B)))),this._injectCss(this._themeService.colors),this._rowFactory=y.createInstance(n.DomRendererRowFactory,document),this._element.classList.add(o+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline((B=>this._handleLinkHover(B)))),this._register(this._linkifier2.onHideLinkUnderline((B=>this._handleLinkLeave(B)))),this._register((0,s.toDisposable)((()=>{this._element.classList.remove(o+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()}))),this._widthCache=new f.WidthCache(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){const C=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*C,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*C),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/C),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/C),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(const A of this._rowElements)A.style.width=`${this.dimensions.css.canvas.width}px`,A.style.height=`${this.dimensions.css.cell.height}px`,A.style.lineHeight=`${this.dimensions.css.cell.height}px`,A.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const E=`${this._terminalSelector} .${d} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=E,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(C){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let E=`${this._terminalSelector} .${d} { pointer-events: none; color: ${C.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;E+=`${this._terminalSelector} .${d} .xterm-dim { color: ${h.color.multiplyOpacity(C.foreground,.5).css};}`,E+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;const A=`blink_underline_${this._terminalClass}`,N=`blink_bar_${this._terminalClass}`,P=`blink_block_${this._terminalClass}`;E+=`@keyframes ${A} { 50% { border-bottom-style: hidden; }}`,E+=`@keyframes ${N} { 50% { box-shadow: none; }}`,E+=`@keyframes ${P} { 0% { background-color: ${C.cursor.css}; color: ${C.cursorAccent.css}; } 50% { background-color: inherit; color: ${C.cursor.css}; }}`,E+=`${this._terminalSelector} .${d}.${m} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${A} 1s step-end infinite;}${this._terminalSelector} .${d}.${m} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${N} 1s step-end infinite;}${this._terminalSelector} .${d}.${m} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${P} 1s step-end infinite;}${this._terminalSelector} .${d} .xterm-cursor.xterm-cursor-block { background-color: ${C.cursor.css}; color: ${C.cursorAccent.css};}${this._terminalSelector} .${d} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${C.cursor.css} !important; color: ${C.cursorAccent.css} !important;}${this._terminalSelector} .${d} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${C.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${d} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${C.cursor.css} inset;}${this._terminalSelector} .${d} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${C.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,E+=`${this._terminalSelector} .${b} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${b} div { position: absolute; background-color: ${C.selectionBackgroundOpaque.css};}${this._terminalSelector} .${b} div { position: absolute; background-color: ${C.selectionInactiveBackgroundOpaque.css};}`;for(const[W,w]of C.ansi.entries())E+=`${this._terminalSelector} .${c}${W} { color: ${w.css}; }${this._terminalSelector} .${c}${W}.xterm-dim { color: ${h.color.multiplyOpacity(w,.5).css}; }${this._terminalSelector} .${a}${W} { background-color: ${w.css}; }`;E+=`${this._terminalSelector} .${c}${g.INVERTED_DEFAULT_COLOR} { color: ${h.color.opaque(C.background).css}; }${this._terminalSelector} .${c}${g.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${h.color.multiplyOpacity(h.color.opaque(C.background),.5).css}; }${this._terminalSelector} .${a}${g.INVERTED_DEFAULT_COLOR} { background-color: ${C.foreground.css}; }`,this._themeStyleElement.textContent=E}_setDefaultSpacing(){const C=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${C}px`,this._rowFactory.defaultSpacing=C}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(C,E){for(let A=this._rowElements.length;A<=E;A++){const N=this._document.createElement("div");this._rowContainer.appendChild(N),this._rowElements.push(N)}for(;this._rowElements.length>E;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(C,E){this._refreshRowElements(C,E),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(m),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(m),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(C,E,A){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(C,E,A),this.renderRows(0,this._bufferService.rows-1),!C||!E||(this._selectionRenderModel.update(this._terminal,C,E,A),!this._selectionRenderModel.hasSelection))return;const N=this._selectionRenderModel.viewportStartRow,P=this._selectionRenderModel.viewportEndRow,W=this._selectionRenderModel.viewportCappedStartRow,w=this._selectionRenderModel.viewportCappedEndRow,y=this._document.createDocumentFragment();if(A){const S=C[0]>E[0];y.appendChild(this._createSelectionElement(W,S?E[0]:C[0],S?C[0]:E[0],w-W+1))}else{const S=N===W?C[0]:0,D=W===P?E[0]:this._bufferService.cols;y.appendChild(this._createSelectionElement(W,S,D));const M=w-W-1;if(y.appendChild(this._createSelectionElement(W+1,0,this._bufferService.cols,M)),W!==w){const I=P===w?E[0]:this._bufferService.cols;y.appendChild(this._createSelectionElement(w,0,I))}}this._selectionContainer.appendChild(y)}_createSelectionElement(C,E,A,N=1){const P=this._document.createElement("div"),W=E*this.dimensions.css.cell.width;let w=this.dimensions.css.cell.width*(A-E);return W+w>this.dimensions.css.canvas.width&&(w=this.dimensions.css.canvas.width-W),P.style.height=N*this.dimensions.css.cell.height+"px",P.style.top=C*this.dimensions.css.cell.height+"px",P.style.left=`${W}px`,P.style.width=`${w}px`,P}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(const C of this._rowElements)C.replaceChildren()}renderRows(C,E){const A=this._bufferService.buffer,N=A.ybase+A.y,P=Math.min(A.x,this._bufferService.cols-1),W=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,w=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,y=this._optionsService.rawOptions.cursorInactiveStyle;for(let S=C;S<=E;S++){const D=S+A.ydisp,M=this._rowElements[S],I=A.lines.get(D);if(!M||!I)break;M.replaceChildren(...this._rowFactory.createRow(I,D,D===N,w,y,P,W,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${o}${this._terminalClass}`}_handleLinkHover(C){this._setCellUnderline(C.x1,C.x2,C.y1,C.y2,C.cols,!0)}_handleLinkLeave(C){this._setCellUnderline(C.x1,C.x2,C.y1,C.y2,C.cols,!1)}_setCellUnderline(C,E,A,N,P,W){A<0&&(C=0),N<0&&(E=0);const w=this._bufferService.rows-1;A=Math.max(Math.min(A,w),0),N=Math.max(Math.min(N,w),0),P=Math.min(P,this._bufferService.cols);const y=this._bufferService.buffer,S=y.ybase+y.y,D=Math.min(y.x,P-1),M=this._optionsService.rawOptions.cursorBlink,I=this._optionsService.rawOptions.cursorStyle,F=this._optionsService.rawOptions.cursorInactiveStyle;for(let H=A;H<=N;++H){const B=H+y.ydisp,k=this._rowElements[H],j=y.lines.get(B);if(!k||!j)break;k.replaceChildren(...this._rowFactory.createRow(j,B,B===S,I,F,D,M,this.dimensions.css.cell.width,this._widthCache,W?H===A?C:0:-1,W?(H===N?E:P)-1:-1))}}};t.DomRenderer=T,t.DomRenderer=T=i([v(7,e.IInstantiationService),v(8,r.ICharSizeService),v(9,e.IOptionsService),v(10,e.IBufferService),v(11,e.ICoreService),v(12,r.ICoreBrowserService),v(13,r.IThemeService)],T)},1433:function(K,t,_){var i=this&&this.__decorate||function(d,c,a,m){var b,R=arguments.length,T=R<3?c:m===null?m=Object.getOwnPropertyDescriptor(c,a):m;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(d,c,a,m);else for(var C=d.length-1;C>=0;C--)(b=d[C])&&(T=(R<3?b(T):R>3?b(c,a,T):b(c,a))||T);return R>3&&T&&Object.defineProperty(c,a,T),T},v=this&&this.__param||function(d,c){return function(a,m){c(a,m,d)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRendererRowFactory=void 0;const n=_(9176),f=_(8938),g=_(3055),p=_(6501),u=_(4103),r=_(7098),h=_(945),s=_(6181),e=_(5451);let l=class{constructor(d,c,a,m,b,R,T){this._document=d,this._characterJoinerService=c,this._optionsService=a,this._coreBrowserService=m,this._coreService=b,this._decorationService=R,this._themeService=T,this._workCell=new g.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(d,c,a){this._selectionStart=d,this._selectionEnd=c,this._columnSelectMode=a}createRow(d,c,a,m,b,R,T,C,E,A,N){const P=[],W=this._characterJoinerService.getJoinedCharacters(c),w=this._themeService.colors;let y,S=d.getNoBgTrimmedLength();a&&S<R+1&&(S=R+1);let D=0,M="",I=0,F=0,H=0,B=0,k=!1,j=0,$=!1,X=0,V=0;const Z=[],se=A!==-1&&N!==-1;for(let te=0;te<S;te++){d.loadCell(te,this._workCell);let re=this._workCell.getWidth();if(re===0)continue;let ne=!1,oe=te>=V,ve=te,ee=this._workCell;if(W.length>0&&te===W[0][0]&&oe){const ie=W.shift(),Te=this._isCellInSelection(ie[0],c);for(I=ie[0]+1;I<ie[1];I++)oe&&(oe=Te===this._isCellInSelection(I,c));oe&&(oe=!a||R<ie[0]||R>=ie[1]),oe?(ne=!0,ee=new h.JoinedCellData(this._workCell,d.translateToString(!0,ie[0],ie[1]),ie[1]-ie[0]),ve=ie[1]-1,re=ee.getWidth()):V=ie[1]}const ue=this._isCellInSelection(te,c),Ae=a&&te===R,ce=se&&te>=A&&te<=N;let Se=!1;this._decorationService.forEachDecorationAtCell(te,c,void 0,(ie=>{Se=!0}));let Ce=ee.getChars()||f.WHITESPACE_CELL_CHAR;if(Ce===" "&&(ee.isUnderline()||ee.isOverline())&&(Ce="\xA0"),X=re*C-E.get(Ce,ee.isBold(),ee.isItalic()),y){if(D&&(ue&&$||!ue&&!$&&ee.bg===F)&&(ue&&$&&w.selectionForeground||ee.fg===H)&&ee.extended.ext===B&&ce===k&&X===j&&!Ae&&!ne&&!Se&&oe){ee.isInvisible()?M+=f.WHITESPACE_CELL_CHAR:M+=Ce,D++;continue}D&&(y.textContent=M),y=this._document.createElement("span"),D=0,M=""}else y=this._document.createElement("span");if(F=ee.bg,H=ee.fg,B=ee.extended.ext,k=ce,j=X,$=ue,ne&&R>=te&&R<=ve&&(R=te),!this._coreService.isCursorHidden&&Ae&&this._coreService.isCursorInitialized){if(Z.push("xterm-cursor"),this._coreBrowserService.isFocused)T&&Z.push("xterm-cursor-blink"),Z.push(m==="bar"?"xterm-cursor-bar":m==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(b)switch(b){case"outline":Z.push("xterm-cursor-outline");break;case"block":Z.push("xterm-cursor-block");break;case"bar":Z.push("xterm-cursor-bar");break;case"underline":Z.push("xterm-cursor-underline")}}if(ee.isBold()&&Z.push("xterm-bold"),ee.isItalic()&&Z.push("xterm-italic"),ee.isDim()&&Z.push("xterm-dim"),M=ee.isInvisible()?f.WHITESPACE_CELL_CHAR:ee.getChars()||f.WHITESPACE_CELL_CHAR,ee.isUnderline()&&(Z.push(`xterm-underline-${ee.extended.underlineStyle}`),M===" "&&(M="\xA0"),!ee.isUnderlineColorDefault()))if(ee.isUnderlineColorRGB())y.style.textDecorationColor=`rgb(${e.AttributeData.toColorRGB(ee.getUnderlineColor()).join(",")})`;else{let ie=ee.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&ee.isBold()&&ie<8&&(ie+=8),y.style.textDecorationColor=w.ansi[ie].css}ee.isOverline()&&(Z.push("xterm-overline"),M===" "&&(M="\xA0")),ee.isStrikethrough()&&Z.push("xterm-strikethrough"),ce&&(y.style.textDecoration="underline");let le=ee.getFgColor(),_e=ee.getFgColorMode(),he=ee.getBgColor(),be=ee.getBgColorMode();const Le=!!ee.isInverse();if(Le){const ie=le;le=he,he=ie;const Te=_e;_e=be,be=Te}let fe,ye,pe,ge=!1;switch(this._decorationService.forEachDecorationAtCell(te,c,void 0,(ie=>{ie.options.layer!=="top"&&ge||(ie.backgroundColorRGB&&(be=50331648,he=ie.backgroundColorRGB.rgba>>8&16777215,fe=ie.backgroundColorRGB),ie.foregroundColorRGB&&(_e=50331648,le=ie.foregroundColorRGB.rgba>>8&16777215,ye=ie.foregroundColorRGB),ge=ie.options.layer==="top")})),!ge&&ue&&(fe=this._coreBrowserService.isFocused?w.selectionBackgroundOpaque:w.selectionInactiveBackgroundOpaque,he=fe.rgba>>8&16777215,be=50331648,ge=!0,w.selectionForeground&&(_e=50331648,le=w.selectionForeground.rgba>>8&16777215,ye=w.selectionForeground)),ge&&Z.push("xterm-decoration-top"),be){case 16777216:case 33554432:pe=w.ansi[he],Z.push(`xterm-bg-${he}`);break;case 50331648:pe=u.channels.toColor(he>>16,he>>8&255,255&he),this._addStyle(y,`background-color:#${o((he>>>0).toString(16),"0",6)}`);break;default:Le?(pe=w.foreground,Z.push(`xterm-bg-${n.INVERTED_DEFAULT_COLOR}`)):pe=w.background}switch(fe||ee.isDim()&&(fe=u.color.multiplyOpacity(pe,.5)),_e){case 16777216:case 33554432:ee.isBold()&&le<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(le+=8),this._applyMinimumContrast(y,pe,w.ansi[le],ee,fe,void 0)||Z.push(`xterm-fg-${le}`);break;case 50331648:const ie=u.channels.toColor(le>>16&255,le>>8&255,255&le);this._applyMinimumContrast(y,pe,ie,ee,fe,ye)||this._addStyle(y,`color:#${o(le.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(y,pe,w.foreground,ee,fe,ye)||Le&&Z.push(`xterm-fg-${n.INVERTED_DEFAULT_COLOR}`)}Z.length&&(y.className=Z.join(" "),Z.length=0),Ae||ne||Se||!oe?y.textContent=M:D++,X!==this.defaultSpacing&&(y.style.letterSpacing=`${X}px`),P.push(y),te=ve}return y&&D&&(y.textContent=M),P}_applyMinimumContrast(d,c,a,m,b,R){if(this._optionsService.rawOptions.minimumContrastRatio===1||(0,s.treatGlyphAsBackgroundColor)(m.getCode()))return!1;const T=this._getContrastCache(m);let C;if(b||R||(C=T.getColor(c.rgba,a.rgba)),C===void 0){const E=this._optionsService.rawOptions.minimumContrastRatio/(m.isDim()?2:1);C=u.color.ensureContrastRatio(b||c,R||a,E),T.setColor((b||c).rgba,(R||a).rgba,C??null)}return!!C&&(this._addStyle(d,`color:${C.css}`),!0)}_getContrastCache(d){return d.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(d,c){d.setAttribute("style",`${d.getAttribute("style")||""}${c};`)}_isCellInSelection(d,c){const a=this._selectionStart,m=this._selectionEnd;return!(!a||!m)&&(this._columnSelectMode?a[0]<=m[0]?d>=a[0]&&c>=a[1]&&d<m[0]&&c<=m[1]:d<a[0]&&c>=a[1]&&d>=m[0]&&c<=m[1]:c>a[1]&&c<m[1]||a[1]===m[1]&&c===a[1]&&d>=a[0]&&d<m[0]||a[1]<m[1]&&c===m[1]&&d<m[0]||a[1]<m[1]&&c===a[1]&&d>=a[0])}};function o(d,c,a){for(;d.length<a;)d=c+d;return d}t.DomRendererRowFactory=l,t.DomRendererRowFactory=l=i([v(1,r.ICharacterJoinerService),v(2,p.IOptionsService),v(3,r.ICoreBrowserService),v(4,p.ICoreService),v(5,p.IDecorationService),v(6,r.IThemeService)],l)},2744:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WidthCache=void 0,t.WidthCache=class{constructor(_,i){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=_.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const v=_.createElement("span");v.classList.add("xterm-char-measure-element");const n=_.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold";const f=_.createElement("span");f.classList.add("xterm-char-measure-element"),f.style.fontStyle="italic";const g=_.createElement("span");g.classList.add("xterm-char-measure-element"),g.style.fontWeight="bold",g.style.fontStyle="italic",this._measureElements=[v,n,f,g],this._container.appendChild(v),this._container.appendChild(n),this._container.appendChild(f),this._container.appendChild(g),i.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(_,i,v,n){_===this._font&&i===this._fontSize&&v===this._weight&&n===this._weightBold||(this._font=_,this._fontSize=i,this._weight=v,this._weightBold=n,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${v}`,this._measureElements[1].style.fontWeight=`${n}`,this._measureElements[2].style.fontWeight=`${v}`,this._measureElements[3].style.fontWeight=`${n}`,this.clear())}get(_,i,v){let n=0;if(!i&&!v&&_.length===1&&(n=_.charCodeAt(0))<256){if(this._flat[n]!==-9999)return this._flat[n];const p=this._measure(_,0);return p>0&&(this._flat[n]=p),p}let f=_;i&&(f+="B"),v&&(f+="I");let g=this._holey.get(f);if(g===void 0){let p=0;i&&(p|=1),v&&(p|=2),g=this._measure(_,p),g>0&&this._holey.set(f,g)}return g}_measure(_,i){const v=this._measureElements[i];return v.textContent=_.repeat(32),v.offsetWidth/32}}},9176:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.INVERTED_DEFAULT_COLOR=void 0,t.INVERTED_DEFAULT_COLOR=257},6181:(K,t)=>{function _(v){return 57508<=v&&v<=57558}function i(v){return v>=128512&&v<=128591||v>=127744&&v<=128511||v>=128640&&v<=128767||v>=9728&&v<=9983||v>=9984&&v<=10175||v>=65024&&v<=65039||v>=129280&&v<=129535||v>=127462&&v<=127487}Object.defineProperty(t,"__esModule",{value:!0}),t.throwIfFalsy=function(v){if(!v)throw new Error("value must not be falsy");return v},t.isPowerlineGlyph=_,t.isRestrictedPowerlineGlyph=function(v){return 57520<=v&&v<=57527},t.isEmoji=i,t.allowRescaling=function(v,n,f,g){return n===1&&f>Math.ceil(1.5*g)&&v!==void 0&&v>255&&!i(v)&&!_(v)&&!(function(p){return 57344<=p&&p<=63743})(v)},t.treatGlyphAsBackgroundColor=function(v){return _(v)||(function(n){return 9472<=n&&n<=9631})(v)},t.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},t.computeNextVariantOffset=function(v,n,f=0){return(v-(2*Math.round(n)-f))%(2*Math.round(n))}},2274:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createSelectionRenderModel=function(){return new _};class _{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(v,n,f,g=!1){if(this.selectionStart=n,this.selectionEnd=f,!n||!f||n[0]===f[0]&&n[1]===f[1])return void this.clear();const p=v.buffers.active.ydisp,u=n[1]-p,r=f[1]-p,h=Math.max(u,0),s=Math.min(r,v.rows-1);h>=v.rows||s<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=g,this.viewportStartRow=u,this.viewportEndRow=r,this.viewportCappedStartRow=h,this.viewportCappedEndRow=s,this.startCol=n[0],this.endCol=f[0])}isCellSelected(v,n,f){return!!this.hasSelection&&(f-=v.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?n>=this.startCol&&f>=this.viewportCappedStartRow&&n<this.endCol&&f<=this.viewportCappedEndRow:n<this.startCol&&f>=this.viewportCappedStartRow&&n>=this.endCol&&f<=this.viewportCappedEndRow:f>this.viewportStartRow&&f<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&f===this.viewportStartRow&&n>=this.startCol&&n<this.endCol||this.viewportStartRow<this.viewportEndRow&&f===this.viewportEndRow&&n<this.endCol||this.viewportStartRow<this.viewportEndRow&&f===this.viewportStartRow&&n>=this.startCol)}}},5959:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionModel=void 0,t.SelectionModel=class{constructor(_){this._bufferService=_,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const _=this.selectionStart[0]+this.selectionStartLength;return _>this._bufferService.cols?_%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(_/this._bufferService.cols)-1]:[_%this._bufferService.cols,this.selectionStart[1]+Math.floor(_/this._bufferService.cols)]:[_,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const _=this.selectionStart[0]+this.selectionStartLength;return _>this._bufferService.cols?[_%this._bufferService.cols,this.selectionStart[1]+Math.floor(_/this._bufferService.cols)]:[Math.max(_,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const _=this.selectionStart,i=this.selectionEnd;return!(!_||!i)&&(_[1]>i[1]||_[1]===i[1]&&_[0]>i[0])}handleTrim(_){return this.selectionStart&&(this.selectionStart[1]-=_),this.selectionEnd&&(this.selectionEnd[1]-=_),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},4792:function(K,t,_){var i=this&&this.__decorate||function(s,e,l,o){var d,c=arguments.length,a=c<3?e:o===null?o=Object.getOwnPropertyDescriptor(e,l):o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(s,e,l,o);else for(var m=s.length-1;m>=0;m--)(d=s[m])&&(a=(c<3?d(a):c>3?d(e,l,a):d(e,l))||a);return c>3&&a&&Object.defineProperty(e,l,a),a},v=this&&this.__param||function(s,e){return function(l,o){e(l,o,s)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharSizeService=void 0;const n=_(6501),f=_(7150),g=_(802);let p=class extends f.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(s,e,l){super(),this._optionsService=l,this.width=0,this.height=0,this._onCharSizeChange=this._register(new g.Emitter),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new h(this._optionsService))}catch{this._measureStrategy=this._register(new r(s,e,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],(()=>this.measure())))}measure(){const s=this._measureStrategy.measure();s.width===this.width&&s.height===this.height||(this.width=s.width,this.height=s.height,this._onCharSizeChange.fire())}};t.CharSizeService=p,t.CharSizeService=p=i([v(2,n.IOptionsService)],p);class u extends f.Disposable{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,l){e!==void 0&&e>0&&l!==void 0&&l>0&&(this._result.width=e,this._result.height=l)}}class r extends u{constructor(e,l,o){super(),this._document=e,this._parentElement=l,this._optionsService=o,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}}class h extends u{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");const l=this._ctx.measureText("W");if(!("width"in l&&"fontBoundingBoxAscent"in l&&"fontBoundingBoxDescent"in l))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;const e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}}},945:function(K,t,_){var i,v=this&&this.__decorate||function(s,e,l,o){var d,c=arguments.length,a=c<3?e:o===null?o=Object.getOwnPropertyDescriptor(e,l):o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(s,e,l,o);else for(var m=s.length-1;m>=0;m--)(d=s[m])&&(a=(c<3?d(a):c>3?d(e,l,a):d(e,l))||a);return c>3&&a&&Object.defineProperty(e,l,a),a},n=this&&this.__param||function(s,e){return function(l,o){e(l,o,s)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharacterJoinerService=t.JoinedCellData=void 0;const f=_(5451),g=_(8938),p=_(3055),u=_(6501);class r extends f.AttributeData{constructor(e,l,o){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=l,this._width=o}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.JoinedCellData=r;let h=i=class{constructor(s){this._bufferService=s,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new p.CellData}register(s){const e={id:this._nextCharacterJoinerId++,handler:s};return this._characterJoiners.push(e),e.id}deregister(s){for(let e=0;e<this._characterJoiners.length;e++)if(this._characterJoiners[e].id===s)return this._characterJoiners.splice(e,1),!0;return!1}getJoinedCharacters(s){if(this._characterJoiners.length===0)return[];const e=this._bufferService.buffer.lines.get(s);if(!e||e.length===0)return[];const l=[],o=e.translateToString(!0);let d=0,c=0,a=0,m=e.getFg(0),b=e.getBg(0);for(let R=0;R<e.getTrimmedLength();R++)if(e.loadCell(R,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==m||this._workCell.bg!==b){if(R-d>1){const T=this._getJoinedRanges(o,a,c,e,d);for(let C=0;C<T.length;C++)l.push(T[C])}d=R,a=c,m=this._workCell.fg,b=this._workCell.bg}c+=this._workCell.getChars().length||g.WHITESPACE_CELL_CHAR.length}if(this._bufferService.cols-d>1){const R=this._getJoinedRanges(o,a,c,e,d);for(let T=0;T<R.length;T++)l.push(R[T])}return l}_getJoinedRanges(s,e,l,o,d){const c=s.substring(e,l);let a=[];try{a=this._characterJoiners[0].handler(c)}catch(m){console.error(m)}for(let m=1;m<this._characterJoiners.length;m++)try{const b=this._characterJoiners[m].handler(c);for(let R=0;R<b.length;R++)i._mergeRanges(a,b[R])}catch(b){console.error(b)}return this._stringRangesToCellRanges(a,o,d),a}_stringRangesToCellRanges(s,e,l){let o=0,d=!1,c=0,a=s[o];if(a){for(let m=l;m<this._bufferService.cols;m++){const b=e.getWidth(m),R=e.getString(m).length||g.WHITESPACE_CELL_CHAR.length;if(b!==0){if(!d&&a[0]<=c&&(a[0]=m,d=!0),a[1]<=c){if(a[1]=m,a=s[++o],!a)break;a[0]<=c?(a[0]=m,d=!0):d=!1}c+=R}}a&&(a[1]=this._bufferService.cols)}}static _mergeRanges(s,e){let l=!1;for(let o=0;o<s.length;o++){const d=s[o];if(l){if(e[1]<=d[0])return s[o-1][1]=e[1],s;if(e[1]<=d[1])return s[o-1][1]=Math.max(e[1],d[1]),s.splice(o,1),s;s.splice(o,1),o--}else{if(e[1]<=d[0])return s.splice(o,0,e),s;if(e[1]<=d[1])return d[0]=Math.min(e[0],d[0]),s;e[0]<d[1]&&(d[0]=Math.min(e[0],d[0]),l=!0)}}return l?s[s.length-1][1]=e[1]:s.push(e),s}};t.CharacterJoinerService=h,t.CharacterJoinerService=h=i=v([n(0,u.IBufferService)],h)},9574:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreBrowserService=void 0;const i=_(802),v=_(7093),n=_(7150);class f extends n.Disposable{constructor(u,r,h){super(),this._textarea=u,this._window=r,this.mainDocument=h,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new g(this._window)),this._onDprChange=this._register(new i.Emitter),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new i.Emitter),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange((s=>this._screenDprMonitor.setWindow(s)))),this._register(i.Event.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register((0,v.addDisposableListener)(this._textarea,"focus",(()=>this._isFocused=!0))),this._register((0,v.addDisposableListener)(this._textarea,"blur",(()=>this._isFocused=!1)))}get window(){return this._window}set window(u){this._window!==u&&(this._window=u,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask((()=>this._cachedIsFocused=void 0))),this._cachedIsFocused}}t.CoreBrowserService=f;class g extends n.Disposable{constructor(u){super(),this._parentWindow=u,this._windowResizeListener=this._register(new n.MutableDisposable),this._onDprChange=this._register(new i.Emitter),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register((0,n.toDisposable)((()=>this.clearListener())))}setWindow(u){this._parentWindow=u,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=(0,v.addDisposableListener)(this._parentWindow,"resize",(()=>this._setDprAndFireIfDiffers()))}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){var u;this._outerListener&&((u=this._resolutionMediaMatchList)==null||u.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}}},9820:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LinkProviderService=void 0;const i=_(7150);class v extends i.Disposable{constructor(){super(),this.linkProviders=[],this._register((0,i.toDisposable)((()=>this.linkProviders.length=0)))}registerLinkProvider(f){return this.linkProviders.push(f),{dispose:()=>{const g=this.linkProviders.indexOf(f);g!==-1&&this.linkProviders.splice(g,1)}}}}t.LinkProviderService=v},9784:function(K,t,_){var i=this&&this.__decorate||function(p,u,r,h){var s,e=arguments.length,l=e<3?u:h===null?h=Object.getOwnPropertyDescriptor(u,r):h;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")l=Reflect.decorate(p,u,r,h);else for(var o=p.length-1;o>=0;o--)(s=p[o])&&(l=(e<3?s(l):e>3?s(u,r,l):s(u,r))||l);return e>3&&l&&Object.defineProperty(u,r,l),l},v=this&&this.__param||function(p,u){return function(r,h){u(r,h,p)}};Object.defineProperty(t,"__esModule",{value:!0}),t.MouseService=void 0;const n=_(7098),f=_(5251);let g=class{constructor(p,u){this._renderService=p,this._charSizeService=u}getCoords(p,u,r,h,s){return(0,f.getCoords)(window,p,u,r,h,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,s)}getMouseReportCoords(p,u){const r=(0,f.getCoordsRelativeToElement)(window,p,u);if(this._charSizeService.hasValidSize)return r[0]=Math.min(Math.max(r[0],0),this._renderService.dimensions.css.canvas.width-1),r[1]=Math.min(Math.max(r[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(r[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(r[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(r[0]),y:Math.floor(r[1])}}};t.MouseService=g,t.MouseService=g=i([v(0,n.IRenderService),v(1,n.ICharSizeService)],g)},5783:function(K,t,_){var i=this&&this.__decorate||function(e,l,o,d){var c,a=arguments.length,m=a<3?l:d===null?d=Object.getOwnPropertyDescriptor(l,o):d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")m=Reflect.decorate(e,l,o,d);else for(var b=e.length-1;b>=0;b--)(c=e[b])&&(m=(a<3?c(m):a>3?c(l,o,m):c(l,o))||m);return a>3&&m&&Object.defineProperty(l,o,m),m},v=this&&this.__param||function(e,l){return function(o,d){l(o,d,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.RenderService=void 0;const n=_(4852),f=_(7098),g=_(7150),p=_(6168),u=_(6501),r=_(802);let h=class extends g.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(e,l,o,d,c,a,m,b,R){super(),this._rowCount=e,this._optionsService=o,this._charSizeService=d,this._coreService=c,this._coreBrowserService=b,this._renderer=this._register(new g.MutableDisposable),this._pausedResizeTask=new p.DebouncedIdleTask,this._observerDisposable=this._register(new g.MutableDisposable),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new r.Emitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new r.Emitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new r.Emitter),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new r.Emitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new n.RenderDebouncer(((T,C)=>this._renderRows(T,C)),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new s(this._coreBrowserService,this._coreService,(()=>this._fullRefresh())),this._register((0,g.toDisposable)((()=>this._syncOutputHandler.dispose()))),this._register(this._coreBrowserService.onDprChange((()=>this.handleDevicePixelRatioChange()))),this._register(m.onResize((()=>this._fullRefresh()))),this._register(m.buffers.onBufferActivate((()=>{var T;return(T=this._renderer.value)==null?void 0:T.clear()}))),this._register(this._optionsService.onOptionChange((()=>this._handleOptionsChanged()))),this._register(this._charSizeService.onCharSizeChange((()=>this.handleCharSizeChanged()))),this._register(a.onDecorationRegistered((()=>this._fullRefresh()))),this._register(a.onDecorationRemoved((()=>this._fullRefresh()))),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],(()=>{this.clear(),this.handleResize(m.cols,m.rows),this._fullRefresh()}))),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],(()=>this.refreshRows(m.buffer.y,m.buffer.y,!0)))),this._register(R.onChangeColors((()=>this._fullRefresh()))),this._registerIntersectionObserver(this._coreBrowserService.window,l),this._register(this._coreBrowserService.onWindowChange((T=>this._registerIntersectionObserver(T,l))))}_registerIntersectionObserver(e,l){if("IntersectionObserver"in e){const o=new e.IntersectionObserver((d=>this._handleIntersectionChange(d[d.length-1])),{threshold:0});o.observe(l),this._observerDisposable.value=(0,g.toDisposable)((()=>o.disconnect()))}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,this._isPaused||this._charSizeService.hasValidSize||this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,l,o=!1){if(this._isPaused)return void(this._needsFullRefresh=!0);if(this._coreService.decPrivateModes.synchronizedOutput)return void this._syncOutputHandler.bufferRows(e,l);const d=this._syncOutputHandler.flush();d&&(e=Math.min(e,d.start),l=Math.max(l,d.end)),o||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,l,this._rowCount)}_renderRows(e,l){this._renderer.value&&(this._coreService.decPrivateModes.synchronizedOutput?this._syncOutputHandler.bufferRows(e,l):(e=Math.min(e,this._rowCount-1),l=Math.min(l,this._rowCount-1),this._renderer.value.renderRows(e,l),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:l}),this._onRender.fire({start:e,end:l}),this._isNextRenderRedrawOnly=!0))}resize(e,l){this._rowCount=l,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw((l=>this.refreshRows(l.start,l.end,!0))),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,l;this._renderer.value&&((l=(e=this._renderer.value).clearTextureAtlas)==null||l.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,l){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set((()=>{var o;return(o=this._renderer.value)==null?void 0:o.handleResize(e,l)})):this._renderer.value.handleResize(e,l),this._fullRefresh())}handleCharSizeChanged(){var e;(e=this._renderer.value)==null||e.handleCharSizeChanged()}handleBlur(){var e;(e=this._renderer.value)==null||e.handleBlur()}handleFocus(){var e;(e=this._renderer.value)==null||e.handleFocus()}handleSelectionChanged(e,l,o){var d;this._selectionState.start=e,this._selectionState.end=l,this._selectionState.columnSelectMode=o,(d=this._renderer.value)==null||d.handleSelectionChanged(e,l,o)}handleCursorMove(){var e;(e=this._renderer.value)==null||e.handleCursorMove()}clear(){var e;(e=this._renderer.value)==null||e.clear()}};t.RenderService=h,t.RenderService=h=i([v(2,u.IOptionsService),v(3,f.ICharSizeService),v(4,u.ICoreService),v(5,u.IDecorationService),v(6,u.IBufferService),v(7,f.ICoreBrowserService),v(8,f.IThemeService)],h);class s{constructor(l,o,d){this._coreBrowserService=l,this._coreService=o,this._onTimeout=d,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(l,o){this._isBuffering?(this._start=Math.min(this._start,l),this._end=Math.max(this._end,o)):(this._start=l,this._end=o,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout((()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()}),1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;const l={start:this._start,end:this._end};return this._isBuffering=!1,l}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}}},2079:function(K,t,_){var i=this&&this.__decorate||function(a,m,b,R){var T,C=arguments.length,E=C<3?m:R===null?R=Object.getOwnPropertyDescriptor(m,b):R;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(a,m,b,R);else for(var A=a.length-1;A>=0;A--)(T=a[A])&&(E=(C<3?T(E):C>3?T(m,b,E):T(m,b))||E);return C>3&&E&&Object.defineProperty(m,b,E),E},v=this&&this.__param||function(a,m){return function(b,R){m(b,R,a)}};Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionService=void 0;const n=_(5251),f=_(9686),g=_(5959),p=_(7098),u=_(7150),r=_(701),h=_(9384),s=_(3055),e=_(6501),l=_(802),o="\xA0",d=new RegExp(o,"g");let c=class extends u.Disposable{constructor(a,m,b,R,T,C,E,A,N){super(),this._element=a,this._screenElement=m,this._linkifier=b,this._bufferService=R,this._coreService=T,this._mouseService=C,this._optionsService=E,this._renderService=A,this._coreBrowserService=N,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new s.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new l.Emitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new l.Emitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new l.Emitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new l.Emitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=P=>this._handleMouseMove(P),this._mouseUpListener=P=>this._handleMouseUp(P),this._coreService.onUserInput((()=>{this.hasSelection&&this.clearSelection()})),this._trimListener=this._bufferService.buffer.lines.onTrim((P=>this._handleTrim(P))),this._register(this._bufferService.buffers.onBufferActivate((P=>this._handleBufferActivate(P)))),this.enable(),this._model=new g.SelectionModel(this._bufferService),this._activeSelectionMode=0,this._register((0,u.toDisposable)((()=>{this._removeMouseDownListeners()}))),this._register(this._bufferService.onResize((P=>{P.rowsChanged&&this.clearSelection()})))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){const a=this._model.finalSelectionStart,m=this._model.finalSelectionEnd;return!(!a||!m||a[0]===m[0]&&a[1]===m[1])}get selectionText(){const a=this._model.finalSelectionStart,m=this._model.finalSelectionEnd;if(!a||!m)return"";const b=this._bufferService.buffer,R=[];if(this._activeSelectionMode===3){if(a[0]===m[0])return"";const T=a[0]<m[0]?a[0]:m[0],C=a[0]<m[0]?m[0]:a[0];for(let E=a[1];E<=m[1];E++){const A=b.translateBufferLineToString(E,!0,T,C);R.push(A)}}else{const T=a[1]===m[1]?m[0]:void 0;R.push(b.translateBufferLineToString(a[1],!0,a[0],T));for(let C=a[1]+1;C<=m[1]-1;C++){const E=b.lines.get(C),A=b.translateBufferLineToString(C,!0);E!=null&&E.isWrapped?R[R.length-1]+=A:R.push(A)}if(a[1]!==m[1]){const C=b.lines.get(m[1]),E=b.translateBufferLineToString(m[1],!0,0,m[0]);C&&C.isWrapped?R[R.length-1]+=E:R.push(E)}}return R.map((T=>T.replace(d," "))).join(r.isWindows?`\r
+`:`
+`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(a){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh()))),r.isLinux&&a&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(a){const m=this._getMouseBufferCoords(a),b=this._model.finalSelectionStart,R=this._model.finalSelectionEnd;return!!(b&&R&&m)&&this._areCoordsInSelection(m,b,R)}isCellInSelection(a,m){const b=this._model.finalSelectionStart,R=this._model.finalSelectionEnd;return!(!b||!R)&&this._areCoordsInSelection([a,m],b,R)}_areCoordsInSelection(a,m,b){return a[1]>m[1]&&a[1]<b[1]||m[1]===b[1]&&a[1]===m[1]&&a[0]>=m[0]&&a[0]<b[0]||m[1]<b[1]&&a[1]===b[1]&&a[0]<b[0]||m[1]<b[1]&&a[1]===m[1]&&a[0]>=m[0]}_selectWordAtCursor(a,m){var T,C;const b=(C=(T=this._linkifier.currentLink)==null?void 0:T.link)==null?void 0:C.range;if(b)return this._model.selectionStart=[b.start.x-1,b.start.y-1],this._model.selectionStartLength=(0,h.getRangeLength)(b,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const R=this._getMouseBufferCoords(a);return!!R&&(this._selectWordAt(R,m),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(a,m){this._model.clearSelection(),a=Math.max(a,0),m=Math.min(m,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,a],this._model.selectionEnd=[this._bufferService.cols,m],this.refresh(),this._onSelectionChange.fire()}_handleTrim(a){this._model.handleTrim(a)&&this.refresh()}_getMouseBufferCoords(a){const m=this._mouseService.getCoords(a,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(m)return m[0]--,m[1]--,m[1]+=this._bufferService.buffer.ydisp,m}_getMouseEventScrollAmount(a){let m=(0,n.getCoordsRelativeToElement)(this._coreBrowserService.window,a,this._screenElement)[1];const b=this._renderService.dimensions.css.canvas.height;return m>=0&&m<=b?0:(m>b&&(m-=b),m=Math.min(Math.max(m,-50),50),m/=50,m/Math.abs(m)+Math.round(14*m))}shouldForceSelection(a){return r.isMac?a.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:a.shiftKey}handleMouseDown(a){if(this._mouseDownTimeStamp=a.timeStamp,(a.button!==2||!this.hasSelection)&&a.button===0){if(!this._enabled){if(!this.shouldForceSelection(a))return;a.stopPropagation()}a.preventDefault(),this._dragScrollAmount=0,this._enabled&&a.shiftKey?this._handleIncrementalClick(a):a.detail===1?this._handleSingleClick(a):a.detail===2?this._handleDoubleClick(a):a.detail===3&&this._handleTripleClick(a),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval((()=>this._dragScroll()),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(a){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(a))}_handleSingleClick(a){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(a)?3:0,this._model.selectionStart=this._getMouseBufferCoords(a),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const m=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);m&&m.length!==this._model.selectionStart[0]&&m.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(a){this._selectWordAtCursor(a,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(a){const m=this._getMouseBufferCoords(a);m&&(this._activeSelectionMode=2,this._selectLineAt(m[1]))}shouldColumnSelect(a){return a.altKey&&!(r.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(a){if(a.stopImmediatePropagation(),!this._model.selectionStart)return;const m=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(a),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(a),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const b=this._bufferService.buffer;if(this._model.selectionEnd[1]<b.lines.length){const R=b.lines.get(this._model.selectionEnd[1]);R&&R.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}m&&m[0]===this._model.selectionEnd[0]&&m[1]===this._model.selectionEnd[1]||this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});const a=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(a.ydisp+this._bufferService.rows,a.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=a.ydisp),this.refresh()}}_handleMouseUp(a){const m=a.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&m<500&&a.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const b=this._mouseService.getCoords(a,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(b&&b[0]!==void 0&&b[1]!==void 0){const R=(0,f.moveToCellSequence)(b[0]-1,b[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(R,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const a=this._model.finalSelectionStart,m=this._model.finalSelectionEnd,b=!(!a||!m||a[0]===m[0]&&a[1]===m[1]);b?a&&m&&(this._oldSelectionStart&&this._oldSelectionEnd&&a[0]===this._oldSelectionStart[0]&&a[1]===this._oldSelectionStart[1]&&m[0]===this._oldSelectionEnd[0]&&m[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(a,m,b)):this._oldHasSelection&&this._fireOnSelectionChange(a,m,b)}_fireOnSelectionChange(a,m,b){this._oldSelectionStart=a,this._oldSelectionEnd=m,this._oldHasSelection=b,this._onSelectionChange.fire()}_handleBufferActivate(a){this.clearSelection(),this._trimListener.dispose(),this._trimListener=a.activeBuffer.lines.onTrim((m=>this._handleTrim(m)))}_convertViewportColToCharacterIndex(a,m){let b=m;for(let R=0;m>=R;R++){const T=a.loadCell(R,this._workCell).getChars().length;this._workCell.getWidth()===0?b--:T>1&&m!==R&&(b+=T-1)}return b}setSelection(a,m,b){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[a,m],this._model.selectionStartLength=b,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(a){this._isClickInSelection(a)||(this._selectWordAtCursor(a,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(a,m,b=!0,R=!0){if(a[0]>=this._bufferService.cols)return;const T=this._bufferService.buffer,C=T.lines.get(a[1]);if(!C)return;const E=T.translateBufferLineToString(a[1],!1);let A=this._convertViewportColToCharacterIndex(C,a[0]),N=A;const P=a[0]-A;let W=0,w=0,y=0,S=0;if(E.charAt(A)===" "){for(;A>0&&E.charAt(A-1)===" ";)A--;for(;N<E.length&&E.charAt(N+1)===" ";)N++}else{let I=a[0],F=a[0];C.getWidth(I)===0&&(W++,I--),C.getWidth(F)===2&&(w++,F++);const H=C.getString(F).length;for(H>1&&(S+=H-1,N+=H-1);I>0&&A>0&&!this._isCharWordSeparator(C.loadCell(I-1,this._workCell));){C.loadCell(I-1,this._workCell);const B=this._workCell.getChars().length;this._workCell.getWidth()===0?(W++,I--):B>1&&(y+=B-1,A-=B-1),A--,I--}for(;F<C.length&&N+1<E.length&&!this._isCharWordSeparator(C.loadCell(F+1,this._workCell));){C.loadCell(F+1,this._workCell);const B=this._workCell.getChars().length;this._workCell.getWidth()===2?(w++,F++):B>1&&(S+=B-1,N+=B-1),N++,F++}}N++;let D=A+P-W+y,M=Math.min(this._bufferService.cols,N-A+W+w-y-S);if(m||E.slice(A,N).trim()!==""){if(b&&D===0&&C.getCodePoint(0)!==32){const I=T.lines.get(a[1]-1);if(I&&C.isWrapped&&I.getCodePoint(this._bufferService.cols-1)!==32){const F=this._getWordAt([this._bufferService.cols-1,a[1]-1],!1,!0,!1);if(F){const H=this._bufferService.cols-F.start;D-=H,M+=H}}}if(R&&D+M===this._bufferService.cols&&C.getCodePoint(this._bufferService.cols-1)!==32){const I=T.lines.get(a[1]+1);if(I!=null&&I.isWrapped&&I.getCodePoint(0)!==32){const F=this._getWordAt([0,a[1]+1],!1,!1,!0);F&&(M+=F.length)}}return{start:D,length:M}}}_selectWordAt(a,m){const b=this._getWordAt(a,m);if(b){for(;b.start<0;)b.start+=this._bufferService.cols,a[1]--;this._model.selectionStart=[b.start,a[1]],this._model.selectionStartLength=b.length}}_selectToWordAt(a){const m=this._getWordAt(a,!0);if(m){let b=a[1];for(;m.start<0;)m.start+=this._bufferService.cols,b--;if(!this._model.areSelectionValuesReversed())for(;m.start+m.length>this._bufferService.cols;)m.length-=this._bufferService.cols,b++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?m.start:m.start+m.length,b]}}_isCharWordSeparator(a){return a.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(a.getChars())>=0}_selectLineAt(a){const m=this._bufferService.buffer.getWrappedRangeForLine(a),b={start:{x:0,y:m.first},end:{x:this._bufferService.cols-1,y:m.last}};this._model.selectionStart=[0,m.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,h.getRangeLength)(b,this._bufferService.cols)}};t.SelectionService=c,t.SelectionService=c=i([v(3,e.IBufferService),v(4,e.ICoreService),v(5,p.IMouseService),v(6,e.IOptionsService),v(7,p.IRenderService),v(8,p.ICoreBrowserService)],c)},7098:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ILinkProviderService=t.IThemeService=t.ICharacterJoinerService=t.ISelectionService=t.IRenderService=t.IMouseService=t.ICoreBrowserService=t.ICharSizeService=void 0;const i=_(6201);t.ICharSizeService=(0,i.createDecorator)("CharSizeService"),t.ICoreBrowserService=(0,i.createDecorator)("CoreBrowserService"),t.IMouseService=(0,i.createDecorator)("MouseService"),t.IRenderService=(0,i.createDecorator)("RenderService"),t.ISelectionService=(0,i.createDecorator)("SelectionService"),t.ICharacterJoinerService=(0,i.createDecorator)("CharacterJoinerService"),t.IThemeService=(0,i.createDecorator)("ThemeService"),t.ILinkProviderService=(0,i.createDecorator)("LinkProviderService")},9078:function(K,t,_){var i=this&&this.__decorate||function(m,b,R,T){var C,E=arguments.length,A=E<3?b:T===null?T=Object.getOwnPropertyDescriptor(b,R):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(m,b,R,T);else for(var N=m.length-1;N>=0;N--)(C=m[N])&&(A=(E<3?C(A):E>3?C(b,R,A):C(b,R))||A);return E>3&&A&&Object.defineProperty(b,R,A),A},v=this&&this.__param||function(m,b){return function(R,T){b(R,T,m)}};Object.defineProperty(t,"__esModule",{value:!0}),t.ThemeService=void 0;const n=_(7174),f=_(9302),g=_(4103),p=_(7150),u=_(6501),r=_(802),h=g.css.toColor("#ffffff"),s=g.css.toColor("#000000"),e=g.css.toColor("#ffffff"),l=s,o={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},d=h;let c=class extends p.Disposable{get colors(){return this._colors}constructor(m){super(),this._optionsService=m,this._contrastCache=new n.ColorContrastCache,this._halfContrastCache=new n.ColorContrastCache,this._onChangeColors=this._register(new r.Emitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:h,background:s,cursor:e,cursorAccent:l,selectionForeground:void 0,selectionBackgroundTransparent:o,selectionBackgroundOpaque:g.color.blend(s,o),selectionInactiveBackgroundTransparent:o,selectionInactiveBackgroundOpaque:g.color.blend(s,o),scrollbarSliderBackground:g.color.opacity(h,.2),scrollbarSliderHoverBackground:g.color.opacity(h,.4),scrollbarSliderActiveBackground:g.color.opacity(h,.5),overviewRulerBorder:h,ansi:f.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",(()=>this._contrastCache.clear()))),this._register(this._optionsService.onSpecificOptionChange("theme",(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(m={}){const b=this._colors;if(b.foreground=a(m.foreground,h),b.background=a(m.background,s),b.cursor=g.color.blend(b.background,a(m.cursor,e)),b.cursorAccent=g.color.blend(b.background,a(m.cursorAccent,l)),b.selectionBackgroundTransparent=a(m.selectionBackground,o),b.selectionBackgroundOpaque=g.color.blend(b.background,b.selectionBackgroundTransparent),b.selectionInactiveBackgroundTransparent=a(m.selectionInactiveBackground,b.selectionBackgroundTransparent),b.selectionInactiveBackgroundOpaque=g.color.blend(b.background,b.selectionInactiveBackgroundTransparent),b.selectionForeground=m.selectionForeground?a(m.selectionForeground,g.NULL_COLOR):void 0,b.selectionForeground===g.NULL_COLOR&&(b.selectionForeground=void 0),g.color.isOpaque(b.selectionBackgroundTransparent)&&(b.selectionBackgroundTransparent=g.color.opacity(b.selectionBackgroundTransparent,.3)),g.color.isOpaque(b.selectionInactiveBackgroundTransparent)&&(b.selectionInactiveBackgroundTransparent=g.color.opacity(b.selectionInactiveBackgroundTransparent,.3)),b.scrollbarSliderBackground=a(m.scrollbarSliderBackground,g.color.opacity(b.foreground,.2)),b.scrollbarSliderHoverBackground=a(m.scrollbarSliderHoverBackground,g.color.opacity(b.foreground,.4)),b.scrollbarSliderActiveBackground=a(m.scrollbarSliderActiveBackground,g.color.opacity(b.foreground,.5)),b.overviewRulerBorder=a(m.overviewRulerBorder,d),b.ansi=f.DEFAULT_ANSI_COLORS.slice(),b.ansi[0]=a(m.black,f.DEFAULT_ANSI_COLORS[0]),b.ansi[1]=a(m.red,f.DEFAULT_ANSI_COLORS[1]),b.ansi[2]=a(m.green,f.DEFAULT_ANSI_COLORS[2]),b.ansi[3]=a(m.yellow,f.DEFAULT_ANSI_COLORS[3]),b.ansi[4]=a(m.blue,f.DEFAULT_ANSI_COLORS[4]),b.ansi[5]=a(m.magenta,f.DEFAULT_ANSI_COLORS[5]),b.ansi[6]=a(m.cyan,f.DEFAULT_ANSI_COLORS[6]),b.ansi[7]=a(m.white,f.DEFAULT_ANSI_COLORS[7]),b.ansi[8]=a(m.brightBlack,f.DEFAULT_ANSI_COLORS[8]),b.ansi[9]=a(m.brightRed,f.DEFAULT_ANSI_COLORS[9]),b.ansi[10]=a(m.brightGreen,f.DEFAULT_ANSI_COLORS[10]),b.ansi[11]=a(m.brightYellow,f.DEFAULT_ANSI_COLORS[11]),b.ansi[12]=a(m.brightBlue,f.DEFAULT_ANSI_COLORS[12]),b.ansi[13]=a(m.brightMagenta,f.DEFAULT_ANSI_COLORS[13]),b.ansi[14]=a(m.brightCyan,f.DEFAULT_ANSI_COLORS[14]),b.ansi[15]=a(m.brightWhite,f.DEFAULT_ANSI_COLORS[15]),m.extendedAnsi){const R=Math.min(b.ansi.length-16,m.extendedAnsi.length);for(let T=0;T<R;T++)b.ansi[T+16]=a(m.extendedAnsi[T],f.DEFAULT_ANSI_COLORS[T+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(m){this._restoreColor(m),this._onChangeColors.fire(this.colors)}_restoreColor(m){if(m!==void 0)switch(m){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[m]=this._restoreColors.ansi[m]}else for(let b=0;b<this._restoreColors.ansi.length;++b)this._colors.ansi[b]=this._restoreColors.ansi[b]}modifyColors(m){m(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function a(m,b){if(m!==void 0)try{return g.css.toColor(m)}catch{}return b}t.ThemeService=c,t.ThemeService=c=i([v(0,u.IOptionsService)],c)},5639:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CircularList=void 0;const i=_(7150),v=_(802);class n extends i.Disposable{constructor(g){super(),this._maxLength=g,this.onDeleteEmitter=this._register(new v.Emitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new v.Emitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new v.Emitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(g){if(this._maxLength===g)return;const p=new Array(g);for(let u=0;u<Math.min(g,this.length);u++)p[u]=this._array[this._getCyclicIndex(u)];this._array=p,this._maxLength=g,this._startIndex=0}get length(){return this._length}set length(g){if(g>this._length)for(let p=this._length;p<g;p++)this._array[p]=void 0;this._length=g}get(g){return this._array[this._getCyclicIndex(g)]}set(g,p){this._array[this._getCyclicIndex(g)]=p}push(g){this._array[this._getCyclicIndex(this._length)]=g,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(g,p,...u){if(p){for(let r=g;r<this._length-p;r++)this._array[this._getCyclicIndex(r)]=this._array[this._getCyclicIndex(r+p)];this._length-=p,this.onDeleteEmitter.fire({index:g,amount:p})}for(let r=this._length-1;r>=g;r--)this._array[this._getCyclicIndex(r+u.length)]=this._array[this._getCyclicIndex(r)];for(let r=0;r<u.length;r++)this._array[this._getCyclicIndex(g+r)]=u[r];if(u.length&&this.onInsertEmitter.fire({index:g,amount:u.length}),this._length+u.length>this._maxLength){const r=this._length+u.length-this._maxLength;this._startIndex+=r,this._length=this._maxLength,this.onTrimEmitter.fire(r)}else this._length+=u.length}trimStart(g){g>this._length&&(g=this._length),this._startIndex+=g,this._length-=g,this.onTrimEmitter.fire(g)}shiftElements(g,p,u){if(!(p<=0)){if(g<0||g>=this._length)throw new Error("start argument out of range");if(g+u<0)throw new Error("Cannot shift elements in list beyond index 0");if(u>0){for(let h=p-1;h>=0;h--)this.set(g+h+u,this.get(g+h));const r=g+p+u-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<p;r++)this.set(g+r+u,this.get(g+r))}}_getCyclicIndex(g){return(this._startIndex+g)%this._maxLength}}t.CircularList=n},7453:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.clone=function _(i,v=5){if(typeof i!="object")return i;const n=Array.isArray(i)?[]:{};for(const f in i)n[f]=v<=1?i[f]:i[f]&&_(i[f],v-1);return n}},4103:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rgba=t.rgb=t.css=t.color=t.channels=t.NULL_COLOR=void 0,t.toPaddedHex=h,t.contrastRatio=s;let _=0,i=0,v=0,n=0;var f,g,p,u,r;function h(e){const l=e.toString(16);return l.length<2?"0"+l:l}function s(e,l){return e<l?(l+.05)/(e+.05):(e+.05)/(l+.05)}t.NULL_COLOR={css:"#00000000",rgba:0},(function(e){e.toCss=function(l,o,d,c){return c!==void 0?`#${h(l)}${h(o)}${h(d)}${h(c)}`:`#${h(l)}${h(o)}${h(d)}`},e.toRgba=function(l,o,d,c=255){return(l<<24|o<<16|d<<8|c)>>>0},e.toColor=function(l,o,d,c){return{css:e.toCss(l,o,d,c),rgba:e.toRgba(l,o,d,c)}}})(f||(t.channels=f={})),(function(e){function l(o,d){return n=Math.round(255*d),[_,i,v]=r.toChannels(o.rgba),{css:f.toCss(_,i,v,n),rgba:f.toRgba(_,i,v,n)}}e.blend=function(o,d){if(n=(255&d.rgba)/255,n===1)return{css:d.css,rgba:d.rgba};const c=d.rgba>>24&255,a=d.rgba>>16&255,m=d.rgba>>8&255,b=o.rgba>>24&255,R=o.rgba>>16&255,T=o.rgba>>8&255;return _=b+Math.round((c-b)*n),i=R+Math.round((a-R)*n),v=T+Math.round((m-T)*n),{css:f.toCss(_,i,v),rgba:f.toRgba(_,i,v)}},e.isOpaque=function(o){return!(255&~o.rgba)},e.ensureContrastRatio=function(o,d,c){const a=r.ensureContrastRatio(o.rgba,d.rgba,c);if(a)return f.toColor(a>>24&255,a>>16&255,a>>8&255)},e.opaque=function(o){const d=(255|o.rgba)>>>0;return[_,i,v]=r.toChannels(d),{css:f.toCss(_,i,v),rgba:d}},e.opacity=l,e.multiplyOpacity=function(o,d){return n=255&o.rgba,l(o,n*d/255)},e.toColorRGB=function(o){return[o.rgba>>24&255,o.rgba>>16&255,o.rgba>>8&255]}})(g||(t.color=g={})),(function(e){let l,o;try{const d=document.createElement("canvas");d.width=1,d.height=1;const c=d.getContext("2d",{willReadFrequently:!0});c&&(l=c,l.globalCompositeOperation="copy",o=l.createLinearGradient(0,0,1,1))}catch{}e.toColor=function(d){if(d.match(/#[\da-f]{3,8}/i))switch(d.length){case 4:return _=parseInt(d.slice(1,2).repeat(2),16),i=parseInt(d.slice(2,3).repeat(2),16),v=parseInt(d.slice(3,4).repeat(2),16),f.toColor(_,i,v);case 5:return _=parseInt(d.slice(1,2).repeat(2),16),i=parseInt(d.slice(2,3).repeat(2),16),v=parseInt(d.slice(3,4).repeat(2),16),n=parseInt(d.slice(4,5).repeat(2),16),f.toColor(_,i,v,n);case 7:return{css:d,rgba:(parseInt(d.slice(1),16)<<8|255)>>>0};case 9:return{css:d,rgba:parseInt(d.slice(1),16)>>>0}}const c=d.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(c)return _=parseInt(c[1]),i=parseInt(c[2]),v=parseInt(c[3]),n=Math.round(255*(c[5]===void 0?1:parseFloat(c[5]))),f.toColor(_,i,v,n);if(!l||!o)throw new Error("css.toColor: Unsupported css format");if(l.fillStyle=o,l.fillStyle=d,typeof l.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(l.fillRect(0,0,1,1),[_,i,v,n]=l.getImageData(0,0,1,1).data,n!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:f.toRgba(_,i,v,n),css:d}}})(p||(t.css=p={})),(function(e){function l(o,d,c){const a=o/255,m=d/255,b=c/255;return .2126*(a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4))+.7152*(m<=.03928?m/12.92:Math.pow((m+.055)/1.055,2.4))+.0722*(b<=.03928?b/12.92:Math.pow((b+.055)/1.055,2.4))}e.relativeLuminance=function(o){return l(o>>16&255,o>>8&255,255&o)},e.relativeLuminance2=l})(u||(t.rgb=u={})),(function(e){function l(d,c,a){const m=d>>24&255,b=d>>16&255,R=d>>8&255;let T=c>>24&255,C=c>>16&255,E=c>>8&255,A=s(u.relativeLuminance2(T,C,E),u.relativeLuminance2(m,b,R));for(;A<a&&(T>0||C>0||E>0);)T-=Math.max(0,Math.ceil(.1*T)),C-=Math.max(0,Math.ceil(.1*C)),E-=Math.max(0,Math.ceil(.1*E)),A=s(u.relativeLuminance2(T,C,E),u.relativeLuminance2(m,b,R));return(T<<24|C<<16|E<<8|255)>>>0}function o(d,c,a){const m=d>>24&255,b=d>>16&255,R=d>>8&255;let T=c>>24&255,C=c>>16&255,E=c>>8&255,A=s(u.relativeLuminance2(T,C,E),u.relativeLuminance2(m,b,R));for(;A<a&&(T<255||C<255||E<255);)T=Math.min(255,T+Math.ceil(.1*(255-T))),C=Math.min(255,C+Math.ceil(.1*(255-C))),E=Math.min(255,E+Math.ceil(.1*(255-E))),A=s(u.relativeLuminance2(T,C,E),u.relativeLuminance2(m,b,R));return(T<<24|C<<16|E<<8|255)>>>0}e.blend=function(d,c){if(n=(255&c)/255,n===1)return c;const a=c>>24&255,m=c>>16&255,b=c>>8&255,R=d>>24&255,T=d>>16&255,C=d>>8&255;return _=R+Math.round((a-R)*n),i=T+Math.round((m-T)*n),v=C+Math.round((b-C)*n),f.toRgba(_,i,v)},e.ensureContrastRatio=function(d,c,a){const m=u.relativeLuminance(d>>8),b=u.relativeLuminance(c>>8);if(s(m,b)<a){if(b<m){const C=l(d,c,a),E=s(m,u.relativeLuminance(C>>8));if(E<a){const A=o(d,c,a);return E>s(m,u.relativeLuminance(A>>8))?C:A}return C}const R=o(d,c,a),T=s(m,u.relativeLuminance(R>>8));if(T<a){const C=l(d,c,a);return T>s(m,u.relativeLuminance(C>>8))?R:C}return R}},e.reduceLuminance=l,e.increaseLuminance=o,e.toChannels=function(d){return[d>>24&255,d>>16&255,d>>8&255,255&d]}})(r||(t.rgba=r={}))},5777:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreTerminal=void 0;const i=_(6501),v=_(6025),n=_(7276),f=_(9640),g=_(56),p=_(4071),u=_(7792),r=_(6415),h=_(5746),s=_(5882),e=_(2486),l=_(3562),o=_(8811),d=_(802),c=_(7150);let a=!1;class m extends c.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new d.Emitter),this._onScroll.event((R=>{var T;(T=this._onScrollApi)==null||T.fire(R.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(R){for(const T in R)this.optionsService.options[T]=R[T]}constructor(R){super(),this._windowsWrappingHeuristics=this._register(new c.MutableDisposable),this._onBinary=this._register(new d.Emitter),this.onBinary=this._onBinary.event,this._onData=this._register(new d.Emitter),this.onData=this._onData.event,this._onLineFeed=this._register(new d.Emitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new d.Emitter),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new d.Emitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new d.Emitter),this._instantiationService=new v.InstantiationService,this.optionsService=this._register(new g.OptionsService(R)),this._instantiationService.setService(i.IOptionsService,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(f.BufferService)),this._instantiationService.setService(i.IBufferService,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(n.LogService)),this._instantiationService.setService(i.ILogService,this._logService),this.coreService=this._register(this._instantiationService.createInstance(p.CoreService)),this._instantiationService.setService(i.ICoreService,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(u.CoreMouseService)),this._instantiationService.setService(i.ICoreMouseService,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(r.UnicodeService)),this._instantiationService.setService(i.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(h.CharsetService),this._instantiationService.setService(i.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(o.OscLinkService),this._instantiationService.setService(i.IOscLinkService,this._oscLinkService),this._inputHandler=this._register(new e.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(d.Event.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(d.Event.forward(this._bufferService.onResize,this._onResize)),this._register(d.Event.forward(this.coreService.onData,this._onData)),this._register(d.Event.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom(!0)))),this._register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],(()=>this._handleWindowsPtyOptionChange()))),this._register(this._bufferService.onScroll((()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this._register(new l.WriteBuffer(((T,C)=>this._inputHandler.parse(T,C)))),this._register(d.Event.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(R,T){this._writeBuffer.write(R,T)}writeSync(R,T){this._logService.logLevel<=i.LogLevelEnum.WARN&&!a&&(this._logService.warn("writeSync is unreliable and will be removed soon."),a=!0),this._writeBuffer.writeSync(R,T)}input(R,T=!0){this.coreService.triggerDataEvent(R,T)}resize(R,T){isNaN(R)||isNaN(T)||(R=Math.max(R,f.MINIMUM_COLS),T=Math.max(T,f.MINIMUM_ROWS),this._bufferService.resize(R,T))}scroll(R,T=!1){this._bufferService.scroll(R,T)}scrollLines(R,T){this._bufferService.scrollLines(R,T)}scrollPages(R){this.scrollLines(R*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(R){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(R){const T=R-this._bufferService.buffer.ydisp;T!==0&&this.scrollLines(T)}registerEscHandler(R,T){return this._inputHandler.registerEscHandler(R,T)}registerDcsHandler(R,T){return this._inputHandler.registerDcsHandler(R,T)}registerCsiHandler(R,T){return this._inputHandler.registerCsiHandler(R,T)}registerOscHandler(R,T){return this._inputHandler.registerOscHandler(R,T)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let R=!1;const T=this.optionsService.rawOptions.windowsPty;T&&T.buildNumber!==void 0&&T.buildNumber!==void 0?R=T.backend==="conpty"&&T.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(R=!0),R?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const R=[];R.push(this.onLineFeed(s.updateWindowsModeWrappedState.bind(null,this._bufferService))),R.push(this.registerCsiHandler({final:"H"},(()=>((0,s.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,c.toDisposable)((()=>{for(const T of R)T.dispose()}))}}}t.CoreTerminal=m},2486:function(K,t,_){var i=this&&this.__decorate||function(W,w,y,S){var D,M=arguments.length,I=M<3?w:S===null?S=Object.getOwnPropertyDescriptor(w,y):S;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(W,w,y,S);else for(var F=W.length-1;F>=0;F--)(D=W[F])&&(I=(M<3?D(I):M>3?D(w,y,I):D(w,y))||I);return M>3&&I&&Object.defineProperty(w,y,I),I},v=this&&this.__param||function(W,w){return function(y,S){w(y,S,W)}};Object.defineProperty(t,"__esModule",{value:!0}),t.InputHandler=t.WindowsOptionsReportType=void 0,t.isValidColorIndex=P;const n=_(3534),f=_(6760),g=_(6717),p=_(7150),u=_(726),r=_(6107),h=_(8938),s=_(3055),e=_(5451),l=_(6501),o=_(6415),d=_(1346),c=_(9823),a=_(8693),m=_(802),b={"(":0,")":1,"*":2,"+":3,"-":1,".":2},R=131072;function T(W,w){if(W>24)return w.setWinLines||!1;switch(W){case 1:return!!w.restoreWin;case 2:return!!w.minimizeWin;case 3:return!!w.setWinPosition;case 4:return!!w.setWinSizePixels;case 5:return!!w.raiseWin;case 6:return!!w.lowerWin;case 7:return!!w.refreshWin;case 8:return!!w.setWinSizeChars;case 9:return!!w.maximizeWin;case 10:return!!w.fullscreenWin;case 11:return!!w.getWinState;case 13:return!!w.getWinPosition;case 14:return!!w.getWinSizePixels;case 15:return!!w.getScreenSizePixels;case 16:return!!w.getCellSizePixels;case 18:return!!w.getWinSizeChars;case 19:return!!w.getScreenSizeChars;case 20:return!!w.getIconTitle;case 21:return!!w.getWinTitle;case 22:return!!w.pushTitle;case 23:return!!w.popTitle;case 24:return!!w.setWinLines}return!1}var C;(function(W){W[W.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",W[W.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(C||(t.WindowsOptionsReportType=C={}));let E=0;class A extends p.Disposable{getAttrData(){return this._curAttrData}constructor(w,y,S,D,M,I,F,H,B=new g.EscapeSequenceParser){super(),this._bufferService=w,this._charsetService=y,this._coreService=S,this._logService=D,this._optionsService=M,this._oscLinkService=I,this._coreMouseService=F,this._unicodeService=H,this._parser=B,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new u.StringToUtf32,this._utf8Decoder=new u.Utf8ToUtf32,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=r.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=r.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this._register(new m.Emitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new m.Emitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new m.Emitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new m.Emitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new m.Emitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new m.Emitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new m.Emitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new m.Emitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new m.Emitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new m.Emitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new m.Emitter),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new m.Emitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new m.Emitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new N(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate((k=>this._activeBuffer=k.activeBuffer))),this._parser.setCsiHandlerFallback(((k,j)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(k),params:j.toArray()})})),this._parser.setEscHandlerFallback((k=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(k)})})),this._parser.setExecuteHandlerFallback((k=>{this._logService.debug("Unknown EXECUTE code: ",{code:k})})),this._parser.setOscHandlerFallback(((k,j,$)=>{this._logService.debug("Unknown OSC code: ",{identifier:k,action:j,data:$})})),this._parser.setDcsHandlerFallback(((k,j,$)=>{j==="HOOK"&&($=$.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(k),action:j,payload:$})})),this._parser.setPrintHandler(((k,j,$)=>this.print(k,j,$))),this._parser.registerCsiHandler({final:"@"},(k=>this.insertChars(k))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(k=>this.scrollLeft(k))),this._parser.registerCsiHandler({final:"A"},(k=>this.cursorUp(k))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(k=>this.scrollRight(k))),this._parser.registerCsiHandler({final:"B"},(k=>this.cursorDown(k))),this._parser.registerCsiHandler({final:"C"},(k=>this.cursorForward(k))),this._parser.registerCsiHandler({final:"D"},(k=>this.cursorBackward(k))),this._parser.registerCsiHandler({final:"E"},(k=>this.cursorNextLine(k))),this._parser.registerCsiHandler({final:"F"},(k=>this.cursorPrecedingLine(k))),this._parser.registerCsiHandler({final:"G"},(k=>this.cursorCharAbsolute(k))),this._parser.registerCsiHandler({final:"H"},(k=>this.cursorPosition(k))),this._parser.registerCsiHandler({final:"I"},(k=>this.cursorForwardTab(k))),this._parser.registerCsiHandler({final:"J"},(k=>this.eraseInDisplay(k,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(k=>this.eraseInDisplay(k,!0))),this._parser.registerCsiHandler({final:"K"},(k=>this.eraseInLine(k,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(k=>this.eraseInLine(k,!0))),this._parser.registerCsiHandler({final:"L"},(k=>this.insertLines(k))),this._parser.registerCsiHandler({final:"M"},(k=>this.deleteLines(k))),this._parser.registerCsiHandler({final:"P"},(k=>this.deleteChars(k))),this._parser.registerCsiHandler({final:"S"},(k=>this.scrollUp(k))),this._parser.registerCsiHandler({final:"T"},(k=>this.scrollDown(k))),this._parser.registerCsiHandler({final:"X"},(k=>this.eraseChars(k))),this._parser.registerCsiHandler({final:"Z"},(k=>this.cursorBackwardTab(k))),this._parser.registerCsiHandler({final:"`"},(k=>this.charPosAbsolute(k))),this._parser.registerCsiHandler({final:"a"},(k=>this.hPositionRelative(k))),this._parser.registerCsiHandler({final:"b"},(k=>this.repeatPrecedingCharacter(k))),this._parser.registerCsiHandler({final:"c"},(k=>this.sendDeviceAttributesPrimary(k))),this._parser.registerCsiHandler({prefix:">",final:"c"},(k=>this.sendDeviceAttributesSecondary(k))),this._parser.registerCsiHandler({final:"d"},(k=>this.linePosAbsolute(k))),this._parser.registerCsiHandler({final:"e"},(k=>this.vPositionRelative(k))),this._parser.registerCsiHandler({final:"f"},(k=>this.hVPosition(k))),this._parser.registerCsiHandler({final:"g"},(k=>this.tabClear(k))),this._parser.registerCsiHandler({final:"h"},(k=>this.setMode(k))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(k=>this.setModePrivate(k))),this._parser.registerCsiHandler({final:"l"},(k=>this.resetMode(k))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(k=>this.resetModePrivate(k))),this._parser.registerCsiHandler({final:"m"},(k=>this.charAttributes(k))),this._parser.registerCsiHandler({final:"n"},(k=>this.deviceStatus(k))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(k=>this.deviceStatusPrivate(k))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(k=>this.softReset(k))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(k=>this.setCursorStyle(k))),this._parser.registerCsiHandler({final:"r"},(k=>this.setScrollRegion(k))),this._parser.registerCsiHandler({final:"s"},(k=>this.saveCursor(k))),this._parser.registerCsiHandler({final:"t"},(k=>this.windowOptions(k))),this._parser.registerCsiHandler({final:"u"},(k=>this.restoreCursor(k))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(k=>this.insertColumns(k))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(k=>this.deleteColumns(k))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(k=>this.selectProtected(k))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(k=>this.requestMode(k,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(k=>this.requestMode(k,!1))),this._parser.setExecuteHandler(n.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(n.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(n.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(n.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(n.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(n.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(n.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(n.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(n.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new d.OscHandler((k=>(this.setTitle(k),this.setIconName(k),!0)))),this._parser.registerOscHandler(1,new d.OscHandler((k=>this.setIconName(k)))),this._parser.registerOscHandler(2,new d.OscHandler((k=>this.setTitle(k)))),this._parser.registerOscHandler(4,new d.OscHandler((k=>this.setOrReportIndexedColor(k)))),this._parser.registerOscHandler(8,new d.OscHandler((k=>this.setHyperlink(k)))),this._parser.registerOscHandler(10,new d.OscHandler((k=>this.setOrReportFgColor(k)))),this._parser.registerOscHandler(11,new d.OscHandler((k=>this.setOrReportBgColor(k)))),this._parser.registerOscHandler(12,new d.OscHandler((k=>this.setOrReportCursorColor(k)))),this._parser.registerOscHandler(104,new d.OscHandler((k=>this.restoreIndexedColor(k)))),this._parser.registerOscHandler(110,new d.OscHandler((k=>this.restoreFgColor(k)))),this._parser.registerOscHandler(111,new d.OscHandler((k=>this.restoreBgColor(k)))),this._parser.registerOscHandler(112,new d.OscHandler((k=>this.restoreCursorColor(k)))),this._parser.registerEscHandler({final:"7"},(()=>this.saveCursor())),this._parser.registerEscHandler({final:"8"},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:"D"},(()=>this.index())),this._parser.registerEscHandler({final:"E"},(()=>this.nextLine())),this._parser.registerEscHandler({final:"H"},(()=>this.tabSet())),this._parser.registerEscHandler({final:"M"},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:"="},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:">"},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:"c"},(()=>this.fullReset())),this._parser.registerEscHandler({final:"n"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"o"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"|"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"}"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"~"},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:"%",final:"@"},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:"%",final:"G"},(()=>this.selectDefaultCharset()));for(const k in f.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:k},(()=>this.selectCharset("("+k))),this._parser.registerEscHandler({intermediates:")",final:k},(()=>this.selectCharset(")"+k))),this._parser.registerEscHandler({intermediates:"*",final:k},(()=>this.selectCharset("*"+k))),this._parser.registerEscHandler({intermediates:"+",final:k},(()=>this.selectCharset("+"+k))),this._parser.registerEscHandler({intermediates:"-",final:k},(()=>this.selectCharset("-"+k))),this._parser.registerEscHandler({intermediates:".",final:k},(()=>this.selectCharset("."+k))),this._parser.registerEscHandler({intermediates:"/",final:k},(()=>this.selectCharset("/"+k)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((k=>(this._logService.error("Parsing error: ",k),k))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new c.DcsHandler(((k,j)=>this.requestStatusString(k,j))))}_preserveStack(w,y,S,D){this._parseStack.paused=!0,this._parseStack.cursorStartX=w,this._parseStack.cursorStartY=y,this._parseStack.decodedLength=S,this._parseStack.position=D}_logSlowResolvingAsync(w){this._logService.logLevel<=l.LogLevelEnum.WARN&&Promise.race([w,new Promise(((y,S)=>setTimeout((()=>S("#SLOW_TIMEOUT")),5e3)))]).catch((y=>{if(y!=="#SLOW_TIMEOUT")throw y;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(w,y){let S,D=this._activeBuffer.x,M=this._activeBuffer.y,I=0;const F=this._parseStack.paused;if(F){if(S=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,y))return this._logSlowResolvingAsync(S),S;D=this._parseStack.cursorStartX,M=this._parseStack.cursorStartY,this._parseStack.paused=!1,w.length>R&&(I=this._parseStack.position+R)}if(this._logService.logLevel<=l.LogLevelEnum.DEBUG&&this._logService.debug("parsing data "+(typeof w=="string"?` "${w}"`:` "${Array.prototype.map.call(w,(k=>String.fromCharCode(k))).join("")}"`)),this._logService.logLevel===l.LogLevelEnum.TRACE&&this._logService.trace("parsing data (codes)",typeof w=="string"?w.split("").map((k=>k.charCodeAt(0))):w),this._parseBuffer.length<w.length&&this._parseBuffer.length<R&&(this._parseBuffer=new Uint32Array(Math.min(w.length,R))),F||this._dirtyRowTracker.clearRange(),w.length>R)for(let k=I;k<w.length;k+=R){const j=k+R<w.length?k+R:w.length,$=typeof w=="string"?this._stringDecoder.decode(w.substring(k,j),this._parseBuffer):this._utf8Decoder.decode(w.subarray(k,j),this._parseBuffer);if(S=this._parser.parse(this._parseBuffer,$))return this._preserveStack(D,M,$,k),this._logSlowResolvingAsync(S),S}else if(!F){const k=typeof w=="string"?this._stringDecoder.decode(w,this._parseBuffer):this._utf8Decoder.decode(w,this._parseBuffer);if(S=this._parser.parse(this._parseBuffer,k))return this._preserveStack(D,M,k,0),this._logSlowResolvingAsync(S),S}this._activeBuffer.x===D&&this._activeBuffer.y===M||this._onCursorMove.fire();const H=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),B=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);B<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(B,this._bufferService.rows-1),end:Math.min(H,this._bufferService.rows-1)})}print(w,y,S){let D,M;const I=this._charsetService.charset,F=this._optionsService.rawOptions.screenReaderMode,H=this._bufferService.cols,B=this._coreService.decPrivateModes.wraparound,k=this._coreService.modes.insertMode,j=this._curAttrData;let $=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&S-y>0&&$.getWidth(this._activeBuffer.x-1)===2&&$.setCellFromCodepoint(this._activeBuffer.x-1,0,1,j);let X=this._parser.precedingJoinState;for(let V=y;V<S;++V){if(D=w[V],D<127&&I){const re=I[String.fromCharCode(D)];re&&(D=re.charCodeAt(0))}const Z=this._unicodeService.charProperties(D,X);M=o.UnicodeService.extractWidth(Z);const se=o.UnicodeService.extractShouldJoin(Z),te=se?o.UnicodeService.extractWidth(X):0;if(X=Z,F&&this._onA11yChar.fire((0,u.stringFromCodePoint)(D)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+M-te>H){if(B){const re=$;let ne=this._activeBuffer.x-te;for(this._activeBuffer.x=te,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),$=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),te>0&&$ instanceof r.BufferLine&&$.copyCellsFrom(re,ne,0,te,!1);ne<H;)re.setCellFromCodepoint(ne++,0,1,j)}else if(this._activeBuffer.x=H-1,M===2)continue}if(se&&this._activeBuffer.x){const re=$.getWidth(this._activeBuffer.x-1)?1:2;$.addCodepointToCell(this._activeBuffer.x-re,D,M);for(let ne=M-te;--ne>=0;)$.setCellFromCodepoint(this._activeBuffer.x++,0,0,j)}else if(k&&($.insertCells(this._activeBuffer.x,M-te,this._activeBuffer.getNullCell(j)),$.getWidth(H-1)===2&&$.setCellFromCodepoint(H-1,h.NULL_CELL_CODE,h.NULL_CELL_WIDTH,j)),$.setCellFromCodepoint(this._activeBuffer.x++,D,M,j),M>0)for(;--M;)$.setCellFromCodepoint(this._activeBuffer.x++,0,0,j)}this._parser.precedingJoinState=X,this._activeBuffer.x<H&&S-y>0&&$.getWidth(this._activeBuffer.x)===0&&!$.hasContent(this._activeBuffer.x)&&$.setCellFromCodepoint(this._activeBuffer.x,0,1,j),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(w,y){return w.final!=="t"||w.prefix||w.intermediates?this._parser.registerCsiHandler(w,y):this._parser.registerCsiHandler(w,(S=>!T(S.params[0],this._optionsService.rawOptions.windowOptions)||y(S)))}registerDcsHandler(w,y){return this._parser.registerDcsHandler(w,new c.DcsHandler(y))}registerEscHandler(w,y){return this._parser.registerEscHandler(w,y)}registerOscHandler(w,y){return this._parser.registerOscHandler(w,new d.OscHandler(y))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var w;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((w=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&w.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const y=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);y.hasWidth(this._activeBuffer.x)&&!y.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const w=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-w),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(w=this._bufferService.cols-1){this._activeBuffer.x=Math.min(w,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(w,y){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=w,this._activeBuffer.y=this._activeBuffer.scrollTop+y):(this._activeBuffer.x=w,this._activeBuffer.y=y),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(w,y){this._restrictCursor(),this._setCursor(this._activeBuffer.x+w,this._activeBuffer.y+y)}cursorUp(w){const y=this._activeBuffer.y-this._activeBuffer.scrollTop;return y>=0?this._moveCursor(0,-Math.min(y,w.params[0]||1)):this._moveCursor(0,-(w.params[0]||1)),!0}cursorDown(w){const y=this._activeBuffer.scrollBottom-this._activeBuffer.y;return y>=0?this._moveCursor(0,Math.min(y,w.params[0]||1)):this._moveCursor(0,w.params[0]||1),!0}cursorForward(w){return this._moveCursor(w.params[0]||1,0),!0}cursorBackward(w){return this._moveCursor(-(w.params[0]||1),0),!0}cursorNextLine(w){return this.cursorDown(w),this._activeBuffer.x=0,!0}cursorPrecedingLine(w){return this.cursorUp(w),this._activeBuffer.x=0,!0}cursorCharAbsolute(w){return this._setCursor((w.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(w){return this._setCursor(w.length>=2?(w.params[1]||1)-1:0,(w.params[0]||1)-1),!0}charPosAbsolute(w){return this._setCursor((w.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(w){return this._moveCursor(w.params[0]||1,0),!0}linePosAbsolute(w){return this._setCursor(this._activeBuffer.x,(w.params[0]||1)-1),!0}vPositionRelative(w){return this._moveCursor(0,w.params[0]||1),!0}hVPosition(w){return this.cursorPosition(w),!0}tabClear(w){const y=w.params[0];return y===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:y===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(w){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let y=w.params[0]||1;for(;y--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(w){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let y=w.params[0]||1;for(;y--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(w){const y=w.params[0];return y===1&&(this._curAttrData.bg|=536870912),y!==2&&y!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(w,y,S,D=!1,M=!1){const I=this._activeBuffer.lines.get(this._activeBuffer.ybase+w);I.replaceCells(y,S,this._activeBuffer.getNullCell(this._eraseAttrData()),M),D&&(I.isWrapped=!1)}_resetBufferLine(w,y=!1){const S=this._activeBuffer.lines.get(this._activeBuffer.ybase+w);S&&(S.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),y),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+w),S.isWrapped=!1)}eraseInDisplay(w,y=!1){let S;switch(this._restrictCursor(this._bufferService.cols),w.params[0]){case 0:for(S=this._activeBuffer.y,this._dirtyRowTracker.markDirty(S),this._eraseInBufferLine(S++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,y);S<this._bufferService.rows;S++)this._resetBufferLine(S,y);this._dirtyRowTracker.markDirty(S);break;case 1:for(S=this._activeBuffer.y,this._dirtyRowTracker.markDirty(S),this._eraseInBufferLine(S,0,this._activeBuffer.x+1,!0,y),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(S+1).isWrapped=!1);S--;)this._resetBufferLine(S,y);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(S=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,S-1);S--;){const M=this._activeBuffer.lines.get(this._activeBuffer.ybase+S);if(M!=null&&M.getTrimmedLength())break}for(;S>=0;S--)this._bufferService.scroll(this._eraseAttrData())}else{for(S=this._bufferService.rows,this._dirtyRowTracker.markDirty(S-1);S--;)this._resetBufferLine(S,y);this._dirtyRowTracker.markDirty(0)}break;case 3:const D=this._activeBuffer.lines.length-this._bufferService.rows;D>0&&(this._activeBuffer.lines.trimStart(D),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-D,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-D,0),this._onScroll.fire(0))}return!0}eraseInLine(w,y=!1){switch(this._restrictCursor(this._bufferService.cols),w.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,y);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,y);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,y)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(w){this._restrictCursor();let y=w.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const S=this._activeBuffer.ybase+this._activeBuffer.y,D=this._bufferService.rows-1-this._activeBuffer.scrollBottom,M=this._bufferService.rows-1+this._activeBuffer.ybase-D+1;for(;y--;)this._activeBuffer.lines.splice(M-1,1),this._activeBuffer.lines.splice(S,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(w){this._restrictCursor();let y=w.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const S=this._activeBuffer.ybase+this._activeBuffer.y;let D;for(D=this._bufferService.rows-1-this._activeBuffer.scrollBottom,D=this._bufferService.rows-1+this._activeBuffer.ybase-D;y--;)this._activeBuffer.lines.splice(S,1),this._activeBuffer.lines.splice(D,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(w){this._restrictCursor();const y=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return y&&(y.insertCells(this._activeBuffer.x,w.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(w){this._restrictCursor();const y=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return y&&(y.deleteCells(this._activeBuffer.x,w.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(w){let y=w.params[0]||1;for(;y--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(w){let y=w.params[0]||1;for(;y--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(r.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(w){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const y=w.params[0]||1;for(let S=this._activeBuffer.scrollTop;S<=this._activeBuffer.scrollBottom;++S){const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+S);D.deleteCells(0,y,this._activeBuffer.getNullCell(this._eraseAttrData())),D.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(w){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const y=w.params[0]||1;for(let S=this._activeBuffer.scrollTop;S<=this._activeBuffer.scrollBottom;++S){const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+S);D.insertCells(0,y,this._activeBuffer.getNullCell(this._eraseAttrData())),D.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(w){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const y=w.params[0]||1;for(let S=this._activeBuffer.scrollTop;S<=this._activeBuffer.scrollBottom;++S){const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+S);D.insertCells(this._activeBuffer.x,y,this._activeBuffer.getNullCell(this._eraseAttrData())),D.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(w){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const y=w.params[0]||1;for(let S=this._activeBuffer.scrollTop;S<=this._activeBuffer.scrollBottom;++S){const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+S);D.deleteCells(this._activeBuffer.x,y,this._activeBuffer.getNullCell(this._eraseAttrData())),D.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(w){this._restrictCursor();const y=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return y&&(y.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(w.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(w){const y=this._parser.precedingJoinState;if(!y)return!0;const S=w.params[0]||1,D=o.UnicodeService.extractWidth(y),M=this._activeBuffer.x-D,I=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(M),F=new Uint32Array(I.length*S);let H=0;for(let k=0;k<I.length;){const j=I.codePointAt(k)||0;F[H++]=j,k+=j>65535?2:1}let B=H;for(let k=1;k<S;++k)F.copyWithin(B,0,H),B+=H;return this.print(F,0,B),!0}sendDeviceAttributesPrimary(w){return w.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(n.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(n.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(w){return w.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(n.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(n.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(w.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(n.C0.ESC+"[>83;40003;0c")),!0}_is(w){return(this._optionsService.rawOptions.termName+"").indexOf(w)===0}setMode(w){for(let y=0;y<w.length;y++)switch(w.params[y]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(w){for(let y=0;y<w.length;y++)switch(w.params[y]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,f.DEFAULT_CHARSET),this._charsetService.setgCharset(1,f.DEFAULT_CHARSET),this._charsetService.setgCharset(2,f.DEFAULT_CHARSET),this._charsetService.setgCharset(3,f.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(w){for(let y=0;y<w.length;y++)switch(w.params[y]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(w){for(let y=0;y<w.length;y++)switch(w.params[y]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),w.params[y]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(w,y){const S=this._coreService.decPrivateModes,{activeProtocol:D,activeEncoding:M}=this._coreMouseService,I=this._coreService,{buffers:F,cols:H}=this._bufferService,{active:B,alt:k}=F,j=this._optionsService.rawOptions,$=se=>se?1:2,X=w.params[0];return V=X,Z=y?X===2?4:X===4?$(I.modes.insertMode):X===12?3:X===20?$(j.convertEol):0:X===1?$(S.applicationCursorKeys):X===3?j.windowOptions.setWinLines?H===80?2:H===132?1:0:0:X===6?$(S.origin):X===7?$(S.wraparound):X===8?3:X===9?$(D==="X10"):X===12?$(j.cursorBlink):X===25?$(!I.isCursorHidden):X===45?$(S.reverseWraparound):X===66?$(S.applicationKeypad):X===67?4:X===1e3?$(D==="VT200"):X===1002?$(D==="DRAG"):X===1003?$(D==="ANY"):X===1004?$(S.sendFocus):X===1005?4:X===1006?$(M==="SGR"):X===1015?4:X===1016?$(M==="SGR_PIXELS"):X===1048?1:X===47||X===1047||X===1049?$(B===k):X===2004?$(S.bracketedPasteMode):X===2026?$(S.synchronizedOutput):0,I.triggerDataEvent(`${n.C0.ESC}[${y?"":"?"}${V};${Z}$y`),!0;var V,Z}_updateAttrColor(w,y,S,D,M){return y===2?(w|=50331648,w&=-16777216,w|=e.AttributeData.fromColorRGB([S,D,M])):y===5&&(w&=-50331904,w|=33554432|255&S),w}_extractColor(w,y,S){const D=[0,0,-1,0,0,0];let M=0,I=0;do{if(D[I+M]=w.params[y+I],w.hasSubParams(y+I)){const F=w.getSubParams(y+I);let H=0;do D[1]===5&&(M=1),D[I+H+1+M]=F[H];while(++H<F.length&&H+I+1+M<D.length);break}if(D[1]===5&&I+M>=2||D[1]===2&&I+M>=5)break;D[1]&&(M=1)}while(++I+y<w.length&&I+M<D.length);for(let F=2;F<D.length;++F)D[F]===-1&&(D[F]=0);switch(D[0]){case 38:S.fg=this._updateAttrColor(S.fg,D[1],D[3],D[4],D[5]);break;case 48:S.bg=this._updateAttrColor(S.bg,D[1],D[3],D[4],D[5]);break;case 58:S.extended=S.extended.clone(),S.extended.underlineColor=this._updateAttrColor(S.extended.underlineColor,D[1],D[3],D[4],D[5])}return I}_processUnderline(w,y){y.extended=y.extended.clone(),(!~w||w>5)&&(w=1),y.extended.underlineStyle=w,y.fg|=268435456,w===0&&(y.fg&=-268435457),y.updateExtended()}_processSGR0(w){w.fg=r.DEFAULT_ATTR_DATA.fg,w.bg=r.DEFAULT_ATTR_DATA.bg,w.extended=w.extended.clone(),w.extended.underlineStyle=0,w.extended.underlineColor&=-67108864,w.updateExtended()}charAttributes(w){if(w.length===1&&w.params[0]===0)return this._processSGR0(this._curAttrData),!0;const y=w.length;let S;const D=this._curAttrData;for(let M=0;M<y;M++)S=w.params[M],S>=30&&S<=37?(D.fg&=-50331904,D.fg|=16777216|S-30):S>=40&&S<=47?(D.bg&=-50331904,D.bg|=16777216|S-40):S>=90&&S<=97?(D.fg&=-50331904,D.fg|=16777224|S-90):S>=100&&S<=107?(D.bg&=-50331904,D.bg|=16777224|S-100):S===0?this._processSGR0(D):S===1?D.fg|=134217728:S===3?D.bg|=67108864:S===4?(D.fg|=268435456,this._processUnderline(w.hasSubParams(M)?w.getSubParams(M)[0]:1,D)):S===5?D.fg|=536870912:S===7?D.fg|=67108864:S===8?D.fg|=1073741824:S===9?D.fg|=2147483648:S===2?D.bg|=134217728:S===21?this._processUnderline(2,D):S===22?(D.fg&=-134217729,D.bg&=-134217729):S===23?D.bg&=-67108865:S===24?(D.fg&=-268435457,this._processUnderline(0,D)):S===25?D.fg&=-536870913:S===27?D.fg&=-67108865:S===28?D.fg&=-1073741825:S===29?D.fg&=2147483647:S===39?(D.fg&=-67108864,D.fg|=16777215&r.DEFAULT_ATTR_DATA.fg):S===49?(D.bg&=-67108864,D.bg|=16777215&r.DEFAULT_ATTR_DATA.bg):S===38||S===48||S===58?M+=this._extractColor(w,M,D):S===53?D.bg|=1073741824:S===55?D.bg&=-1073741825:S===59?(D.extended=D.extended.clone(),D.extended.underlineColor=-1,D.updateExtended()):S===100?(D.fg&=-67108864,D.fg|=16777215&r.DEFAULT_ATTR_DATA.fg,D.bg&=-67108864,D.bg|=16777215&r.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",S);return!0}deviceStatus(w){switch(w.params[0]){case 5:this._coreService.triggerDataEvent(`${n.C0.ESC}[0n`);break;case 6:const y=this._activeBuffer.y+1,S=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n.C0.ESC}[${y};${S}R`)}return!0}deviceStatusPrivate(w){if(w.params[0]===6){const y=this._activeBuffer.y+1,S=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n.C0.ESC}[?${y};${S}R`)}return!0}softReset(w){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=r.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(w){const y=w.length===0?1:w.params[0];if(y===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(y){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar"}const S=y%2==1;this._coreService.decPrivateModes.cursorBlink=S}return!0}setScrollRegion(w){const y=w.params[0]||1;let S;return(w.length<2||(S=w.params[1])>this._bufferService.rows||S===0)&&(S=this._bufferService.rows),S>y&&(this._activeBuffer.scrollTop=y-1,this._activeBuffer.scrollBottom=S-1,this._setCursor(0,0)),!0}windowOptions(w){if(!T(w.params[0],this._optionsService.rawOptions.windowOptions))return!0;const y=w.length>1?w.params[1]:0;switch(w.params[0]){case 14:y!==2&&this._onRequestWindowsOptionsReport.fire(C.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(C.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${n.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:y!==0&&y!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),y!==0&&y!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:y!==0&&y!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),y!==0&&y!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(w){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(w){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(w){return this._windowTitle=w,this._onTitleChange.fire(w),!0}setIconName(w){return this._iconName=w,!0}setOrReportIndexedColor(w){const y=[],S=w.split(";");for(;S.length>1;){const D=S.shift(),M=S.shift();if(/^\d+$/.exec(D)){const I=parseInt(D);if(P(I))if(M==="?")y.push({type:0,index:I});else{const F=(0,a.parseColor)(M);F&&y.push({type:1,index:I,color:F})}}}return y.length&&this._onColor.fire(y),!0}setHyperlink(w){const y=w.indexOf(";");if(y===-1)return!0;const S=w.slice(0,y).trim(),D=w.slice(y+1);return D?this._createHyperlink(S,D):!S.trim()&&this._finishHyperlink()}_createHyperlink(w,y){this._getCurrentLinkId()&&this._finishHyperlink();const S=w.split(":");let D;const M=S.findIndex((I=>I.startsWith("id=")));return M!==-1&&(D=S[M].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:D,uri:y}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(w,y){const S=w.split(";");for(let D=0;D<S.length&&!(y>=this._specialColors.length);++D,++y)if(S[D]==="?")this._onColor.fire([{type:0,index:this._specialColors[y]}]);else{const M=(0,a.parseColor)(S[D]);M&&this._onColor.fire([{type:1,index:this._specialColors[y],color:M}])}return!0}setOrReportFgColor(w){return this._setOrReportSpecialColor(w,0)}setOrReportBgColor(w){return this._setOrReportSpecialColor(w,1)}setOrReportCursorColor(w){return this._setOrReportSpecialColor(w,2)}restoreIndexedColor(w){if(!w)return this._onColor.fire([{type:2}]),!0;const y=[],S=w.split(";");for(let D=0;D<S.length;++D)if(/^\d+$/.exec(S[D])){const M=parseInt(S[D]);P(M)&&y.push({type:2,index:M})}return y.length&&this._onColor.fire(y),!0}restoreFgColor(w){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(w){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(w){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,f.DEFAULT_CHARSET),!0}selectCharset(w){return w.length!==2?(this.selectDefaultCharset(),!0):(w[0]==="/"||this._charsetService.setgCharset(b[w[0]],f.CHARSETS[w[1]]||f.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const w=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,w,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=r.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=r.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(w){return this._charsetService.setgLevel(w),!0}screenAlignmentPattern(){const w=new s.CellData;w.content=4194373,w.fg=this._curAttrData.fg,w.bg=this._curAttrData.bg,this._setCursor(0,0);for(let y=0;y<this._bufferService.rows;++y){const S=this._activeBuffer.ybase+this._activeBuffer.y+y,D=this._activeBuffer.lines.get(S);D&&(D.fill(w),D.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(w,y){const S=this._bufferService.buffer,D=this._optionsService.rawOptions;return(M=>(this._coreService.triggerDataEvent(`${n.C0.ESC}${M}${n.C0.ESC}\\`),!0))(w==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:w==='"p'?'P1$r61;1"p':w==="r"?`P1$r${S.scrollTop+1};${S.scrollBottom+1}r`:w==="m"?"P1$r0m":w===" q"?`P1$r${{block:2,underline:4,bar:6}[D.cursorStyle]-(D.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(w,y){this._dirtyRowTracker.markRangeDirty(w,y)}}t.InputHandler=A;let N=class{constructor(W){this._bufferService=W,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(W){W<this.start?this.start=W:W>this.end&&(this.end=W)}markRangeDirty(W,w){W>w&&(E=W,W=w,w=E),W<this.start&&(this.start=W),w>this.end&&(this.end=w)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function P(W){return 0<=W&&W<256}N=i([v(0,l.IBufferService)],N)},7710:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FourKeyMap=t.TwoKeyMap=void 0;class _{constructor(){this._data={}}set(v,n,f){this._data[v]||(this._data[v]={}),this._data[v][n]=f}get(v,n){return this._data[v]?this._data[v][n]:void 0}clear(){this._data={}}}t.TwoKeyMap=_,t.FourKeyMap=class{constructor(){this._data=new _}set(i,v,n,f,g){this._data.get(i,v)||this._data.set(i,v,new _),this._data.get(i,v).set(n,f,g)}get(i,v,n,f){var g;return(g=this._data.get(i,v))==null?void 0:g.get(n,f)}clear(){this._data.clear()}}},701:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isChromeOS=t.isLinux=t.isWindows=t.isIphone=t.isIpad=t.isMac=t.isSafari=t.isLegacyEdge=t.isFirefox=t.isNode=void 0,t.getSafariVersion=function(){if(!t.isSafari)return 0;const v=_.match(/Version\/(\d+)/);return v===null||v.length<2?0:parseInt(v[1])},t.isNode=typeof process<"u"&&"title"in process;const _=t.isNode?"node":navigator.userAgent,i=t.isNode?"node":navigator.platform;t.isFirefox=_.includes("Firefox"),t.isLegacyEdge=_.includes("Edge"),t.isSafari=/^((?!chrome|android).)*safari/i.test(_),t.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(i),t.isIpad=i==="iPad",t.isIphone=i==="iPhone",t.isWindows=["Windows","Win16","Win32","WinCE"].includes(i),t.isLinux=i.indexOf("Linux")>=0,t.isChromeOS=/\bCrOS\b/.test(_)},3087:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedList=void 0;const i=_(6168);let v=0;t.SortedList=class{constructor(n){this._getKey=n,this._array=[],this._insertedValues=[],this._flushInsertedTask=new i.IdleTaskQueue,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new i.IdleTaskQueue,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(n){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue((()=>this._flushInserted())),this._insertedValues.push(n)}_flushInserted(){const n=this._insertedValues.sort(((u,r)=>this._getKey(u)-this._getKey(r)));let f=0,g=0;const p=new Array(this._array.length+this._insertedValues.length);for(let u=0;u<p.length;u++)g>=this._array.length||this._getKey(n[f])<=this._getKey(this._array[g])?(p[u]=n[f],f++):p[u]=this._array[g++];this._array=p,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(n){if(this._flushCleanupInserted(),this._array.length===0)return!1;const f=this._getKey(n);if(f===void 0||(v=this._search(f),v===-1)||this._getKey(this._array[v])!==f)return!1;do if(this._array[v]===n)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue((()=>this._flushDeleted())),this._deletedIndices.push(v),!0;while(++v<this._array.length&&this._getKey(this._array[v])===f);return!1}_flushDeleted(){this._isFlushingDeleted=!0;const n=this._deletedIndices.sort(((u,r)=>u-r));let f=0;const g=new Array(this._array.length-n.length);let p=0;for(let u=0;u<this._array.length;u++)n[f]===u?f++:g[p++]=this._array[u];this._array=g,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(n){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(v=this._search(n),!(v<0||v>=this._array.length)&&this._getKey(this._array[v])===n))do yield this._array[v];while(++v<this._array.length&&this._getKey(this._array[v])===n)}forEachByKey(n,f){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(v=this._search(n),!(v<0||v>=this._array.length)&&this._getKey(this._array[v])===n))do f(this._array[v]);while(++v<this._array.length&&this._getKey(this._array[v])===n)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(n){let f=0,g=this._array.length-1;for(;g>=f;){let p=f+g>>1;const u=this._getKey(this._array[p]);if(u>n)g=p-1;else{if(!(u<n)){for(;p>0&&this._getKey(this._array[p-1])===n;)p--;return p}f=p+1}}return f}}},6168:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DebouncedIdleTask=t.IdleTaskQueue=t.PriorityTaskQueue=void 0;const i=_(701);class v{constructor(){this._tasks=[],this._i=0}enqueue(g){this._tasks.push(g),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(g){this._idleCallback=void 0;let p=0,u=0,r=g.timeRemaining(),h=0;for(;this._i<this._tasks.length;){if(p=performance.now(),this._tasks[this._i]()||this._i++,p=Math.max(1,performance.now()-p),u=Math.max(p,u),h=g.timeRemaining(),1.5*u>h)return r-p<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-p))}ms`),void this._start();r=h}this.clear()}}class n extends v{_requestCallback(g){return setTimeout((()=>g(this._createDeadline(16))))}_cancelCallback(g){clearTimeout(g)}_createDeadline(g){const p=performance.now()+g;return{timeRemaining:()=>Math.max(0,p-performance.now())}}}t.PriorityTaskQueue=n,t.IdleTaskQueue=!i.isNode&&"requestIdleCallback"in window?class extends v{_requestCallback(f){return requestIdleCallback(f)}_cancelCallback(f){cancelIdleCallback(f)}}:n,t.DebouncedIdleTask=class{constructor(){this._queue=new t.IdleTaskQueue}set(f){this._queue.clear(),this._queue.enqueue(f)}flush(){this._queue.flush()}}},5882:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateWindowsModeWrappedState=function(v){const n=v.buffer.lines.get(v.buffer.ybase+v.buffer.y-1),f=n==null?void 0:n.get(v.cols-1),g=v.buffer.lines.get(v.buffer.ybase+v.buffer.y);g&&f&&(g.isWrapped=f[i.CHAR_DATA_CODE_INDEX]!==i.NULL_CELL_CODE&&f[i.CHAR_DATA_CODE_INDEX]!==i.WHITESPACE_CELL_CODE)};const i=_(8938)},5451:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtendedAttrs=t.AttributeData=void 0;class _{constructor(){this.fg=0,this.bg=0,this.extended=new i}static toColorRGB(n){return[n>>>16&255,n>>>8&255,255&n]}static fromColorRGB(n){return(255&n[0])<<16|(255&n[1])<<8|255&n[2]}clone(){const n=new _;return n.fg=this.fg,n.bg=this.bg,n.extended=this.extended.clone(),n}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}t.AttributeData=_;class i{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(n){this._ext=n}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(n){this._ext&=-469762049,this._ext|=n<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(n){this._ext&=-67108864,this._ext|=67108863&n}get urlId(){return this._urlId}set urlId(n){this._urlId=n}get underlineVariantOffset(){const n=(3758096384&this._ext)>>29;return n<0?4294967288^n:n}set underlineVariantOffset(n){this._ext&=536870911,this._ext|=n<<29&3758096384}constructor(n=0,f=0){this._ext=0,this._urlId=0,this._ext=n,this._urlId=f}clone(){return new i(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}t.ExtendedAttrs=i},1073:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Buffer=t.MAX_BUFFER_SIZE=void 0;const i=_(5639),v=_(6168),n=_(5451),f=_(6107),g=_(732),p=_(3055),u=_(8938),r=_(8158),h=_(6760);t.MAX_BUFFER_SIZE=4294967295,t.Buffer=class{constructor(s,e,l){this._hasScrollback=s,this._optionsService=e,this._bufferService=l,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=f.DEFAULT_ATTR_DATA.clone(),this.savedCharset=h.DEFAULT_CHARSET,this.markers=[],this._nullCell=p.CellData.fromCharData([0,u.NULL_CELL_CHAR,u.NULL_CELL_WIDTH,u.NULL_CELL_CODE]),this._whitespaceCell=p.CellData.fromCharData([0,u.WHITESPACE_CELL_CHAR,u.WHITESPACE_CELL_WIDTH,u.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new v.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new i.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(s){return s?(this._nullCell.fg=s.fg,this._nullCell.bg=s.bg,this._nullCell.extended=s.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new n.ExtendedAttrs),this._nullCell}getWhitespaceCell(s){return s?(this._whitespaceCell.fg=s.fg,this._whitespaceCell.bg=s.bg,this._whitespaceCell.extended=s.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new n.ExtendedAttrs),this._whitespaceCell}getBlankLine(s,e){return new f.BufferLine(this._bufferService.cols,this.getNullCell(s),e)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const s=this.ybase+this.y-this.ydisp;return s>=0&&s<this._rows}_getCorrectBufferLength(s){if(!this._hasScrollback)return s;const e=s+this._optionsService.rawOptions.scrollback;return e>t.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:e}fillViewportRows(s){if(this.lines.length===0){s===void 0&&(s=f.DEFAULT_ATTR_DATA);let e=this._rows;for(;e--;)this.lines.push(this.getBlankLine(s))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new i.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(s,e){const l=this.getNullCell(f.DEFAULT_ATTR_DATA);let o=0;const d=this._getCorrectBufferLength(e);if(d>this.lines.maxLength&&(this.lines.maxLength=d),this.lines.length>0){if(this._cols<s)for(let a=0;a<this.lines.length;a++)o+=+this.lines.get(a).resize(s,l);let c=0;if(this._rows<e)for(let a=this._rows;a<e;a++)this.lines.length<e+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new f.BufferLine(s,l)):this.ybase>0&&this.lines.length<=this.ybase+this.y+c+1?(this.ybase--,c++,this.ydisp>0&&this.ydisp--):this.lines.push(new f.BufferLine(s,l)));else for(let a=this._rows;a>e;a--)this.lines.length>e+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(d<this.lines.maxLength){const a=this.lines.length-d;a>0&&(this.lines.trimStart(a),this.ybase=Math.max(this.ybase-a,0),this.ydisp=Math.max(this.ydisp-a,0),this.savedY=Math.max(this.savedY-a,0)),this.lines.maxLength=d}this.x=Math.min(this.x,s-1),this.y=Math.min(this.y,e-1),c&&(this.y+=c),this.savedX=Math.min(this.savedX,s-1),this.scrollTop=0}if(this.scrollBottom=e-1,this._isReflowEnabled&&(this._reflow(s,e),this._cols>s))for(let c=0;c<this.lines.length;c++)o+=+this.lines.get(c).resize(s,l);this._cols=s,this._rows=e,this._memoryCleanupQueue.clear(),o>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let s=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,s=!1);let e=0;for(;this._memoryCleanupPosition<this.lines.length;)if(e+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),e>100)return!0;return s}get _isReflowEnabled(){const s=this._optionsService.rawOptions.windowsPty;return s&&s.buildNumber?this._hasScrollback&&s.backend==="conpty"&&s.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(s,e){this._cols!==s&&(s>this._cols?this._reflowLarger(s,e):this._reflowSmaller(s,e))}_reflowLarger(s,e){const l=this._optionsService.rawOptions.reflowCursorLine,o=(0,g.reflowLargerGetLinesToRemove)(this.lines,this._cols,s,this.ybase+this.y,this.getNullCell(f.DEFAULT_ATTR_DATA),l);if(o.length>0){const d=(0,g.reflowLargerCreateNewLayout)(this.lines,o);(0,g.reflowLargerApplyNewLayout)(this.lines,d.layout),this._reflowLargerAdjustViewport(s,e,d.countRemoved)}}_reflowLargerAdjustViewport(s,e,l){const o=this.getNullCell(f.DEFAULT_ATTR_DATA);let d=l;for(;d-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<e&&this.lines.push(new f.BufferLine(s,o))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-l,0)}_reflowSmaller(s,e){const l=this._optionsService.rawOptions.reflowCursorLine,o=this.getNullCell(f.DEFAULT_ATTR_DATA),d=[];let c=0;for(let a=this.lines.length-1;a>=0;a--){let m=this.lines.get(a);if(!m||!m.isWrapped&&m.getTrimmedLength()<=s)continue;const b=[m];for(;m.isWrapped&&a>0;)m=this.lines.get(--a),b.unshift(m);if(!l){const S=this.ybase+this.y;if(S>=a&&S<a+b.length)continue}const R=b[b.length-1].getTrimmedLength(),T=(0,g.reflowSmallerGetNewLineLengths)(b,this._cols,s),C=T.length-b.length;let E;E=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+C):Math.max(0,this.lines.length-this.lines.maxLength+C);const A=[];for(let S=0;S<C;S++){const D=this.getBlankLine(f.DEFAULT_ATTR_DATA,!0);A.push(D)}A.length>0&&(d.push({start:a+b.length+c,newLines:A}),c+=A.length),b.push(...A);let N=T.length-1,P=T[N];P===0&&(N--,P=T[N]);let W=b.length-C-1,w=R;for(;W>=0;){const S=Math.min(w,P);if(b[N]===void 0)break;if(b[N].copyCellsFrom(b[W],w-S,P-S,S,!0),P-=S,P===0&&(N--,P=T[N]),w-=S,w===0){W--;const D=Math.max(W,0);w=(0,g.getWrappedLineTrimmedLength)(b,D,this._cols)}}for(let S=0;S<b.length;S++)T[S]<s&&b[S].setCell(T[S],o);let y=C-E;for(;y-- >0;)this.ybase===0?this.y<e-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+c)-e&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+C,this.ybase+e-1)}if(d.length>0){const a=[],m=[];for(let P=0;P<this.lines.length;P++)m.push(this.lines.get(P));const b=this.lines.length;let R=b-1,T=0,C=d[T];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+c);let E=0;for(let P=Math.min(this.lines.maxLength-1,b+c-1);P>=0;P--)if(C&&C.start>R+E){for(let W=C.newLines.length-1;W>=0;W--)this.lines.set(P--,C.newLines[W]);P++,a.push({index:R+1,amount:C.newLines.length}),E+=C.newLines.length,C=d[++T]}else this.lines.set(P,m[R--]);let A=0;for(let P=a.length-1;P>=0;P--)a[P].index+=A,this.lines.onInsertEmitter.fire(a[P]),A+=a[P].amount;const N=Math.max(0,b+c-this.lines.maxLength);N>0&&this.lines.onTrimEmitter.fire(N)}}translateBufferLineToString(s,e,l=0,o){const d=this.lines.get(s);return d?d.translateToString(e,l,o):""}getWrappedRangeForLine(s){let e=s,l=s;for(;e>0&&this.lines.get(e).isWrapped;)e--;for(;l+1<this.lines.length&&this.lines.get(l+1).isWrapped;)l++;return{first:e,last:l}}setupTabStops(s){for(s!=null?this.tabs[s]||(s=this.prevStop(s)):(this.tabs={},s=0);s<this._cols;s+=this._optionsService.rawOptions.tabStopWidth)this.tabs[s]=!0}prevStop(s){for(s==null&&(s=this.x);!this.tabs[--s]&&s>0;);return s>=this._cols?this._cols-1:s<0?0:s}nextStop(s){for(s==null&&(s=this.x);!this.tabs[++s]&&s<this._cols;);return s>=this._cols?this._cols-1:s<0?0:s}clearMarkers(s){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].line===s&&(this.markers[e].dispose(),this.markers.splice(e--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let s=0;s<this.markers.length;s++)this.markers[s].dispose();this.markers.length=0,this._isClearing=!1}addMarker(s){const e=new r.Marker(s);return this.markers.push(e),e.register(this.lines.onTrim((l=>{e.line-=l,e.line<0&&e.dispose()}))),e.register(this.lines.onInsert((l=>{e.line>=l.index&&(e.line+=l.amount)}))),e.register(this.lines.onDelete((l=>{e.line>=l.index&&e.line<l.index+l.amount&&e.dispose(),e.line>l.index&&(e.line-=l.amount)}))),e.register(e.onDispose((()=>this._removeMarker(e)))),e}_removeMarker(s){this._isClearing||this.markers.splice(this.markers.indexOf(s),1)}}},6107:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferLine=t.DEFAULT_ATTR_DATA=void 0;const i=_(5451),v=_(3055),n=_(8938),f=_(726);t.DEFAULT_ATTR_DATA=Object.freeze(new i.AttributeData);let g=0;class p{constructor(r,h,s=!1){this.isWrapped=s,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*r);const e=h||v.CellData.fromCharData([0,n.NULL_CELL_CHAR,n.NULL_CELL_WIDTH,n.NULL_CELL_CODE]);for(let l=0;l<r;++l)this.setCell(l,e);this.length=r}get(r){const h=this._data[3*r+0],s=2097151&h;return[this._data[3*r+1],2097152&h?this._combined[r]:s?(0,f.stringFromCodePoint)(s):"",h>>22,2097152&h?this._combined[r].charCodeAt(this._combined[r].length-1):s]}set(r,h){this._data[3*r+1]=h[n.CHAR_DATA_ATTR_INDEX],h[n.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[r]=h[1],this._data[3*r+0]=2097152|r|h[n.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*r+0]=h[n.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|h[n.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(r){return this._data[3*r+0]>>22}hasWidth(r){return 12582912&this._data[3*r+0]}getFg(r){return this._data[3*r+1]}getBg(r){return this._data[3*r+2]}hasContent(r){return 4194303&this._data[3*r+0]}getCodePoint(r){const h=this._data[3*r+0];return 2097152&h?this._combined[r].charCodeAt(this._combined[r].length-1):2097151&h}isCombined(r){return 2097152&this._data[3*r+0]}getString(r){const h=this._data[3*r+0];return 2097152&h?this._combined[r]:2097151&h?(0,f.stringFromCodePoint)(2097151&h):""}isProtected(r){return 536870912&this._data[3*r+2]}loadCell(r,h){return g=3*r,h.content=this._data[g+0],h.fg=this._data[g+1],h.bg=this._data[g+2],2097152&h.content&&(h.combinedData=this._combined[r]),268435456&h.bg&&(h.extended=this._extendedAttrs[r]),h}setCell(r,h){2097152&h.content&&(this._combined[r]=h.combinedData),268435456&h.bg&&(this._extendedAttrs[r]=h.extended),this._data[3*r+0]=h.content,this._data[3*r+1]=h.fg,this._data[3*r+2]=h.bg}setCellFromCodepoint(r,h,s,e){268435456&e.bg&&(this._extendedAttrs[r]=e.extended),this._data[3*r+0]=h|s<<22,this._data[3*r+1]=e.fg,this._data[3*r+2]=e.bg}addCodepointToCell(r,h,s){let e=this._data[3*r+0];2097152&e?this._combined[r]+=(0,f.stringFromCodePoint)(h):2097151&e?(this._combined[r]=(0,f.stringFromCodePoint)(2097151&e)+(0,f.stringFromCodePoint)(h),e&=-2097152,e|=2097152):e=h|4194304,s&&(e&=-12582913,e|=s<<22),this._data[3*r+0]=e}insertCells(r,h,s){if((r%=this.length)&&this.getWidth(r-1)===2&&this.setCellFromCodepoint(r-1,0,1,s),h<this.length-r){const e=new v.CellData;for(let l=this.length-r-h-1;l>=0;--l)this.setCell(r+h+l,this.loadCell(r+l,e));for(let l=0;l<h;++l)this.setCell(r+l,s)}else for(let e=r;e<this.length;++e)this.setCell(e,s);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,s)}deleteCells(r,h,s){if(r%=this.length,h<this.length-r){const e=new v.CellData;for(let l=0;l<this.length-r-h;++l)this.setCell(r+l,this.loadCell(r+h+l,e));for(let l=this.length-h;l<this.length;++l)this.setCell(l,s)}else for(let e=r;e<this.length;++e)this.setCell(e,s);r&&this.getWidth(r-1)===2&&this.setCellFromCodepoint(r-1,0,1,s),this.getWidth(r)!==0||this.hasContent(r)||this.setCellFromCodepoint(r,0,1,s)}replaceCells(r,h,s,e=!1){if(e)for(r&&this.getWidth(r-1)===2&&!this.isProtected(r-1)&&this.setCellFromCodepoint(r-1,0,1,s),h<this.length&&this.getWidth(h-1)===2&&!this.isProtected(h)&&this.setCellFromCodepoint(h,0,1,s);r<h&&r<this.length;)this.isProtected(r)||this.setCell(r,s),r++;else for(r&&this.getWidth(r-1)===2&&this.setCellFromCodepoint(r-1,0,1,s),h<this.length&&this.getWidth(h-1)===2&&this.setCellFromCodepoint(h,0,1,s);r<h&&r<this.length;)this.setCell(r++,s)}resize(r,h){if(r===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;const s=3*r;if(r>this.length){if(this._data.buffer.byteLength>=4*s)this._data=new Uint32Array(this._data.buffer,0,s);else{const e=new Uint32Array(s);e.set(this._data),this._data=e}for(let e=this.length;e<r;++e)this.setCell(e,h)}else{this._data=this._data.subarray(0,s);const e=Object.keys(this._combined);for(let o=0;o<e.length;o++){const d=parseInt(e[o],10);d>=r&&delete this._combined[d]}const l=Object.keys(this._extendedAttrs);for(let o=0;o<l.length;o++){const d=parseInt(l[o],10);d>=r&&delete this._extendedAttrs[d]}}return this.length=r,4*s*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){const r=new Uint32Array(this._data.length);return r.set(this._data),this._data=r,1}return 0}fill(r,h=!1){if(h)for(let s=0;s<this.length;++s)this.isProtected(s)||this.setCell(s,r);else{this._combined={},this._extendedAttrs={};for(let s=0;s<this.length;++s)this.setCell(s,r)}}copyFrom(r){this.length!==r.length?this._data=new Uint32Array(r._data):this._data.set(r._data),this.length=r.length,this._combined={};for(const h in r._combined)this._combined[h]=r._combined[h];this._extendedAttrs={};for(const h in r._extendedAttrs)this._extendedAttrs[h]=r._extendedAttrs[h];this.isWrapped=r.isWrapped}clone(){const r=new p(0);r._data=new Uint32Array(this._data),r.length=this.length;for(const h in this._combined)r._combined[h]=this._combined[h];for(const h in this._extendedAttrs)r._extendedAttrs[h]=this._extendedAttrs[h];return r.isWrapped=this.isWrapped,r}getTrimmedLength(){for(let r=this.length-1;r>=0;--r)if(4194303&this._data[3*r+0])return r+(this._data[3*r+0]>>22);return 0}getNoBgTrimmedLength(){for(let r=this.length-1;r>=0;--r)if(4194303&this._data[3*r+0]||50331648&this._data[3*r+2])return r+(this._data[3*r+0]>>22);return 0}copyCellsFrom(r,h,s,e,l){const o=r._data;if(l)for(let c=e-1;c>=0;c--){for(let a=0;a<3;a++)this._data[3*(s+c)+a]=o[3*(h+c)+a];268435456&o[3*(h+c)+2]&&(this._extendedAttrs[s+c]=r._extendedAttrs[h+c])}else for(let c=0;c<e;c++){for(let a=0;a<3;a++)this._data[3*(s+c)+a]=o[3*(h+c)+a];268435456&o[3*(h+c)+2]&&(this._extendedAttrs[s+c]=r._extendedAttrs[h+c])}const d=Object.keys(r._combined);for(let c=0;c<d.length;c++){const a=parseInt(d[c],10);a>=h&&(this._combined[a-h+s]=r._combined[a])}}translateToString(r,h,s,e){h=h??0,s=s??this.length,r&&(s=Math.min(s,this.getTrimmedLength())),e&&(e.length=0);let l="";for(;h<s;){const o=this._data[3*h+0],d=2097151&o,c=2097152&o?this._combined[h]:d?(0,f.stringFromCodePoint)(d):n.WHITESPACE_CELL_CHAR;if(l+=c,e)for(let a=0;a<c.length;++a)e.push(h);h+=o>>22||1}return e&&e.push(h),l}}t.BufferLine=p},9384:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRangeLength=function(_,i){if(_.start.y>_.end.y)throw new Error(`Buffer range end (${_.end.x}, ${_.end.y}) cannot be before start (${_.start.x}, ${_.start.y})`);return i*(_.end.y-_.start.y)+(_.end.x-_.start.x+1)}},732:(K,t)=>{function _(i,v,n){if(v===i.length-1)return i[v].getTrimmedLength();const f=!i[v].hasContent(n-1)&&i[v].getWidth(n-1)===1,g=i[v+1].getWidth(0)===2;return f&&g?n-1:n}Object.defineProperty(t,"__esModule",{value:!0}),t.reflowLargerGetLinesToRemove=function(i,v,n,f,g,p){const u=[];for(let r=0;r<i.length-1;r++){let h=r,s=i.get(++h);if(!s.isWrapped)continue;const e=[i.get(r)];for(;h<i.length&&s.isWrapped;)e.push(s),s=i.get(++h);if(!p&&f>=r&&f<h){r+=e.length-1;continue}let l=0,o=_(e,l,v),d=1,c=0;for(;d<e.length;){const m=_(e,d,v),b=m-c,R=n-o,T=Math.min(b,R);e[l].copyCellsFrom(e[d],c,o,T,!1),o+=T,o===n&&(l++,o=0),c+=T,c===m&&(d++,c=0),o===0&&l!==0&&e[l-1].getWidth(n-1)===2&&(e[l].copyCellsFrom(e[l-1],n-1,o++,1,!1),e[l-1].setCell(n-1,g))}e[l].replaceCells(o,n,g);let a=0;for(let m=e.length-1;m>0&&(m>l||e[m].getTrimmedLength()===0);m--)a++;a>0&&(u.push(r+e.length-a),u.push(a)),r+=e.length-1}return u},t.reflowLargerCreateNewLayout=function(i,v){const n=[];let f=0,g=v[f],p=0;for(let u=0;u<i.length;u++)if(g===u){const r=v[++f];i.onDeleteEmitter.fire({index:u-p,amount:r}),u+=r-1,p+=r,g=v[++f]}else n.push(u);return{layout:n,countRemoved:p}},t.reflowLargerApplyNewLayout=function(i,v){const n=[];for(let f=0;f<v.length;f++)n.push(i.get(v[f]));for(let f=0;f<n.length;f++)i.set(f,n[f]);i.length=v.length},t.reflowSmallerGetNewLineLengths=function(i,v,n){const f=[],g=i.map(((h,s)=>_(i,s,v))).reduce(((h,s)=>h+s));let p=0,u=0,r=0;for(;r<g;){if(g-r<n){f.push(g-r);break}p+=n;const h=_(i,u,v);p>h&&(p-=h,u++);const s=i[u].getWidth(p-1)===2;s&&p--;const e=s?n-1:n;f.push(e),r+=e}return f},t.getWrappedLineTrimmedLength=_},4097:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferSet=void 0;const i=_(7150),v=_(1073),n=_(802);class f extends i.Disposable{constructor(p,u){super(),this._optionsService=p,this._bufferService=u,this._onBufferActivate=this._register(new n.Emitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",(()=>this.setupTabStops())))}reset(){this._normal=new v.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new v.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(p){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(p),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(p,u){this._normal.resize(p,u),this._alt.resize(p,u),this.setupTabStops(p)}setupTabStops(p){this._normal.setupTabStops(p),this._alt.setupTabStops(p)}}t.BufferSet=f},3055:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CellData=void 0;const i=_(726),v=_(8938),n=_(5451);class f extends n.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new n.ExtendedAttrs,this.combinedData=""}static fromCharData(p){const u=new f;return u.setFromCharData(p),u}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,i.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(p){this.fg=p[v.CHAR_DATA_ATTR_INDEX],this.bg=0;let u=!1;if(p[v.CHAR_DATA_CHAR_INDEX].length>2)u=!0;else if(p[v.CHAR_DATA_CHAR_INDEX].length===2){const r=p[v.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=r&&r<=56319){const h=p[v.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=h&&h<=57343?this.content=1024*(r-55296)+h-56320+65536|p[v.CHAR_DATA_WIDTH_INDEX]<<22:u=!0}else u=!0}else this.content=p[v.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|p[v.CHAR_DATA_WIDTH_INDEX]<<22;u&&(this.combinedData=p[v.CHAR_DATA_CHAR_INDEX],this.content=2097152|p[v.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.CellData=f},8938:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WHITESPACE_CELL_CODE=t.WHITESPACE_CELL_WIDTH=t.WHITESPACE_CELL_CHAR=t.NULL_CELL_CODE=t.NULL_CELL_WIDTH=t.NULL_CELL_CHAR=t.CHAR_DATA_CODE_INDEX=t.CHAR_DATA_WIDTH_INDEX=t.CHAR_DATA_CHAR_INDEX=t.CHAR_DATA_ATTR_INDEX=t.DEFAULT_EXT=t.DEFAULT_ATTR=t.DEFAULT_COLOR=void 0,t.DEFAULT_COLOR=0,t.DEFAULT_ATTR=t.DEFAULT_COLOR<<9|256,t.DEFAULT_EXT=0,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR="",t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=" ",t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},8158:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Marker=void 0;const i=_(802),v=_(7150);class n{get id(){return this._id}constructor(g){this.line=g,this.isDisposed=!1,this._disposables=[],this._id=n._nextId++,this._onDispose=this.register(new i.Emitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,v.dispose)(this._disposables),this._disposables.length=0)}register(g){return this._disposables.push(g),g}}t.Marker=n,n._nextId=1},6760:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_CHARSET=t.CHARSETS=void 0,t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":"\u25C6",a:"\u2592",b:"\u2409",c:"\u240C",d:"\u240D",e:"\u240A",f:"\xB0",g:"\xB1",h:"\u2424",i:"\u240B",j:"\u2518",k:"\u2510",l:"\u250C",m:"\u2514",n:"\u253C",o:"\u23BA",p:"\u23BB",q:"\u2500",r:"\u23BC",s:"\u23BD",t:"\u251C",u:"\u2524",v:"\u2534",w:"\u252C",x:"\u2502",y:"\u2264",z:"\u2265","{":"\u03C0","|":"\u2260","}":"\xA3","~":"\xB7"},t.CHARSETS.A={"#":"\xA3"},t.CHARSETS.B=void 0,t.CHARSETS[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"},t.CHARSETS.C=t.CHARSETS[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"},t.CHARSETS.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"},t.CHARSETS.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"},t.CHARSETS.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"},t.CHARSETS.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"},t.CHARSETS.E=t.CHARSETS[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"},t.CHARSETS.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"},t.CHARSETS.H=t.CHARSETS[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"},t.CHARSETS["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"}},3534:(K,t)=>{var _,i,v;Object.defineProperty(t,"__esModule",{value:!0}),t.C1_ESCAPED=t.C1=t.C0=void 0,(function(n){n.NUL="\0",n.SOH="",n.STX="",n.ETX="",n.EOT="",n.ENQ="",n.ACK="",n.BEL="\x07",n.BS="\b",n.HT=" ",n.LF=`
+`,n.VT="\v",n.FF="\f",n.CR="\r",n.SO="",n.SI="",n.DLE="",n.DC1="",n.DC2="",n.DC3="",n.DC4="",n.NAK="",n.SYN="",n.ETB="",n.CAN="",n.EM="",n.SUB="",n.ESC="\x1B",n.FS="",n.GS="",n.RS="",n.US="",n.SP=" ",n.DEL="\x7F"})(_||(t.C0=_={})),(function(n){n.PAD="\x80",n.HOP="\x81",n.BPH="\x82",n.NBH="\x83",n.IND="\x84",n.NEL="\x85",n.SSA="\x86",n.ESA="\x87",n.HTS="\x88",n.HTJ="\x89",n.VTS="\x8A",n.PLD="\x8B",n.PLU="\x8C",n.RI="\x8D",n.SS2="\x8E",n.SS3="\x8F",n.DCS="\x90",n.PU1="\x91",n.PU2="\x92",n.STS="\x93",n.CCH="\x94",n.MW="\x95",n.SPA="\x96",n.EPA="\x97",n.SOS="\x98",n.SGCI="\x99",n.SCI="\x9A",n.CSI="\x9B",n.ST="\x9C",n.OSC="\x9D",n.PM="\x9E",n.APC="\x9F"})(i||(t.C1=i={})),(function(n){n.ST=`${_.ESC}\\`})(v||(t.C1_ESCAPED=v={}))},706:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateKeyboardEvent=function(n,f,g,p){const u={type:0,cancel:!1,key:void 0},r=(n.shiftKey?1:0)|(n.altKey?2:0)|(n.ctrlKey?4:0)|(n.metaKey?8:0);switch(n.keyCode){case 0:n.key==="UIKeyInputUpArrow"?u.key=f?i.C0.ESC+"OA":i.C0.ESC+"[A":n.key==="UIKeyInputLeftArrow"?u.key=f?i.C0.ESC+"OD":i.C0.ESC+"[D":n.key==="UIKeyInputRightArrow"?u.key=f?i.C0.ESC+"OC":i.C0.ESC+"[C":n.key==="UIKeyInputDownArrow"&&(u.key=f?i.C0.ESC+"OB":i.C0.ESC+"[B");break;case 8:u.key=n.ctrlKey?"\b":i.C0.DEL,n.altKey&&(u.key=i.C0.ESC+u.key);break;case 9:if(n.shiftKey){u.key=i.C0.ESC+"[Z";break}u.key=i.C0.HT,u.cancel=!0;break;case 13:u.key=n.altKey?i.C0.ESC+i.C0.CR:i.C0.CR,u.cancel=!0;break;case 27:u.key=i.C0.ESC,n.altKey&&(u.key=i.C0.ESC+i.C0.ESC),u.cancel=!0;break;case 37:if(n.metaKey)break;u.key=r?i.C0.ESC+"[1;"+(r+1)+"D":f?i.C0.ESC+"OD":i.C0.ESC+"[D";break;case 39:if(n.metaKey)break;u.key=r?i.C0.ESC+"[1;"+(r+1)+"C":f?i.C0.ESC+"OC":i.C0.ESC+"[C";break;case 38:if(n.metaKey)break;u.key=r?i.C0.ESC+"[1;"+(r+1)+"A":f?i.C0.ESC+"OA":i.C0.ESC+"[A";break;case 40:if(n.metaKey)break;u.key=r?i.C0.ESC+"[1;"+(r+1)+"B":f?i.C0.ESC+"OB":i.C0.ESC+"[B";break;case 45:n.shiftKey||n.ctrlKey||(u.key=i.C0.ESC+"[2~");break;case 46:u.key=r?i.C0.ESC+"[3;"+(r+1)+"~":i.C0.ESC+"[3~";break;case 36:u.key=r?i.C0.ESC+"[1;"+(r+1)+"H":f?i.C0.ESC+"OH":i.C0.ESC+"[H";break;case 35:u.key=r?i.C0.ESC+"[1;"+(r+1)+"F":f?i.C0.ESC+"OF":i.C0.ESC+"[F";break;case 33:n.shiftKey?u.type=2:n.ctrlKey?u.key=i.C0.ESC+"[5;"+(r+1)+"~":u.key=i.C0.ESC+"[5~";break;case 34:n.shiftKey?u.type=3:n.ctrlKey?u.key=i.C0.ESC+"[6;"+(r+1)+"~":u.key=i.C0.ESC+"[6~";break;case 112:u.key=r?i.C0.ESC+"[1;"+(r+1)+"P":i.C0.ESC+"OP";break;case 113:u.key=r?i.C0.ESC+"[1;"+(r+1)+"Q":i.C0.ESC+"OQ";break;case 114:u.key=r?i.C0.ESC+"[1;"+(r+1)+"R":i.C0.ESC+"OR";break;case 115:u.key=r?i.C0.ESC+"[1;"+(r+1)+"S":i.C0.ESC+"OS";break;case 116:u.key=r?i.C0.ESC+"[15;"+(r+1)+"~":i.C0.ESC+"[15~";break;case 117:u.key=r?i.C0.ESC+"[17;"+(r+1)+"~":i.C0.ESC+"[17~";break;case 118:u.key=r?i.C0.ESC+"[18;"+(r+1)+"~":i.C0.ESC+"[18~";break;case 119:u.key=r?i.C0.ESC+"[19;"+(r+1)+"~":i.C0.ESC+"[19~";break;case 120:u.key=r?i.C0.ESC+"[20;"+(r+1)+"~":i.C0.ESC+"[20~";break;case 121:u.key=r?i.C0.ESC+"[21;"+(r+1)+"~":i.C0.ESC+"[21~";break;case 122:u.key=r?i.C0.ESC+"[23;"+(r+1)+"~":i.C0.ESC+"[23~";break;case 123:u.key=r?i.C0.ESC+"[24;"+(r+1)+"~":i.C0.ESC+"[24~";break;default:if(!n.ctrlKey||n.shiftKey||n.altKey||n.metaKey)if(g&&!p||!n.altKey||n.metaKey)!g||n.altKey||n.ctrlKey||n.shiftKey||!n.metaKey?n.key&&!n.ctrlKey&&!n.altKey&&!n.metaKey&&n.keyCode>=48&&n.key.length===1?u.key=n.key:n.key&&n.ctrlKey&&(n.key==="_"&&(u.key=i.C0.US),n.key==="@"&&(u.key=i.C0.NUL)):n.keyCode===65&&(u.type=1);else{const h=v[n.keyCode],s=h==null?void 0:h[n.shiftKey?1:0];if(s)u.key=i.C0.ESC+s;else if(n.keyCode>=65&&n.keyCode<=90){const e=n.ctrlKey?n.keyCode-64:n.keyCode+32;let l=String.fromCharCode(e);n.shiftKey&&(l=l.toUpperCase()),u.key=i.C0.ESC+l}else if(n.keyCode===32)u.key=i.C0.ESC+(n.ctrlKey?i.C0.NUL:" ");else if(n.key==="Dead"&&n.code.startsWith("Key")){let e=n.code.slice(3,4);n.shiftKey||(e=e.toLowerCase()),u.key=i.C0.ESC+e,u.cancel=!0}}else n.keyCode>=65&&n.keyCode<=90?u.key=String.fromCharCode(n.keyCode-64):n.keyCode===32?u.key=i.C0.NUL:n.keyCode>=51&&n.keyCode<=55?u.key=String.fromCharCode(n.keyCode-51+27):n.keyCode===56?u.key=i.C0.DEL:n.keyCode===219?u.key=i.C0.ESC:n.keyCode===220?u.key=i.C0.FS:n.keyCode===221&&(u.key=i.C0.GS)}return u};const i=_(3534),v={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']}},726:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Utf8ToUtf32=t.StringToUtf32=void 0,t.stringFromCodePoint=function(_){return _>65535?(_-=65536,String.fromCharCode(55296+(_>>10))+String.fromCharCode(_%1024+56320)):String.fromCharCode(_)},t.utf32ToString=function(_,i=0,v=_.length){let n="";for(let f=i;f<v;++f){let g=_[f];g>65535?(g-=65536,n+=String.fromCharCode(55296+(g>>10))+String.fromCharCode(g%1024+56320)):n+=String.fromCharCode(g)}return n},t.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(_,i){const v=_.length;if(!v)return 0;let n=0,f=0;if(this._interim){const g=_.charCodeAt(f++);56320<=g&&g<=57343?i[n++]=1024*(this._interim-55296)+g-56320+65536:(i[n++]=this._interim,i[n++]=g),this._interim=0}for(let g=f;g<v;++g){const p=_.charCodeAt(g);if(55296<=p&&p<=56319){if(++g>=v)return this._interim=p,n;const u=_.charCodeAt(g);56320<=u&&u<=57343?i[n++]=1024*(p-55296)+u-56320+65536:(i[n++]=p,i[n++]=u)}else p!==65279&&(i[n++]=p)}return n}},t.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(_,i){const v=_.length;if(!v)return 0;let n,f,g,p,u=0,r=0,h=0;if(this.interim[0]){let l=!1,o=this.interim[0];o&=(224&o)==192?31:(240&o)==224?15:7;let d,c=0;for(;(d=63&this.interim[++c])&&c<4;)o<<=6,o|=d;const a=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,m=a-c;for(;h<m;){if(h>=v)return 0;if(d=_[h++],(192&d)!=128){h--,l=!0;break}this.interim[c++]=d,o<<=6,o|=63&d}l||(a===2?o<128?h--:i[u++]=o:a===3?o<2048||o>=55296&&o<=57343||o===65279||(i[u++]=o):o<65536||o>1114111||(i[u++]=o)),this.interim.fill(0)}const s=v-4;let e=h;for(;e<v;){for(;!(!(e<s)||128&(n=_[e])||128&(f=_[e+1])||128&(g=_[e+2])||128&(p=_[e+3]));)i[u++]=n,i[u++]=f,i[u++]=g,i[u++]=p,e+=4;if(n=_[e++],n<128)i[u++]=n;else if((224&n)==192){if(e>=v)return this.interim[0]=n,u;if(f=_[e++],(192&f)!=128){e--;continue}if(r=(31&n)<<6|63&f,r<128){e--;continue}i[u++]=r}else if((240&n)==224){if(e>=v)return this.interim[0]=n,u;if(f=_[e++],(192&f)!=128){e--;continue}if(e>=v)return this.interim[0]=n,this.interim[1]=f,u;if(g=_[e++],(192&g)!=128){e--;continue}if(r=(15&n)<<12|(63&f)<<6|63&g,r<2048||r>=55296&&r<=57343||r===65279)continue;i[u++]=r}else if((248&n)==240){if(e>=v)return this.interim[0]=n,u;if(f=_[e++],(192&f)!=128){e--;continue}if(e>=v)return this.interim[0]=n,this.interim[1]=f,u;if(g=_[e++],(192&g)!=128){e--;continue}if(e>=v)return this.interim[0]=n,this.interim[1]=f,this.interim[2]=g,u;if(p=_[e++],(192&p)!=128){e--;continue}if(r=(7&n)<<18|(63&f)<<12|(63&g)<<6|63&p,r<65536||r>1114111)continue;i[u++]=r}}return u}}},7428:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeV6=void 0;const i=_(6415),v=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],n=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];let f;t.UnicodeV6=class{constructor(){if(this.version="6",!f){f=new Uint8Array(65536),f.fill(1),f[0]=0,f.fill(0,1,32),f.fill(0,127,160),f.fill(2,4352,4448),f[9001]=2,f[9002]=2,f.fill(2,11904,42192),f[12351]=1,f.fill(2,44032,55204),f.fill(2,63744,64256),f.fill(2,65040,65050),f.fill(2,65072,65136),f.fill(2,65280,65377),f.fill(2,65504,65511);for(let g=0;g<v.length;++g)f.fill(0,v[g][0],v[g][1]+1)}}wcwidth(g){return g<32?0:g<127?1:g<65536?f[g]:(function(p,u){let r,h=0,s=u.length-1;if(p<u[0][0]||p>u[s][1])return!1;for(;s>=h;)if(r=h+s>>1,p>u[r][1])h=r+1;else{if(!(p<u[r][0]))return!0;s=r-1}return!1})(g,n)?0:g>=131072&&g<=196605||g>=196608&&g<=262141?2:1}charProperties(g,p){let u=this.wcwidth(g),r=u===0&&p!==0;if(r){const h=i.UnicodeService.extractWidth(p);h===0?r=!1:h>u&&(u=h)}return i.UnicodeService.createPropertyValue(0,u,r)}}},3562:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WriteBuffer=void 0;const i=_(7150),v=_(802);class n extends i.Disposable{constructor(g){super(),this._action=g,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new v.Emitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(g,p){if(p!==void 0&&this._syncCalls>p)return void(this._syncCalls=0);if(this._pendingData+=g.length,this._writeBuffer.push(g),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let u;for(this._isSyncWriting=!0;u=this._writeBuffer.shift();){this._action(u);const r=this._callbacks.shift();r&&r()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(g,p){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=g.length,this._writeBuffer.push(g),this._callbacks.push(p),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=g.length,this._writeBuffer.push(g),this._callbacks.push(p)}_innerWrite(g=0,p=!0){const u=g||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){const r=this._writeBuffer[this._bufferOffset],h=this._action(r,p);if(h){const e=l=>performance.now()-u>=12?setTimeout((()=>this._innerWrite(0,l))):this._innerWrite(u,l);return void h.catch((l=>(queueMicrotask((()=>{throw l})),Promise.resolve(!1)))).then(e)}const s=this._callbacks[this._bufferOffset];if(s&&s(),this._bufferOffset++,this._pendingData-=r.length,performance.now()-u>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}t.WriteBuffer=n},8693:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseColor=function(n){if(!n)return;let f=n.toLowerCase();if(f.indexOf("rgb:")===0){f=f.slice(4);const g=_.exec(f);if(g){const p=g[1]?15:g[4]?255:g[7]?4095:65535;return[Math.round(parseInt(g[1]||g[4]||g[7]||g[10],16)/p*255),Math.round(parseInt(g[2]||g[5]||g[8]||g[11],16)/p*255),Math.round(parseInt(g[3]||g[6]||g[9]||g[12],16)/p*255)]}}else if(f.indexOf("#")===0&&(f=f.slice(1),i.exec(f)&&[3,6,9,12].includes(f.length))){const g=f.length/3,p=[0,0,0];for(let u=0;u<3;++u){const r=parseInt(f.slice(g*u,g*u+g),16);p[u]=g===1?r<<4:g===2?r:g===3?r>>4:r>>8}return p}},t.toRgbString=function(n,f=16){const[g,p,u]=n;return`rgb:${v(g,f)}/${v(p,f)}/${v(u,f)}`};const _=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,i=/^[\da-f]+$/;function v(n,f){const g=n.toString(16),p=g.length<2?"0"+g:g;switch(f){case 4:return g[0];case 8:return p;case 12:return(p+p).slice(0,3);default:return p+p}}},1263:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PAYLOAD_LIMIT=void 0,t.PAYLOAD_LIMIT=1e7},9823:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DcsHandler=t.DcsParser=void 0;const i=_(726),v=_(7262),n=_(1263),f=[];t.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=f,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=f}registerHandler(p,u){this._handlers[p]===void 0&&(this._handlers[p]=[]);const r=this._handlers[p];return r.push(u),{dispose:()=>{const h=r.indexOf(u);h!==-1&&r.splice(h,1)}}}clearHandler(p){this._handlers[p]&&delete this._handlers[p]}setHandlerFallback(p){this._handlerFb=p}reset(){if(this._active.length)for(let p=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;p>=0;--p)this._active[p].unhook(!1);this._stack.paused=!1,this._active=f,this._ident=0}hook(p,u){if(this.reset(),this._ident=p,this._active=this._handlers[p]||f,this._active.length)for(let r=this._active.length-1;r>=0;r--)this._active[r].hook(u);else this._handlerFb(this._ident,"HOOK",u)}put(p,u,r){if(this._active.length)for(let h=this._active.length-1;h>=0;h--)this._active[h].put(p,u,r);else this._handlerFb(this._ident,"PUT",(0,i.utf32ToString)(p,u,r))}unhook(p,u=!0){if(this._active.length){let r=!1,h=this._active.length-1,s=!1;if(this._stack.paused&&(h=this._stack.loopPosition-1,r=u,s=this._stack.fallThrough,this._stack.paused=!1),!s&&r===!1){for(;h>=0&&(r=this._active[h].unhook(p),r!==!0);h--)if(r instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=h,this._stack.fallThrough=!1,r;h--}for(;h>=0;h--)if(r=this._active[h].unhook(!1),r instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=h,this._stack.fallThrough=!0,r}else this._handlerFb(this._ident,"UNHOOK",p);this._active=f,this._ident=0}};const g=new v.Params;g.addParam(0),t.DcsHandler=class{constructor(p){this._handler=p,this._data="",this._params=g,this._hitLimit=!1}hook(p){this._params=p.length>1||p.params[0]?p.clone():g,this._data="",this._hitLimit=!1}put(p,u,r){this._hitLimit||(this._data+=(0,i.utf32ToString)(p,u,r),this._data.length>n.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(p){let u=!1;if(this._hitLimit)u=!1;else if(p&&(u=this._handler(this._data,this._params),u instanceof Promise))return u.then((r=>(this._params=g,this._data="",this._hitLimit=!1,r)));return this._params=g,this._data="",this._hitLimit=!1,u}}},6717:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EscapeSequenceParser=t.VT500_TRANSITION_TABLE=t.TransitionTable=void 0;const i=_(7150),v=_(7262),n=_(1346),f=_(9823);class g{constructor(h){this.table=new Uint8Array(h)}setDefault(h,s){this.table.fill(h<<4|s)}add(h,s,e,l){this.table[s<<8|h]=e<<4|l}addMany(h,s,e,l){for(let o=0;o<h.length;o++)this.table[s<<8|h[o]]=e<<4|l}}t.TransitionTable=g;const p=160;t.VT500_TRANSITION_TABLE=(function(){const r=new g(4095),h=Array.apply(null,Array(256)).map(((c,a)=>a)),s=(c,a)=>h.slice(c,a),e=s(32,127),l=s(0,24);l.push(25),l.push.apply(l,s(28,32));const o=s(0,14);let d;for(d in r.setDefault(1,0),r.addMany(e,0,2,0),o)r.addMany([24,26,153,154],d,3,0),r.addMany(s(128,144),d,3,0),r.addMany(s(144,152),d,3,0),r.add(156,d,0,0),r.add(27,d,11,1),r.add(157,d,4,8),r.addMany([152,158,159],d,0,7),r.add(155,d,11,3),r.add(144,d,11,9);return r.addMany(l,0,3,0),r.addMany(l,1,3,1),r.add(127,1,0,1),r.addMany(l,8,0,8),r.addMany(l,3,3,3),r.add(127,3,0,3),r.addMany(l,4,3,4),r.add(127,4,0,4),r.addMany(l,6,3,6),r.addMany(l,5,3,5),r.add(127,5,0,5),r.addMany(l,2,3,2),r.add(127,2,0,2),r.add(93,1,4,8),r.addMany(e,8,5,8),r.add(127,8,5,8),r.addMany([156,27,24,26,7],8,6,0),r.addMany(s(28,32),8,0,8),r.addMany([88,94,95],1,0,7),r.addMany(e,7,0,7),r.addMany(l,7,0,7),r.add(156,7,0,0),r.add(127,7,0,7),r.add(91,1,11,3),r.addMany(s(64,127),3,7,0),r.addMany(s(48,60),3,8,4),r.addMany([60,61,62,63],3,9,4),r.addMany(s(48,60),4,8,4),r.addMany(s(64,127),4,7,0),r.addMany([60,61,62,63],4,0,6),r.addMany(s(32,64),6,0,6),r.add(127,6,0,6),r.addMany(s(64,127),6,0,0),r.addMany(s(32,48),3,9,5),r.addMany(s(32,48),5,9,5),r.addMany(s(48,64),5,0,6),r.addMany(s(64,127),5,7,0),r.addMany(s(32,48),4,9,5),r.addMany(s(32,48),1,9,2),r.addMany(s(32,48),2,9,2),r.addMany(s(48,127),2,10,0),r.addMany(s(48,80),1,10,0),r.addMany(s(81,88),1,10,0),r.addMany([89,90,92],1,10,0),r.addMany(s(96,127),1,10,0),r.add(80,1,11,9),r.addMany(l,9,0,9),r.add(127,9,0,9),r.addMany(s(28,32),9,0,9),r.addMany(s(32,48),9,9,12),r.addMany(s(48,60),9,8,10),r.addMany([60,61,62,63],9,9,10),r.addMany(l,11,0,11),r.addMany(s(32,128),11,0,11),r.addMany(s(28,32),11,0,11),r.addMany(l,10,0,10),r.add(127,10,0,10),r.addMany(s(28,32),10,0,10),r.addMany(s(48,60),10,8,10),r.addMany([60,61,62,63],10,0,11),r.addMany(s(32,48),10,9,12),r.addMany(l,12,0,12),r.add(127,12,0,12),r.addMany(s(28,32),12,0,12),r.addMany(s(32,48),12,9,12),r.addMany(s(48,64),12,0,11),r.addMany(s(64,127),12,12,13),r.addMany(s(64,127),10,12,13),r.addMany(s(64,127),9,12,13),r.addMany(l,13,13,13),r.addMany(e,13,13,13),r.add(127,13,0,13),r.addMany([27,156,24,26],13,14,0),r.add(p,0,2,0),r.add(p,8,5,8),r.add(p,6,0,6),r.add(p,11,0,11),r.add(p,13,13,13),r})();class u extends i.Disposable{constructor(h=t.VT500_TRANSITION_TABLE){super(),this._transitions=h,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new v.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(s,e,l)=>{},this._executeHandlerFb=s=>{},this._csiHandlerFb=(s,e)=>{},this._escHandlerFb=s=>{},this._errorHandlerFb=s=>s,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register((0,i.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this._register(new n.OscParser),this._dcsParser=this._register(new f.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(h,s=[64,126]){let e=0;if(h.prefix){if(h.prefix.length>1)throw new Error("only one byte as prefix supported");if(e=h.prefix.charCodeAt(0),e&&60>e||e>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(h.intermediates){if(h.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let o=0;o<h.intermediates.length;++o){const d=h.intermediates.charCodeAt(o);if(32>d||d>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");e<<=8,e|=d}}if(h.final.length!==1)throw new Error("final must be a single byte");const l=h.final.charCodeAt(0);if(s[0]>l||l>s[1])throw new Error(`final must be in range ${s[0]} .. ${s[1]}`);return e<<=8,e|=l,e}identToString(h){const s=[];for(;h;)s.push(String.fromCharCode(255&h)),h>>=8;return s.reverse().join("")}setPrintHandler(h){this._printHandler=h}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(h,s){const e=this._identifier(h,[48,126]);this._escHandlers[e]===void 0&&(this._escHandlers[e]=[]);const l=this._escHandlers[e];return l.push(s),{dispose:()=>{const o=l.indexOf(s);o!==-1&&l.splice(o,1)}}}clearEscHandler(h){this._escHandlers[this._identifier(h,[48,126])]&&delete this._escHandlers[this._identifier(h,[48,126])]}setEscHandlerFallback(h){this._escHandlerFb=h}setExecuteHandler(h,s){this._executeHandlers[h.charCodeAt(0)]=s}clearExecuteHandler(h){this._executeHandlers[h.charCodeAt(0)]&&delete this._executeHandlers[h.charCodeAt(0)]}setExecuteHandlerFallback(h){this._executeHandlerFb=h}registerCsiHandler(h,s){const e=this._identifier(h);this._csiHandlers[e]===void 0&&(this._csiHandlers[e]=[]);const l=this._csiHandlers[e];return l.push(s),{dispose:()=>{const o=l.indexOf(s);o!==-1&&l.splice(o,1)}}}clearCsiHandler(h){this._csiHandlers[this._identifier(h)]&&delete this._csiHandlers[this._identifier(h)]}setCsiHandlerFallback(h){this._csiHandlerFb=h}registerDcsHandler(h,s){return this._dcsParser.registerHandler(this._identifier(h),s)}clearDcsHandler(h){this._dcsParser.clearHandler(this._identifier(h))}setDcsHandlerFallback(h){this._dcsParser.setHandlerFallback(h)}registerOscHandler(h,s){return this._oscParser.registerHandler(h,s)}clearOscHandler(h){this._oscParser.clearHandler(h)}setOscHandlerFallback(h){this._oscParser.setHandlerFallback(h)}setErrorHandler(h){this._errorHandler=h}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(h,s,e,l,o){this._parseStack.state=h,this._parseStack.handlers=s,this._parseStack.handlerPos=e,this._parseStack.transition=l,this._parseStack.chunkPos=o}parse(h,s,e){let l,o=0,d=0,c=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,c=this._parseStack.chunkPos+1;else{if(e===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const a=this._parseStack.handlers;let m=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(e===!1&&m>-1){for(;m>=0&&(l=a[m](this._params),l!==!0);m--)if(l instanceof Promise)return this._parseStack.handlerPos=m,l}this._parseStack.handlers=[];break;case 4:if(e===!1&&m>-1){for(;m>=0&&(l=a[m](),l!==!0);m--)if(l instanceof Promise)return this._parseStack.handlerPos=m,l}this._parseStack.handlers=[];break;case 6:if(o=h[this._parseStack.chunkPos],l=this._dcsParser.unhook(o!==24&&o!==26,e),l)return l;o===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(o=h[this._parseStack.chunkPos],l=this._oscParser.end(o!==24&&o!==26,e),l)return l;o===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,c=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let a=c;a<s;++a){switch(o=h[a],d=this._transitions.table[this.currentState<<8|(o<160?o:p)],d>>4){case 2:for(let C=a+1;;++C){if(C>=s||(o=h[C])<32||o>126&&o<p){this._printHandler(h,a,C),a=C-1;break}if(++C>=s||(o=h[C])<32||o>126&&o<p){this._printHandler(h,a,C),a=C-1;break}if(++C>=s||(o=h[C])<32||o>126&&o<p){this._printHandler(h,a,C),a=C-1;break}if(++C>=s||(o=h[C])<32||o>126&&o<p){this._printHandler(h,a,C),a=C-1;break}}break;case 3:this._executeHandlers[o]?this._executeHandlers[o]():this._executeHandlerFb(o),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:a,code:o,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:const m=this._csiHandlers[this._collect<<8|o];let b=m?m.length-1:-1;for(;b>=0&&(l=m[b](this._params),l!==!0);b--)if(l instanceof Promise)return this._preserveStack(3,m,b,d,a),l;b<0&&this._csiHandlerFb(this._collect<<8|o,this._params),this.precedingJoinState=0;break;case 8:do switch(o){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(o-48)}while(++a<s&&(o=h[a])>47&&o<60);a--;break;case 9:this._collect<<=8,this._collect|=o;break;case 10:const R=this._escHandlers[this._collect<<8|o];let T=R?R.length-1:-1;for(;T>=0&&(l=R[T](),l!==!0);T--)if(l instanceof Promise)return this._preserveStack(4,R,T,d,a),l;T<0&&this._escHandlerFb(this._collect<<8|o),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|o,this._params);break;case 13:for(let C=a+1;;++C)if(C>=s||(o=h[C])===24||o===26||o===27||o>127&&o<p){this._dcsParser.put(h,a,C),a=C-1;break}break;case 14:if(l=this._dcsParser.unhook(o!==24&&o!==26),l)return this._preserveStack(6,[],0,d,a),l;o===27&&(d|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let C=a+1;;C++)if(C>=s||(o=h[C])<32||o>127&&o<p){this._oscParser.put(h,a,C),a=C-1;break}break;case 6:if(l=this._oscParser.end(o!==24&&o!==26),l)return this._preserveStack(5,[],0,d,a),l;o===27&&(d|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&d}}}t.EscapeSequenceParser=u},1346:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OscHandler=t.OscParser=void 0;const i=_(1263),v=_(726),n=[];t.OscParser=class{constructor(){this._state=0,this._active=n,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(f,g){this._handlers[f]===void 0&&(this._handlers[f]=[]);const p=this._handlers[f];return p.push(g),{dispose:()=>{const u=p.indexOf(g);u!==-1&&p.splice(u,1)}}}clearHandler(f){this._handlers[f]&&delete this._handlers[f]}setHandlerFallback(f){this._handlerFb=f}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=n}reset(){if(this._state===2)for(let f=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;f>=0;--f)this._active[f].end(!1);this._stack.paused=!1,this._active=n,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||n,this._active.length)for(let f=this._active.length-1;f>=0;f--)this._active[f].start();else this._handlerFb(this._id,"START")}_put(f,g,p){if(this._active.length)for(let u=this._active.length-1;u>=0;u--)this._active[u].put(f,g,p);else this._handlerFb(this._id,"PUT",(0,v.utf32ToString)(f,g,p))}start(){this.reset(),this._state=1}put(f,g,p){if(this._state!==3){if(this._state===1)for(;g<p;){const u=f[g++];if(u===59){this._state=2,this._start();break}if(u<48||57<u)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+u-48}this._state===2&&p-g>0&&this._put(f,g,p)}}end(f,g=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let p=!1,u=this._active.length-1,r=!1;if(this._stack.paused&&(u=this._stack.loopPosition-1,p=g,r=this._stack.fallThrough,this._stack.paused=!1),!r&&p===!1){for(;u>=0&&(p=this._active[u].end(f),p!==!0);u--)if(p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=u,this._stack.fallThrough=!1,p;u--}for(;u>=0;u--)if(p=this._active[u].end(!1),p instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=u,this._stack.fallThrough=!0,p}else this._handlerFb(this._id,"END",f);this._active=n,this._id=-1,this._state=0}}},t.OscHandler=class{constructor(f){this._handler=f,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(f,g,p){this._hitLimit||(this._data+=(0,v.utf32ToString)(f,g,p),this._data.length>i.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(f){let g=!1;if(this._hitLimit)g=!1;else if(f&&(g=this._handler(this._data),g instanceof Promise))return g.then((p=>(this._data="",this._hitLimit=!1,p)));return this._data="",this._hitLimit=!1,g}}},7262:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Params=void 0;const _=2147483647;class i{static fromArray(n){const f=new i;if(!n.length)return f;for(let g=Array.isArray(n[0])?1:0;g<n.length;++g){const p=n[g];if(Array.isArray(p))for(let u=0;u<p.length;++u)f.addSubParam(p[u]);else f.addParam(p)}return f}constructor(n=32,f=32){if(this.maxLength=n,this.maxSubParamsLength=f,f>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(n),this.length=0,this._subParams=new Int32Array(f),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(n),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const n=new i(this.maxLength,this.maxSubParamsLength);return n.params.set(this.params),n.length=this.length,n._subParams.set(this._subParams),n._subParamsLength=this._subParamsLength,n._subParamsIdx.set(this._subParamsIdx),n._rejectDigits=this._rejectDigits,n._rejectSubDigits=this._rejectSubDigits,n._digitIsSub=this._digitIsSub,n}toArray(){const n=[];for(let f=0;f<this.length;++f){n.push(this.params[f]);const g=this._subParamsIdx[f]>>8,p=255&this._subParamsIdx[f];p-g>0&&n.push(Array.prototype.slice.call(this._subParams,g,p))}return n}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(n){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(n<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=n>_?_:n}}addSubParam(n){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(n<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=n>_?_:n,this._subParamsIdx[this.length-1]++}}hasSubParams(n){return(255&this._subParamsIdx[n])-(this._subParamsIdx[n]>>8)>0}getSubParams(n){const f=this._subParamsIdx[n]>>8,g=255&this._subParamsIdx[n];return g-f>0?this._subParams.subarray(f,g):null}getSubParamsAll(){const n={};for(let f=0;f<this.length;++f){const g=this._subParamsIdx[f]>>8,p=255&this._subParamsIdx[f];p-g>0&&(n[f]=this._subParams.slice(g,p))}return n}addDigit(n){let f;if(this._rejectDigits||!(f=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const g=this._digitIsSub?this._subParams:this.params,p=g[f-1];g[f-1]=~p?Math.min(10*p+n,_):n}}t.Params=i},3027:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AddonManager=void 0,t.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let _=this._addons.length-1;_>=0;_--)this._addons[_].instance.dispose()}loadAddon(_,i){const v={instance:i,dispose:i.dispose,isDisposed:!1};this._addons.push(v),i.dispose=()=>this._wrappedAddonDispose(v),i.activate(_)}_wrappedAddonDispose(_){if(_.isDisposed)return;let i=-1;for(let v=0;v<this._addons.length;v++)if(this._addons[v]===_){i=v;break}if(i===-1)throw new Error("Could not dispose an addon that has not been loaded");_.isDisposed=!0,_.dispose.apply(_.instance),this._addons.splice(i,1)}}},3235:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferApiView=void 0;const i=_(793),v=_(3055);t.BufferApiView=class{constructor(n,f){this._buffer=n,this.type=f}init(n){return this._buffer=n,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(n){const f=this._buffer.lines.get(n);if(f)return new i.BufferLineApiView(f)}getNullCell(){return new v.CellData}}},793:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferLineApiView=void 0;const i=_(3055);t.BufferLineApiView=class{constructor(v){this._line=v}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(v,n){if(!(v<0||v>=this._line.length))return n?(this._line.loadCell(v,n),n):this._line.loadCell(v,new i.CellData)}translateToString(v,n,f){return this._line.translateToString(v,n,f)}}},5101:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferNamespaceApi=void 0;const i=_(3235),v=_(7150),n=_(802);class f extends v.Disposable{constructor(p){super(),this._core=p,this._onBufferChange=this._register(new n.Emitter),this.onBufferChange=this._onBufferChange.event,this._normal=new i.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new i.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}t.BufferNamespaceApi=f},6097:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ParserApi=void 0,t.ParserApi=class{constructor(_){this._core=_}registerCsiHandler(_,i){return this._core.registerCsiHandler(_,(v=>i(v.toArray())))}addCsiHandler(_,i){return this.registerCsiHandler(_,i)}registerDcsHandler(_,i){return this._core.registerDcsHandler(_,((v,n)=>i(v,n.toArray())))}addDcsHandler(_,i){return this.registerDcsHandler(_,i)}registerEscHandler(_,i){return this._core.registerEscHandler(_,i)}addEscHandler(_,i){return this.registerEscHandler(_,i)}registerOscHandler(_,i){return this._core.registerOscHandler(_,i)}addOscHandler(_,i){return this.registerOscHandler(_,i)}}},4335:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeApi=void 0,t.UnicodeApi=class{constructor(_){this._core=_}register(_){this._core.unicodeService.register(_)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(_){this._core.unicodeService.activeVersion=_}}},9640:function(K,t,_){var i=this&&this.__decorate||function(r,h,s,e){var l,o=arguments.length,d=o<3?h:e===null?e=Object.getOwnPropertyDescriptor(h,s):e;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")d=Reflect.decorate(r,h,s,e);else for(var c=r.length-1;c>=0;c--)(l=r[c])&&(d=(o<3?l(d):o>3?l(h,s,d):l(h,s))||d);return o>3&&d&&Object.defineProperty(h,s,d),d},v=this&&this.__param||function(r,h){return function(s,e){h(s,e,r)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferService=t.MINIMUM_ROWS=t.MINIMUM_COLS=void 0;const n=_(7150),f=_(4097),g=_(6501),p=_(802);t.MINIMUM_COLS=2,t.MINIMUM_ROWS=1;let u=class extends n.Disposable{get buffer(){return this.buffers.active}constructor(r){super(),this.isUserScrolling=!1,this._onResize=this._register(new p.Emitter),this.onResize=this._onResize.event,this._onScroll=this._register(new p.Emitter),this.onScroll=this._onScroll.event,this.cols=Math.max(r.rawOptions.cols||0,t.MINIMUM_COLS),this.rows=Math.max(r.rawOptions.rows||0,t.MINIMUM_ROWS),this.buffers=this._register(new f.BufferSet(r,this)),this._register(this.buffers.onBufferActivate((h=>{this._onScroll.fire(h.activeBuffer.ydisp)})))}resize(r,h){const s=this.cols!==r,e=this.rows!==h;this.cols=r,this.rows=h,this.buffers.resize(r,h),this._onResize.fire({cols:r,rows:h,colsChanged:s,rowsChanged:e})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(r,h=!1){const s=this.buffer;let e;e=this._cachedBlankLine,e&&e.length===this.cols&&e.getFg(0)===r.fg&&e.getBg(0)===r.bg||(e=s.getBlankLine(r,h),this._cachedBlankLine=e),e.isWrapped=h;const l=s.ybase+s.scrollTop,o=s.ybase+s.scrollBottom;if(s.scrollTop===0){const d=s.lines.isFull;o===s.lines.length-1?d?s.lines.recycle().copyFrom(e):s.lines.push(e.clone()):s.lines.splice(o+1,0,e.clone()),d?this.isUserScrolling&&(s.ydisp=Math.max(s.ydisp-1,0)):(s.ybase++,this.isUserScrolling||s.ydisp++)}else{const d=o-l+1;s.lines.shiftElements(l+1,d-1,-1),s.lines.set(o,e.clone())}this.isUserScrolling||(s.ydisp=s.ybase),this._onScroll.fire(s.ydisp)}scrollLines(r,h){const s=this.buffer;if(r<0){if(s.ydisp===0)return;this.isUserScrolling=!0}else r+s.ydisp>=s.ybase&&(this.isUserScrolling=!1);const e=s.ydisp;s.ydisp=Math.max(Math.min(s.ydisp+r,s.ybase),0),e!==s.ydisp&&(h||this._onScroll.fire(s.ydisp))}};t.BufferService=u,t.BufferService=u=i([v(0,g.IOptionsService)],u)},5746:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CharsetService=void 0,t.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(_){this.glevel=_,this.charset=this._charsets[_]}setgCharset(_,i){this._charsets[_]=i,this.glevel===_&&(this.charset=i)}}},7792:function(K,t,_){var i=this&&this.__decorate||function(e,l,o,d){var c,a=arguments.length,m=a<3?l:d===null?d=Object.getOwnPropertyDescriptor(l,o):d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")m=Reflect.decorate(e,l,o,d);else for(var b=e.length-1;b>=0;b--)(c=e[b])&&(m=(a<3?c(m):a>3?c(l,o,m):c(l,o))||m);return a>3&&m&&Object.defineProperty(l,o,m),m},v=this&&this.__param||function(e,l){return function(o,d){l(o,d,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreMouseService=void 0;const n=_(6501),f=_(7150),g=_(802),p={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button!==4&&e.action===1&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function u(e,l){let o=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(o|=64,o|=e.action):(o|=3&e.button,4&e.button&&(o|=64),8&e.button&&(o|=128),e.action===32?o|=32:e.action!==0||l||(o|=3)),o}const r=String.fromCharCode,h={DEFAULT:e=>{const l=[u(e,!1)+32,e.col+32,e.row+32];return l[0]>255||l[1]>255||l[2]>255?"":`\x1B[M${r(l[0])}${r(l[1])}${r(l[2])}`},SGR:e=>{const l=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${u(e,!0)};${e.col};${e.row}${l}`},SGR_PIXELS:e=>{const l=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${u(e,!0)};${e.x};${e.y}${l}`}};let s=class extends f.Disposable{constructor(e,l,o){super(),this._bufferService=e,this._coreService=l,this._optionsService=o,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new g.Emitter),this.onProtocolChange=this._onProtocolChange.event;for(const d of Object.keys(p))this.addProtocol(d,p[d]);for(const d of Object.keys(h))this.addEncoding(d,h[d]);this.reset()}addProtocol(e,l){this._protocols[e]=l}addEncoding(e,l){this._encodings[e]=l}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,l,o){if(e.deltaY===0||e.shiftKey||l===void 0||o===void 0)return 0;const d=l/o;let c=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(c/=d+0,Math.abs(e.deltaY)<50&&(c*=.3),this._wheelPartialScroll+=c,c=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(c*=this._bufferService.rows),c}_applyScrollModifier(e,l){return l.altKey||l.ctrlKey||l.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;const l=this._encodings[this._activeEncoding](e);return l&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(l):this._coreService.triggerDataEvent(l,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,l,o){if(o){if(e.x!==l.x||e.y!==l.y)return!1}else if(e.col!==l.col||e.row!==l.row)return!1;return e.button===l.button&&e.action===l.action&&e.ctrl===l.ctrl&&e.alt===l.alt&&e.shift===l.shift}};t.CoreMouseService=s,t.CoreMouseService=s=i([v(0,n.IBufferService),v(1,n.ICoreService),v(2,n.IOptionsService)],s)},4071:function(K,t,_){var i=this&&this.__decorate||function(s,e,l,o){var d,c=arguments.length,a=c<3?e:o===null?o=Object.getOwnPropertyDescriptor(e,l):o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(s,e,l,o);else for(var m=s.length-1;m>=0;m--)(d=s[m])&&(a=(c<3?d(a):c>3?d(e,l,a):d(e,l))||a);return c>3&&a&&Object.defineProperty(e,l,a),a},v=this&&this.__param||function(s,e){return function(l,o){e(l,o,s)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreService=void 0;const n=_(7453),f=_(7150),g=_(6501),p=_(802),u=Object.freeze({insertMode:!1}),r=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0});let h=class extends f.Disposable{constructor(s,e,l){super(),this._bufferService=s,this._logService=e,this._optionsService=l,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new p.Emitter),this.onData=this._onData.event,this._onUserInput=this._register(new p.Emitter),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new p.Emitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new p.Emitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,n.clone)(u),this.decPrivateModes=(0,n.clone)(r)}reset(){this.modes=(0,n.clone)(u),this.decPrivateModes=(0,n.clone)(r)}triggerDataEvent(s,e=!1){if(this._optionsService.rawOptions.disableStdin)return;const l=this._bufferService.buffer;e&&this._optionsService.rawOptions.scrollOnUserInput&&l.ybase!==l.ydisp&&this._onRequestScrollToBottom.fire(),e&&this._onUserInput.fire(),this._logService.debug(`sending data "${s}"`),this._logService.trace("sending data (codes)",(()=>s.split("").map((o=>o.charCodeAt(0))))),this._onData.fire(s)}triggerBinaryEvent(s){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${s}"`),this._logService.trace("sending binary (codes)",(()=>s.split("").map((e=>e.charCodeAt(0))))),this._onBinary.fire(s))}};t.CoreService=h,t.CoreService=h=i([v(0,g.IBufferService),v(1,g.ILogService),v(2,g.IOptionsService)],h)},4720:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DecorationService=void 0;const i=_(4103),v=_(7150),n=_(3087),f=_(802);let g=0,p=0;class u extends v.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new n.SortedList((s=>s==null?void 0:s.marker.line)),this._onDecorationRegistered=this._register(new f.Emitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new f.Emitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register((0,v.toDisposable)((()=>this.reset())))}registerDecoration(s){if(s.marker.isDisposed)return;const e=new r(s);if(e){const l=e.marker.onDispose((()=>e.dispose())),o=e.onDispose((()=>{o.dispose(),e&&(this._decorations.delete(e)&&this._onDecorationRemoved.fire(e),l.dispose())}));this._decorations.insert(e),this._onDecorationRegistered.fire(e)}return e}reset(){for(const s of this._decorations.values())s.dispose();this._decorations.clear()}*getDecorationsAtCell(s,e,l){let o=0,d=0;for(const c of this._decorations.getKeyIterator(e))o=c.options.x??0,d=o+(c.options.width??1),s>=o&&s<d&&(!l||(c.options.layer??"bottom")===l)&&(yield c)}forEachDecorationAtCell(s,e,l,o){this._decorations.forEachByKey(e,(d=>{g=d.options.x??0,p=g+(d.options.width??1),s>=g&&s<p&&(!l||(d.options.layer??"bottom")===l)&&o(d)}))}}t.DecorationService=u;class r extends v.DisposableStore{get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=i.css.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=i.css.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}constructor(s){super(),this.options=s,this.onRenderEmitter=this.add(new f.Emitter),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new f.Emitter),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=s.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}dispose(){this._onDispose.fire(),super.dispose()}}},6025:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InstantiationService=t.ServiceCollection=void 0;const i=_(6501),v=_(6201);class n{constructor(...g){this._entries=new Map;for(const[p,u]of g)this.set(p,u)}set(g,p){const u=this._entries.get(g);return this._entries.set(g,p),u}forEach(g){for(const[p,u]of this._entries.entries())g(p,u)}has(g){return this._entries.has(g)}get(g){return this._entries.get(g)}}t.ServiceCollection=n,t.InstantiationService=class{constructor(){this._services=new n,this._services.set(i.IInstantiationService,this)}setService(f,g){this._services.set(f,g)}getService(f){return this._services.get(f)}createInstance(f,...g){const p=(0,v.getServiceDependencies)(f).sort(((h,s)=>h.index-s.index)),u=[];for(const h of p){const s=this._services.get(h.id);if(!s)throw new Error(`[createInstance] ${f.name} depends on UNKNOWN service ${h.id._id}.`);u.push(s)}const r=p.length>0?p[0].index:g.length;if(g.length!==r)throw new Error(`[createInstance] First service dependency of ${f.name} at position ${r+1} conflicts with ${g.length} static arguments`);return new f(...g,...u)}}},7276:function(K,t,_){var i=this&&this.__decorate||function(r,h,s,e){var l,o=arguments.length,d=o<3?h:e===null?e=Object.getOwnPropertyDescriptor(h,s):e;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")d=Reflect.decorate(r,h,s,e);else for(var c=r.length-1;c>=0;c--)(l=r[c])&&(d=(o<3?l(d):o>3?l(h,s,d):l(h,s))||d);return o>3&&d&&Object.defineProperty(h,s,d),d},v=this&&this.__param||function(r,h){return function(s,e){h(s,e,r)}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogService=void 0,t.setTraceLogger=function(r){p=r},t.traceCall=function(r,h,s){if(typeof s.value!="function")throw new Error("not supported");const e=s.value;s.value=function(...l){if(p.logLevel!==f.LogLevelEnum.TRACE)return e.apply(this,l);p.trace(`GlyphRenderer#${e.name}(${l.map((d=>JSON.stringify(d))).join(", ")})`);const o=e.apply(this,l);return p.trace(`GlyphRenderer#${e.name} return`,o),o}};const n=_(7150),f=_(6501),g={trace:f.LogLevelEnum.TRACE,debug:f.LogLevelEnum.DEBUG,info:f.LogLevelEnum.INFO,warn:f.LogLevelEnum.WARN,error:f.LogLevelEnum.ERROR,off:f.LogLevelEnum.OFF};let p,u=class extends n.Disposable{get logLevel(){return this._logLevel}constructor(r){super(),this._optionsService=r,this._logLevel=f.LogLevelEnum.OFF,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),p=this}_updateLogLevel(){this._logLevel=g[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(r){for(let h=0;h<r.length;h++)typeof r[h]=="function"&&(r[h]=r[h]())}_log(r,h,s){this._evalLazyOptionalParams(s),r.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+h,...s)}trace(r,...h){var s;this._logLevel<=f.LogLevelEnum.TRACE&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.trace.bind(this._optionsService.options.logger))??console.log,r,h)}debug(r,...h){var s;this._logLevel<=f.LogLevelEnum.DEBUG&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.debug.bind(this._optionsService.options.logger))??console.log,r,h)}info(r,...h){var s;this._logLevel<=f.LogLevelEnum.INFO&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.info.bind(this._optionsService.options.logger))??console.info,r,h)}warn(r,...h){var s;this._logLevel<=f.LogLevelEnum.WARN&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.warn.bind(this._optionsService.options.logger))??console.warn,r,h)}error(r,...h){var s;this._logLevel<=f.LogLevelEnum.ERROR&&this._log(((s=this._optionsService.options.logger)==null?void 0:s.error.bind(this._optionsService.options.logger))??console.error,r,h)}};t.LogService=u,t.LogService=u=i([v(0,f.IOptionsService)],u)},56:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionsService=t.DEFAULT_OPTIONS=void 0;const i=_(7150),v=_(701),n=_(802);t.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:v.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}};const f=["normal","bold","100","200","300","400","500","600","700","800","900"];class g extends i.Disposable{constructor(u){super(),this._onOptionChange=this._register(new n.Emitter),this.onOptionChange=this._onOptionChange.event;const r={...t.DEFAULT_OPTIONS};for(const h in u)if(h in r)try{const s=u[h];r[h]=this._sanitizeAndValidateOption(h,s)}catch(s){console.error(s)}this.rawOptions=r,this.options={...r},this._setupOptions(),this._register((0,i.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(u,r){return this.onOptionChange((h=>{h===u&&r(this.rawOptions[u])}))}onMultipleOptionChange(u,r){return this.onOptionChange((h=>{u.indexOf(h)!==-1&&r()}))}_setupOptions(){const u=h=>{if(!(h in t.DEFAULT_OPTIONS))throw new Error(`No option with key "${h}"`);return this.rawOptions[h]},r=(h,s)=>{if(!(h in t.DEFAULT_OPTIONS))throw new Error(`No option with key "${h}"`);s=this._sanitizeAndValidateOption(h,s),this.rawOptions[h]!==s&&(this.rawOptions[h]=s,this._onOptionChange.fire(h))};for(const h in this.rawOptions){const s={get:u.bind(this,h),set:r.bind(this,h)};Object.defineProperty(this.options,h,s)}}_sanitizeAndValidateOption(u,r){switch(u){case"cursorStyle":if(r||(r=t.DEFAULT_OPTIONS[u]),!(function(h){return h==="block"||h==="underline"||h==="bar"})(r))throw new Error(`"${r}" is not a valid value for ${u}`);break;case"wordSeparator":r||(r=t.DEFAULT_OPTIONS[u]);break;case"fontWeight":case"fontWeightBold":if(typeof r=="number"&&1<=r&&r<=1e3)break;r=f.includes(r)?r:t.DEFAULT_OPTIONS[u];break;case"cursorWidth":r=Math.floor(r);case"lineHeight":case"tabStopWidth":if(r<1)throw new Error(`${u} cannot be less than 1, value: ${r}`);break;case"minimumContrastRatio":r=Math.max(1,Math.min(21,Math.round(10*r)/10));break;case"scrollback":if((r=Math.min(r,4294967295))<0)throw new Error(`${u} cannot be less than 0, value: ${r}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(r<=0)throw new Error(`${u} cannot be less than or equal to 0, value: ${r}`);break;case"rows":case"cols":if(!r&&r!==0)throw new Error(`${u} must be numeric, value: ${r}`);break;case"windowsPty":r=r??{}}return r}}t.OptionsService=g},8811:function(K,t,_){var i=this&&this.__decorate||function(g,p,u,r){var h,s=arguments.length,e=s<3?p:r===null?r=Object.getOwnPropertyDescriptor(p,u):r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")e=Reflect.decorate(g,p,u,r);else for(var l=g.length-1;l>=0;l--)(h=g[l])&&(e=(s<3?h(e):s>3?h(p,u,e):h(p,u))||e);return s>3&&e&&Object.defineProperty(p,u,e),e},v=this&&this.__param||function(g,p){return function(u,r){p(u,r,g)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OscLinkService=void 0;const n=_(6501);let f=class{constructor(g){this._bufferService=g,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(g){const p=this._bufferService.buffer;if(g.id===void 0){const l=p.addMarker(p.ybase+p.y),o={data:g,id:this._nextId++,lines:[l]};return l.onDispose((()=>this._removeMarkerFromLink(o,l))),this._dataByLinkId.set(o.id,o),o.id}const u=g,r=this._getEntryIdKey(u),h=this._entriesWithId.get(r);if(h)return this.addLineToLink(h.id,p.ybase+p.y),h.id;const s=p.addMarker(p.ybase+p.y),e={id:this._nextId++,key:this._getEntryIdKey(u),data:u,lines:[s]};return s.onDispose((()=>this._removeMarkerFromLink(e,s))),this._entriesWithId.set(e.key,e),this._dataByLinkId.set(e.id,e),e.id}addLineToLink(g,p){const u=this._dataByLinkId.get(g);if(u&&u.lines.every((r=>r.line!==p))){const r=this._bufferService.buffer.addMarker(p);u.lines.push(r),r.onDispose((()=>this._removeMarkerFromLink(u,r)))}}getLinkData(g){var p;return(p=this._dataByLinkId.get(g))==null?void 0:p.data}_getEntryIdKey(g){return`${g.id};;${g.uri}`}_removeMarkerFromLink(g,p){const u=g.lines.indexOf(p);u!==-1&&(g.lines.splice(u,1),g.lines.length===0&&(g.data.id!==void 0&&this._entriesWithId.delete(g.key),this._dataByLinkId.delete(g.id)))}};t.OscLinkService=f,t.OscLinkService=f=i([v(0,n.IBufferService)],f)},6201:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.serviceRegistry=void 0,t.getServiceDependencies=function(v){return v[i]||[]},t.createDecorator=function(v){if(t.serviceRegistry.has(v))return t.serviceRegistry.get(v);const n=function(f,g,p){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(u,r,h){r[_]===r?r[i].push({id:u,index:h}):(r[i]=[{id:u,index:h}],r[_]=r)})(n,f,p)};return n._id=v,t.serviceRegistry.set(v,n),n};const _="di$target",i="di$dependencies";t.serviceRegistry=new Map},6501:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;const i=_(6201);var v;t.IBufferService=(0,i.createDecorator)("BufferService"),t.ICoreMouseService=(0,i.createDecorator)("CoreMouseService"),t.ICoreService=(0,i.createDecorator)("CoreService"),t.ICharsetService=(0,i.createDecorator)("CharsetService"),t.IInstantiationService=(0,i.createDecorator)("InstantiationService"),(function(n){n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.OFF=5]="OFF"})(v||(t.LogLevelEnum=v={})),t.ILogService=(0,i.createDecorator)("LogService"),t.IOptionsService=(0,i.createDecorator)("OptionsService"),t.IOscLinkService=(0,i.createDecorator)("OscLinkService"),t.IUnicodeService=(0,i.createDecorator)("UnicodeService"),t.IDecorationService=(0,i.createDecorator)("DecorationService")},6415:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeService=void 0;const i=_(7428),v=_(802);class n{static extractShouldJoin(g){return!!(1&g)}static extractWidth(g){return g>>1&3}static extractCharKind(g){return g>>3}static createPropertyValue(g,p,u=!1){return(16777215&g)<<3|(3&p)<<1|(u?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new v.Emitter,this.onChange=this._onChange.event;const g=new i.UnicodeV6;this.register(g),this._active=g.version,this._activeProvider=g}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(g){if(!this._providers[g])throw new Error(`unknown Unicode version "${g}"`);this._active=g,this._activeProvider=this._providers[g],this._onChange.fire(g)}register(g){this._providers[g.version]=g}wcwidth(g){return this._activeProvider.wcwidth(g)}getStringCellWidth(g){let p=0,u=0;const r=g.length;for(let h=0;h<r;++h){let s=g.charCodeAt(h);if(55296<=s&&s<=56319){if(++h>=r)return p+this.wcwidth(s);const o=g.charCodeAt(h);56320<=o&&o<=57343?s=1024*(s-55296)+o-56320+65536:p+=this.wcwidth(o)}const e=this.charProperties(s,u);let l=n.extractWidth(e);n.extractShouldJoin(e)&&(l-=n.extractWidth(u)),p+=l,u=e}return p}charProperties(g,p){return this._activeProvider.charProperties(g,p)}}t.UnicodeService=n},4333:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isAndroid=t.isElectron=t.isWebkitWebView=t.isSafari=t.isChrome=t.isWebKit=t.isFirefox=t.onDidChangeFullscreen=t.onDidChangeZoomLevel=void 0,t.addMatchMediaChangeListener=f,t.setZoomLevel=function(r,h){n.INSTANCE.setZoomLevel(r,h)},t.getZoomLevel=function(r){return n.INSTANCE.getZoomLevel(r)},t.getZoomFactor=function(r){return n.INSTANCE.getZoomFactor(r)},t.setZoomFactor=function(r,h){n.INSTANCE.setZoomFactor(r,h)},t.setFullscreen=function(r,h){n.INSTANCE.setFullscreen(r,h)},t.isFullscreen=function(r){return n.INSTANCE.isFullscreen(r)},t.isStandalone=function(){return p},t.isWCOEnabled=function(){var r;return(r=navigator==null?void 0:navigator.windowControlsOverlay)==null?void 0:r.visible},t.getWCOBoundingRect=function(){var r;return(r=navigator==null?void 0:navigator.windowControlsOverlay)==null?void 0:r.getTitlebarAreaRect()};const i=_(4693),v=_(802),u=class u{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new v.Emitter,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new v.Emitter,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(h){return this.mapWindowIdToZoomLevel.get(this.getWindowId(h))??0}setZoomLevel(h,s){if(this.getZoomLevel(s)===h)return;const e=this.getWindowId(s);this.mapWindowIdToZoomLevel.set(e,h),this._onDidChangeZoomLevel.fire(e)}getZoomFactor(h){return this.mapWindowIdToZoomFactor.get(this.getWindowId(h))??1}setZoomFactor(h,s){this.mapWindowIdToZoomFactor.set(this.getWindowId(s),h)}setFullscreen(h,s){if(this.isFullscreen(s)===h)return;const e=this.getWindowId(s);this.mapWindowIdToFullScreen.set(e,h),this._onDidChangeFullscreen.fire(e)}isFullscreen(h){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(h))}getWindowId(h){return h.vscodeWindowId}};u.INSTANCE=new u;let n=u;function f(r,h,s){typeof h=="string"&&(h=r.matchMedia(h)),h.addEventListener("change",s)}t.onDidChangeZoomLevel=n.INSTANCE.onDidChangeZoomLevel,t.onDidChangeFullscreen=n.INSTANCE.onDidChangeFullscreen;const g=typeof navigator=="object"?navigator.userAgent:"";t.isFirefox=g.indexOf("Firefox")>=0,t.isWebKit=g.indexOf("AppleWebKit")>=0,t.isChrome=g.indexOf("Chrome")>=0,t.isSafari=!t.isChrome&&g.indexOf("Safari")>=0,t.isWebkitWebView=!t.isChrome&&!t.isSafari&&t.isWebKit,t.isElectron=g.indexOf("Electron/")>=0,t.isAndroid=g.indexOf("Android")>=0;let p=!1;if(typeof i.mainWindow.matchMedia=="function"){const r=i.mainWindow.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),h=i.mainWindow.matchMedia("(display-mode: fullscreen)");p=r.matches,f(i.mainWindow,r,(({matches:s})=>{p&&h.matches||(p=s)}))}},7745:function(K,t,_){var i=this&&this.__createBinding||(Object.create?function(h,s,e,l){l===void 0&&(l=e);var o=Object.getOwnPropertyDescriptor(s,e);o&&!("get"in o?!s.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return s[e]}}),Object.defineProperty(h,l,o)}:function(h,s,e,l){l===void 0&&(l=e),h[l]=s[e]}),v=this&&this.__setModuleDefault||(Object.create?function(h,s){Object.defineProperty(h,"default",{enumerable:!0,value:s})}:function(h,s){h.default=s}),n=this&&this.__importStar||function(h){if(h&&h.__esModule)return h;var s={};if(h!=null)for(var e in h)e!=="default"&&Object.prototype.hasOwnProperty.call(h,e)&&i(s,h,e);return v(s,h),s};Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserFeatures=t.KeyboardSupport=void 0;const f=n(_(4333)),g=_(4693),p=n(_(8163));var u;(function(h){h[h.Always=0]="Always",h[h.FullScreen=1]="FullScreen",h[h.None=2]="None"})(u||(t.KeyboardSupport=u={}));const r=typeof navigator=="object"?navigator:{};t.BrowserFeatures={clipboard:{writeText:p.isNative||document.queryCommandSupported&&document.queryCommandSupported("copy")||!!(r&&r.clipboard&&r.clipboard.writeText),readText:p.isNative||!!(r&&r.clipboard&&r.clipboard.readText)},keyboard:p.isNative||f.isStandalone()?u.Always:r.keyboard||f.isSafari?u.FullScreen:u.None,touch:"ontouchstart"in g.mainWindow||r.maxTouchPoints>0,pointerEvents:g.mainWindow.PointerEvent&&("ontouchstart"in g.mainWindow||navigator.maxTouchPoints>0)}},7093:function(K,t,_){var i,v=this&&this.__createBinding||(Object.create?function(L,O,x,U){U===void 0&&(U=x);var z=Object.getOwnPropertyDescriptor(O,x);z&&!("get"in z?!O.__esModule:z.writable||z.configurable)||(z={enumerable:!0,get:function(){return O[x]}}),Object.defineProperty(L,U,z)}:function(L,O,x,U){U===void 0&&(U=x),L[U]=O[x]}),n=this&&this.__setModuleDefault||(Object.create?function(L,O){Object.defineProperty(L,"default",{enumerable:!0,value:O})}:function(L,O){L.default=O}),f=this&&this.__importStar||function(L){if(L&&L.__esModule)return L;var O={};if(L!=null)for(var x in L)x!=="default"&&Object.prototype.hasOwnProperty.call(L,x)&&v(O,L,x);return n(O,L),O};Object.defineProperty(t,"__esModule",{value:!0}),t.SafeTriangle=t.DragAndDropObserver=t.ModifierKeyEmitter=t.DetectedFullscreenMode=t.Namespace=t.EventHelper=t.EventType=t.sharedMutationObserver=t.Dimension=t.WindowIntervalTimer=t.scheduleAtNextAnimationFrame=t.runAtThisOrScheduleAtNextAnimationFrame=t.WindowIdleValue=t.addStandardDisposableGenericMouseUpListener=t.addStandardDisposableGenericMouseDownListener=t.addStandardDisposableListener=t.onDidUnregisterWindow=t.onWillUnregisterWindow=t.onDidRegisterWindow=t.hasWindow=t.getWindowById=t.getWindowId=t.getWindowsCount=t.getWindows=t.getDocument=t.getWindow=t.registerWindow=void 0,t.clearNode=function(L){for(;L.firstChild;)L.firstChild.remove()},t.clearNodeRecursively=function L(O){for(;O.firstChild;){const x=O.firstChild;x.remove(),L(x)}},t.addDisposableListener=R,t.addDisposableGenericMouseDownListener=C,t.addDisposableGenericMouseMoveListener=function(L,O,x){return R(L,d.isIOS&&p.BrowserFeatures.pointerEvents?t.EventType.POINTER_MOVE:t.EventType.MOUSE_MOVE,O,x)},t.addDisposableGenericMouseUpListener=E,t.runWhenWindowIdle=function(L,O,x){return(0,h._runWhenIdle)(L,O,x)},t.disposableWindowInterval=function(L,O,x,U){let z=0;const G=L.setInterval((()=>{z++,(typeof U=="number"&&z>=U||O()===!0)&&q.dispose()}),x),q=(0,o.toDisposable)((()=>{L.clearInterval(G)}));return q},t.measure=function(L,O){return(0,t.scheduleAtNextAnimationFrame)(L,O,1e4)},t.modify=function(L,O){return(0,t.scheduleAtNextAnimationFrame)(L,O,-1e4)},t.addDisposableThrottledListener=function(L,O,x,U,z){return new w(L,O,x,U,z)},t.getComputedStyle=y,t.getClientArea=function L(O,x){const U=(0,t.getWindow)(O),z=U.document;if(O!==z.body)return new D(O.clientWidth,O.clientHeight);if(d.isIOS&&(U!=null&&U.visualViewport))return new D(U.visualViewport.width,U.visualViewport.height);if(U!=null&&U.innerWidth&&U.innerHeight)return new D(U.innerWidth,U.innerHeight);if(z.body&&z.body.clientWidth&&z.body.clientHeight)return new D(z.body.clientWidth,z.body.clientHeight);if(z.documentElement&&z.documentElement.clientWidth&&z.documentElement.clientHeight)return new D(z.documentElement.clientWidth,z.documentElement.clientHeight);if(x)return L(x);throw new Error("Unable to figure out browser width and height")},t.getTopLeftOffset=M,t.size=function(L,O,x){typeof O=="number"&&(L.style.width=`${O}px`),typeof x=="number"&&(L.style.height=`${x}px`)},t.position=function(L,O,x,U,z,G="absolute"){typeof O=="number"&&(L.style.top=`${O}px`),typeof x=="number"&&(L.style.right=`${x}px`),typeof U=="number"&&(L.style.bottom=`${U}px`),typeof z=="number"&&(L.style.left=`${z}px`),L.style.position=G},t.getDomNodePagePosition=function(L){const O=L.getBoundingClientRect(),x=(0,t.getWindow)(L);return{left:O.left+x.scrollX,top:O.top+x.scrollY,width:O.width,height:O.height}},t.getDomNodeZoomLevel=function(L){let O=L,x=1;do{const U=y(O).zoom;U!=null&&U!=="1"&&(x*=U),O=O.parentElement}while(O!==null&&O!==O.ownerDocument.documentElement);return x},t.getTotalWidth=I,t.getContentWidth=function(L){const O=S.getBorderLeftWidth(L)+S.getBorderRightWidth(L),x=S.getPaddingLeft(L)+S.getPaddingRight(L);return L.offsetWidth-O-x},t.getTotalScrollWidth=F,t.getContentHeight=function(L){const O=S.getBorderTopWidth(L)+S.getBorderBottomWidth(L),x=S.getPaddingTop(L)+S.getPaddingBottom(L);return L.offsetHeight-O-x},t.getTotalHeight=function(L){const O=S.getMarginTop(L)+S.getMarginBottom(L);return L.offsetHeight+O},t.getLargestChildWidth=function(L,O){const x=O.map((U=>Math.max(F(U),I(U))+(function(z,G){if(z===null)return 0;const q=M(z),Y=M(G);return q.left-Y.left})(U,L)||0));return Math.max(...x)},t.isAncestor=H,t.setParentFlowTo=function(L,O){L.dataset[B]=O.id},t.isAncestorUsingFlowTo=function(L,O){let x=L;for(;x;){if(x===O)return!0;if(ce(x)){const U=k(x);if(U){x=U;continue}}x=x.parentNode}return!1},t.findParentWithClass=j,t.hasParentWithClass=function(L,O,x){return!!j(L,O,x)},t.isShadowRoot=$,t.isInShadowDOM=function(L){return!!X(L)},t.getShadowRoot=X,t.getActiveElement=V,t.isActiveElement=function(L){return V()===L},t.isAncestorOfActiveElement=function(L){return H(V(),L)},t.isActiveDocument=function(L){return L.ownerDocument===Z()},t.getActiveDocument=Z,t.getActiveWindow=function(){var O;return((O=Z().defaultView)==null?void 0:O.window)??a.mainWindow},t.isGlobalStylesheet=function(L){return se.has(L)},t.createStyleSheet2=function(){return new te},t.createStyleSheet=re,t.cloneGlobalStylesheets=function(L){const O=new o.DisposableStore;for(const[x,U]of se)O.add(ne(x,U,L));return O},t.createMetaElement=function(L=a.mainWindow.document.head){return oe("meta",L)},t.createLinkElement=function(L=a.mainWindow.document.head){return oe("link",L)},t.createCSSRule=function L(O,x,U=ee()){var z;if(U&&x){(z=U.sheet)==null||z.insertRule(`${O} {${x}}`,0);for(const G of se.get(U)??[])L(O,x,G)}},t.removeCSSRulesContainingSelector=function L(O,x=ee()){var G;if(!x)return;const U=ue(x),z=[];for(let q=0;q<U.length;q++){const Y=U[q];Ae(Y)&&Y.selectorText.indexOf(O)!==-1&&z.push(q)}for(let q=z.length-1;q>=0;q--)(G=x.sheet)==null||G.deleteRule(z[q]);for(const q of se.get(x)??[])L(O,q)},t.isHTMLElement=ce,t.isHTMLAnchorElement=function(L){return L instanceof HTMLAnchorElement||L instanceof(0,t.getWindow)(L).HTMLAnchorElement},t.isHTMLSpanElement=function(L){return L instanceof HTMLSpanElement||L instanceof(0,t.getWindow)(L).HTMLSpanElement},t.isHTMLTextAreaElement=function(L){return L instanceof HTMLTextAreaElement||L instanceof(0,t.getWindow)(L).HTMLTextAreaElement},t.isHTMLInputElement=function(L){return L instanceof HTMLInputElement||L instanceof(0,t.getWindow)(L).HTMLInputElement},t.isHTMLButtonElement=function(L){return L instanceof HTMLButtonElement||L instanceof(0,t.getWindow)(L).HTMLButtonElement},t.isHTMLDivElement=function(L){return L instanceof HTMLDivElement||L instanceof(0,t.getWindow)(L).HTMLDivElement},t.isSVGElement=function(L){return L instanceof SVGElement||L instanceof(0,t.getWindow)(L).SVGElement},t.isMouseEvent=function(L){return L instanceof MouseEvent||L instanceof(0,t.getWindow)(L).MouseEvent},t.isKeyboardEvent=function(L){return L instanceof KeyboardEvent||L instanceof(0,t.getWindow)(L).KeyboardEvent},t.isPointerEvent=function(L){return L instanceof PointerEvent||L instanceof(0,t.getWindow)(L).PointerEvent},t.isDragEvent=function(L){return L instanceof DragEvent||L instanceof(0,t.getWindow)(L).DragEvent},t.isEventLike=function(L){const O=L;return!(!O||typeof O.preventDefault!="function"||typeof O.stopPropagation!="function")},t.saveParentsScrollTop=function(L){const O=[];for(let x=0;L&&L.nodeType===L.ELEMENT_NODE;x++)O[x]=L.scrollTop,L=L.parentNode;return O},t.restoreParentsScrollTop=function(L,O){for(let x=0;L&&L.nodeType===L.ELEMENT_NODE;x++)L.scrollTop!==O[x]&&(L.scrollTop=O[x]),L=L.parentNode},t.trackFocus=function(L){return new Se(L)},t.after=function(L,O){return L.after(O),O},t.append=Ce,t.prepend=function(L,O){return L.insertBefore(O,L.firstChild),O},t.reset=function(L,...O){L.innerText="",Ce(L,...O)},t.$=be,t.join=function(L,O){const x=[];return L.forEach(((U,z)=>{z>0&&(O instanceof Node?x.push(O.cloneNode()):x.push(document.createTextNode(O))),x.push(U)})),x},t.setVisibility=function(L,...O){L?Le(...O):fe(...O)},t.show=Le,t.hide=fe,t.removeTabIndexAndUpdateFocus=function(L){if(L&&L.hasAttribute("tabIndex")){if(L.ownerDocument.activeElement===L){const O=(function(x){for(;x&&x.nodeType===x.ELEMENT_NODE;){if(ce(x)&&x.hasAttribute("tabIndex"))return x;x=x.parentNode}return null})(L.parentElement);O==null||O.focus()}L.removeAttribute("tabindex")}},t.finalHandler=function(L){return O=>{O.preventDefault(),O.stopPropagation(),L(O)}},t.domContentLoaded=function(L){return new Promise((O=>{if(L.document.readyState==="complete"||L.document&&L.document.body!==null)O(void 0);else{const x=()=>{L.window.removeEventListener("DOMContentLoaded",x,!1),O()};L.window.addEventListener("DOMContentLoaded",x,!1)}}))},t.computeScreenAwareSize=function(L,O){const x=L.devicePixelRatio*O;return Math.max(1,Math.floor(x))/L.devicePixelRatio},t.windowOpenNoOpener=function(L){a.mainWindow.open(L,"_blank","noopener")},t.windowOpenPopup=function(L){const O=Math.floor(a.mainWindow.screenLeft+a.mainWindow.innerWidth/2-ye/2),x=Math.floor(a.mainWindow.screenTop+a.mainWindow.innerHeight/2-pe/2);a.mainWindow.open(L,"_blank",`width=${ye},height=${pe},top=${x},left=${O}`)},t.windowOpenWithSuccess=function(L,O=!0){const x=a.mainWindow.open();return!!x&&(O&&(x.opener=null),x.location.href=L,!0)},t.animate=function(L,O){const x=()=>{O(),U=(0,t.scheduleAtNextAnimationFrame)(L,x)};let U=(0,t.scheduleAtNextAnimationFrame)(L,x);return(0,o.toDisposable)((()=>U.dispose()))},t.asCSSPropertyValue=function(L){return`'${L.replace(/'/g,"%27")}'`},t.asCssValueWithDefault=function L(O,x){if(O!==void 0){const U=O.match(/^\s*var\((.+)\)$/);if(U){const z=U[1].split(",",2);return z.length===2&&(x=L(z[1].trim(),x)),`var(${z[0]}, ${x})`}return O}return x},t.detectFullscreen=function(L){return L.document.fullscreenElement||L.document.webkitFullscreenElement||L.document.webkitIsFullScreen?{mode:ge.DOCUMENT,guess:!1}:L.innerHeight===L.screen.height?{mode:ge.BROWSER,guess:!1}:(d.isMacintosh||d.isLinux)&&L.outerHeight===L.screen.height&&L.outerWidth===L.screen.width?{mode:ge.BROWSER,guess:!0}:null},t.multibyteAwareBtoa=function(L){return btoa((function(O){const x=new Uint16Array(O.length);for(let G=0;G<x.length;G++)x[G]=O.charCodeAt(G);let U="";const z=new Uint8Array(x.buffer);for(let G=0;G<z.length;G++)U+=String.fromCharCode(z[G]);return U})(L))},t.getCookieValue=function(L){const O=document.cookie.match("(^|[^;]+)\\s*"+L+"\\s*=\\s*([^;]+)");return O?O.pop():void 0},t.h=function(L,...O){let x,U;Array.isArray(O[0])?(x={},U=O[0]):(x=O[0]||{},U=O[1]);const z=Me.exec(L);if(!z||!z.groups)throw new Error("Bad use of h");const G=z.groups.tag||"div",q=document.createElement(G);z.groups.id&&(q.id=z.groups.id);const Y=[];if(z.groups.class)for(const J of z.groups.class.split("."))J!==""&&Y.push(J);if(x.className!==void 0)for(const J of x.className.split("."))J!==""&&Y.push(J);Y.length>0&&(q.className=Y.join(" "));const Q={};if(z.groups.name&&(Q[z.groups.name]=q),U)for(const J of U)ce(J)?q.appendChild(J):typeof J=="string"?q.append(J):"root"in J&&(Object.assign(Q,J),q.appendChild(J.root));for(const[J,ae]of Object.entries(x))if(J!=="className")if(J==="style")for(const[me,Ee]of Object.entries(ae))q.style.setProperty(ke(me),typeof Ee=="number"?Ee+"px":""+Ee);else J==="tabIndex"?q.tabIndex=ae:q.setAttribute(ke(J),ae.toString());return Q.root=q,Q},t.svgElem=function(L,...O){let x,U;Array.isArray(O[0])?(x={},U=O[0]):(x=O[0]||{},U=O[1]);const z=Me.exec(L);if(!z||!z.groups)throw new Error("Bad use of h");const G=z.groups.tag||"div",q=document.createElementNS("http://www.w3.org/2000/svg",G);z.groups.id&&(q.id=z.groups.id);const Y=[];if(z.groups.class)for(const J of z.groups.class.split("."))J!==""&&Y.push(J);if(x.className!==void 0)for(const J of x.className.split("."))J!==""&&Y.push(J);Y.length>0&&(q.className=Y.join(" "));const Q={};if(z.groups.name&&(Q[z.groups.name]=q),U)for(const J of U)ce(J)?q.appendChild(J):typeof J=="string"?q.append(J):"root"in J&&(Object.assign(Q,J),q.appendChild(J.root));for(const[J,ae]of Object.entries(x))if(J!=="className")if(J==="style")for(const[me,Ee]of Object.entries(ae))q.style.setProperty(ke(me),typeof Ee=="number"?Ee+"px":""+Ee);else J==="tabIndex"?q.tabIndex=ae:q.setAttribute(ke(J),ae.toString());return Q.root=q,Q},t.copyAttributes=Ie,t.trackAttributes=function(L,O,x){Ie(L,O,x);const U=new o.DisposableStore;return U.add(t.sharedMutationObserver.observe(L,U,{attributes:!0,attributeFilter:x})((z=>{for(const G of z)G.type==="attributes"&&G.attributeName&&Pe(L,O,G.attributeName)}))),U};const g=f(_(4333)),p=_(7745),u=_(5394),r=_(5964),h=_(1758),s=_(9807),e=f(_(802)),l=_(7883),o=_(7150),d=f(_(8163)),c=_(6304),a=_(4693),m=_(7704);i=(function(){const L=new Map;(0,a.ensureCodeWindow)(a.mainWindow,1);const O={window:a.mainWindow,disposables:new o.DisposableStore};L.set(a.mainWindow.vscodeWindowId,O);const x=new e.Emitter,U=new e.Emitter,z=new e.Emitter;return{onDidRegisterWindow:x.event,onWillUnregisterWindow:z.event,onDidUnregisterWindow:U.event,registerWindow(G){if(L.has(G.vscodeWindowId))return o.Disposable.None;const q=new o.DisposableStore,Y={window:G,disposables:q.add(new o.DisposableStore)};return L.set(G.vscodeWindowId,Y),q.add((0,o.toDisposable)((()=>{L.delete(G.vscodeWindowId),U.fire(G)}))),q.add(R(G,t.EventType.BEFORE_UNLOAD,(()=>{z.fire(G)}))),x.fire(Y),q},getWindows:()=>L.values(),getWindowsCount:()=>L.size,getWindowId:G=>G.vscodeWindowId,hasWindow:G=>L.has(G),getWindowById:function(G,q){return(typeof G=="number"?L.get(G):void 0)??(q?O:void 0)},getWindow(G){var Q;const q=G;if((Q=q==null?void 0:q.ownerDocument)!=null&&Q.defaultView)return q.ownerDocument.defaultView.window;const Y=G;return Y!=null&&Y.view?Y.view.window:a.mainWindow},getDocument(G){const q=G;return(0,t.getWindow)(q).document}}})(),t.registerWindow=i.registerWindow,t.getWindow=i.getWindow,t.getDocument=i.getDocument,t.getWindows=i.getWindows,t.getWindowsCount=i.getWindowsCount,t.getWindowId=i.getWindowId,t.getWindowById=i.getWindowById,t.hasWindow=i.hasWindow,t.onDidRegisterWindow=i.onDidRegisterWindow,t.onWillUnregisterWindow=i.onWillUnregisterWindow,t.onDidUnregisterWindow=i.onDidUnregisterWindow;class b{constructor(O,x,U,z){this._node=O,this._type=x,this._handler=U,this._options=z||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}}function R(L,O,x,U){return new b(L,O,x,U)}function T(L,O){return function(x){return O(new r.StandardMouseEvent(L,x))}}function C(L,O,x){return R(L,d.isIOS&&p.BrowserFeatures.pointerEvents?t.EventType.POINTER_DOWN:t.EventType.MOUSE_DOWN,O,x)}function E(L,O,x){return R(L,d.isIOS&&p.BrowserFeatures.pointerEvents?t.EventType.POINTER_UP:t.EventType.MOUSE_UP,O,x)}t.addStandardDisposableListener=function(L,O,x,U){let z=x;return O==="click"||O==="mousedown"||O==="contextmenu"?z=T((0,t.getWindow)(L),x):O!=="keydown"&&O!=="keypress"&&O!=="keyup"||(z=(function(G){return function(q){return G(new u.StandardKeyboardEvent(q))}})(x)),R(L,O,z,U)},t.addStandardDisposableGenericMouseDownListener=function(L,O,x){return C(L,T((0,t.getWindow)(L),O),x)},t.addStandardDisposableGenericMouseUpListener=function(L,O,x){return E(L,T((0,t.getWindow)(L),O),x)};class A extends h.AbstractIdleValue{constructor(O,x){super(O,x)}}t.WindowIdleValue=A;class N extends h.IntervalTimer{constructor(O){super(),this.defaultTarget=O&&(0,t.getWindow)(O)}cancelAndSet(O,x,U){return super.cancelAndSet(O,x,U??this.defaultTarget)}}t.WindowIntervalTimer=N;class P{constructor(O,x=0){this._runner=O,this.priority=x,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(O){(0,s.onUnexpectedError)(O)}}static sort(O,x){return x.priority-O.priority}}(function(){const L=new Map,O=new Map,x=new Map,U=new Map;t.scheduleAtNextAnimationFrame=(z,G,q=0)=>{const Y=(0,t.getWindowId)(z),Q=new P(G,q);let J=L.get(Y);return J||(J=[],L.set(Y,J)),J.push(Q),x.get(Y)||(x.set(Y,!0),z.requestAnimationFrame((()=>(ae=>{x.set(ae,!1);const me=L.get(ae)??[];for(O.set(ae,me),L.set(ae,[]),U.set(ae,!0);me.length>0;)me.sort(P.sort),me.shift().execute();U.set(ae,!1)})(Y)))),Q},t.runAtThisOrScheduleAtNextAnimationFrame=(z,G,q)=>{const Y=(0,t.getWindowId)(z);if(U.get(Y)){const Q=new P(G,q);let J=O.get(Y);return J||(J=[],O.set(Y,J)),J.push(Q),Q}return(0,t.scheduleAtNextAnimationFrame)(z,G,q)}})();const W=function(L,O){return O};class w extends o.Disposable{constructor(O,x,U,z=W,G=8){super();let q=null,Y=0;const Q=this._register(new h.TimeoutTimer),J=()=>{Y=new Date().getTime(),U(q),q=null};this._register(R(O,x,(ae=>{q=z(q,ae);const me=new Date().getTime()-Y;me>=G?(Q.cancel(),J()):Q.setIfNotSet(J,G-me)})))}}function y(L){return(0,t.getWindow)(L).getComputedStyle(L,null)}class S{static convertToPixels(O,x){return parseFloat(x)||0}static getDimension(O,x,U){const z=y(O),G=z?z.getPropertyValue(x):"0";return S.convertToPixels(O,G)}static getBorderLeftWidth(O){return S.getDimension(O,"border-left-width","borderLeftWidth")}static getBorderRightWidth(O){return S.getDimension(O,"border-right-width","borderRightWidth")}static getBorderTopWidth(O){return S.getDimension(O,"border-top-width","borderTopWidth")}static getBorderBottomWidth(O){return S.getDimension(O,"border-bottom-width","borderBottomWidth")}static getPaddingLeft(O){return S.getDimension(O,"padding-left","paddingLeft")}static getPaddingRight(O){return S.getDimension(O,"padding-right","paddingRight")}static getPaddingTop(O){return S.getDimension(O,"padding-top","paddingTop")}static getPaddingBottom(O){return S.getDimension(O,"padding-bottom","paddingBottom")}static getMarginLeft(O){return S.getDimension(O,"margin-left","marginLeft")}static getMarginTop(O){return S.getDimension(O,"margin-top","marginTop")}static getMarginRight(O){return S.getDimension(O,"margin-right","marginRight")}static getMarginBottom(O){return S.getDimension(O,"margin-bottom","marginBottom")}}const we=class we{constructor(O,x){this.width=O,this.height=x}with(O=this.width,x=this.height){return O!==this.width||x!==this.height?new we(O,x):this}static is(O){return typeof O=="object"&&typeof O.height=="number"&&typeof O.width=="number"}static lift(O){return O instanceof we?O:new we(O.width,O.height)}static equals(O,x){return O===x||!(!O||!x)&&O.width===x.width&&O.height===x.height}};we.None=new we(0,0);let D=we;function M(L){let O=L.offsetParent,x=L.offsetTop,U=L.offsetLeft;for(;(L=L.parentNode)!==null&&L!==L.ownerDocument.body&&L!==L.ownerDocument.documentElement;){x-=L.scrollTop;const z=$(L)?null:y(L);z&&(U-=z.direction!=="rtl"?L.scrollLeft:-L.scrollLeft),L===O&&(U+=S.getBorderLeftWidth(L),x+=S.getBorderTopWidth(L),x+=L.offsetTop,U+=L.offsetLeft,O=L.offsetParent)}return{left:U,top:x}}function I(L){const O=S.getMarginLeft(L)+S.getMarginRight(L);return L.offsetWidth+O}function F(L){const O=S.getMarginLeft(L)+S.getMarginRight(L);return L.scrollWidth+O}function H(L,O){return!!(O!=null&&O.contains(L))}t.Dimension=D;const B="parentFlowToElementId";function k(L){const O=L.dataset[B];return typeof O=="string"?L.ownerDocument.getElementById(O):null}function j(L,O,x){for(;L&&L.nodeType===L.ELEMENT_NODE;){if(L.classList.contains(O))return L;if(x){if(typeof x=="string"){if(L.classList.contains(x))return null}else if(L===x)return null}L=L.parentNode}return null}function $(L){return L&&!!L.host&&!!L.mode}function X(L){var O;for(;L.parentNode;){if(L===((O=L.ownerDocument)==null?void 0:O.body))return null;L=L.parentNode}return $(L)?L:null}function V(){let L=Z().activeElement;for(;L!=null&&L.shadowRoot;)L=L.shadowRoot.activeElement;return L}function Z(){return(0,t.getWindowsCount)()<=1?a.mainWindow.document:Array.from((0,t.getWindows)()).map((({window:L})=>L.document)).find((L=>L.hasFocus()))??a.mainWindow.document}const se=new Map;class te{constructor(){this._currentCssStyle="",this._styleSheet=void 0}setStyle(O){O!==this._currentCssStyle&&(this._currentCssStyle=O,this._styleSheet?this._styleSheet.innerText=O:this._styleSheet=re(a.mainWindow.document.head,(x=>x.innerText=O)))}dispose(){this._styleSheet&&(this._styleSheet.remove(),this._styleSheet=void 0)}}function re(L=a.mainWindow.document.head,O,x){const U=document.createElement("style");if(U.type="text/css",U.media="screen",O==null||O(U),L.appendChild(U),x&&x.add((0,o.toDisposable)((()=>U.remove()))),L===a.mainWindow.document.head){const z=new Set;se.set(U,z);for(const{window:G,disposables:q}of(0,t.getWindows)()){if(G===a.mainWindow)continue;const Y=q.add(ne(U,z,G));x==null||x.add(Y)}}return U}function ne(L,O,x){var G,q;const U=new o.DisposableStore,z=L.cloneNode(!0);x.document.head.appendChild(z),U.add((0,o.toDisposable)((()=>z.remove())));for(const Y of ue(L))(q=z.sheet)==null||q.insertRule(Y.cssText,(G=z.sheet)==null?void 0:G.cssRules.length);return U.add(t.sharedMutationObserver.observe(L,U,{childList:!0})((()=>{z.textContent=L.textContent}))),O.add(z),U.add((0,o.toDisposable)((()=>O.delete(z)))),U}function oe(L,O=a.mainWindow.document.head){const x=document.createElement(L);return O.appendChild(x),x}t.sharedMutationObserver=new class{constructor(){this.mutationObservers=new Map}observe(L,O,x){let U=this.mutationObservers.get(L);U||(U=new Map,this.mutationObservers.set(L,U));const z=(0,c.hash)(x);let G=U.get(z);if(G)G.users+=1;else{const q=new e.Emitter,Y=new MutationObserver((J=>q.fire(J)));Y.observe(L,x);const Q=G={users:1,observer:Y,onDidMutate:q.event};O.add((0,o.toDisposable)((()=>{Q.users-=1,Q.users===0&&(q.dispose(),Y.disconnect(),U==null||U.delete(z),(U==null?void 0:U.size)===0&&this.mutationObservers.delete(L))}))),U.set(z,G)}return G.onDidMutate}};let ve=null;function ee(){return ve||(ve=re()),ve}function ue(L){var O,x;return(O=L==null?void 0:L.sheet)!=null&&O.rules?L.sheet.rules:(x=L==null?void 0:L.sheet)!=null&&x.cssRules?L.sheet.cssRules:[]}function Ae(L){return typeof L.selectorText=="string"}function ce(L){return L instanceof HTMLElement||L instanceof(0,t.getWindow)(L).HTMLElement}t.EventType={CLICK:"click",AUXCLICK:"auxclick",DBLCLICK:"dblclick",MOUSE_UP:"mouseup",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_MOVE:"mousemove",MOUSE_OUT:"mouseout",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",POINTER_LEAVE:"pointerleave",CONTEXT_MENU:"contextmenu",WHEEL:"wheel",KEY_DOWN:"keydown",KEY_PRESS:"keypress",KEY_UP:"keyup",LOAD:"load",BEFORE_UNLOAD:"beforeunload",UNLOAD:"unload",PAGE_SHOW:"pageshow",PAGE_HIDE:"pagehide",PASTE:"paste",ABORT:"abort",ERROR:"error",RESIZE:"resize",SCROLL:"scroll",FULLSCREEN_CHANGE:"fullscreenchange",WK_FULLSCREEN_CHANGE:"webkitfullscreenchange",SELECT:"select",CHANGE:"change",SUBMIT:"submit",RESET:"reset",FOCUS:"focus",FOCUS_IN:"focusin",FOCUS_OUT:"focusout",BLUR:"blur",INPUT:"input",STORAGE:"storage",DRAG_START:"dragstart",DRAG:"drag",DRAG_ENTER:"dragenter",DRAG_LEAVE:"dragleave",DRAG_OVER:"dragover",DROP:"drop",DRAG_END:"dragend",ANIMATION_START:g.isWebKit?"webkitAnimationStart":"animationstart",ANIMATION_END:g.isWebKit?"webkitAnimationEnd":"animationend",ANIMATION_ITERATION:g.isWebKit?"webkitAnimationIteration":"animationiteration"},t.EventHelper={stop:(L,O)=>(L.preventDefault(),O&&L.stopPropagation(),L)};class Se extends o.Disposable{static hasFocusWithin(O){if(ce(O)){const x=X(O);return H(x?x.activeElement:O.ownerDocument.activeElement,O)}{const x=O;return H(x.document.activeElement,x.document)}}constructor(O){super(),this._onDidFocus=this._register(new e.Emitter),this.onDidFocus=this._onDidFocus.event,this._onDidBlur=this._register(new e.Emitter),this.onDidBlur=this._onDidBlur.event;let x=Se.hasFocusWithin(O),U=!1;const z=()=>{U=!1,x||(x=!0,this._onDidFocus.fire())},G=()=>{x&&(U=!0,(ce(O)?(0,t.getWindow)(O):O).setTimeout((()=>{U&&(U=!1,x=!1,this._onDidBlur.fire())}),0))};this._refreshStateHandler=()=>{Se.hasFocusWithin(O)!==x&&(x?G():z())},this._register(R(O,t.EventType.FOCUS,z,!0)),this._register(R(O,t.EventType.BLUR,G,!0)),ce(O)&&(this._register(R(O,t.EventType.FOCUS_IN,(()=>this._refreshStateHandler()))),this._register(R(O,t.EventType.FOCUS_OUT,(()=>this._refreshStateHandler()))))}refreshState(){this._refreshStateHandler()}}function Ce(L,...O){if(L.append(...O),O.length===1&&typeof O[0]!="string")return O[0]}const le=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;var _e;function he(L,O,x,...U){const z=le.exec(O);if(!z)throw new Error("Bad use of emmet");const G=z[1]||"div";let q;return q=L!==_e.HTML?document.createElementNS(L,G):document.createElement(G),z[3]&&(q.id=z[3]),z[4]&&(q.className=z[4].replace(/\./g," ").trim()),x&&Object.entries(x).forEach((([Y,Q])=>{Q!==void 0&&(/^on\w+$/.test(Y)?q[Y]=Q:Y==="selected"?Q&&q.setAttribute(Y,"true"):q.setAttribute(Y,Q))})),q.append(...U),q}function be(L,O,...x){return he(_e.HTML,L,O,...x)}function Le(...L){for(const O of L)O.style.display="",O.removeAttribute("aria-hidden")}function fe(...L){for(const O of L)O.style.display="none",O.setAttribute("aria-hidden","true")}(function(L){L.HTML="http://www.w3.org/1999/xhtml",L.SVG="http://www.w3.org/2000/svg"})(_e||(t.Namespace=_e={})),be.SVG=function(L,O,...x){return he(_e.SVG,L,O,...x)};const ye=780,pe=640;var ge;(function(L){L[L.DOCUMENT=1]="DOCUMENT",L[L.BROWSER=2]="BROWSER"})(ge||(t.DetectedFullscreenMode=ge={}));class ie extends e.Emitter{constructor(){super(),this._subscriptions=new o.DisposableStore,this._keyStatus={altKey:!1,shiftKey:!1,ctrlKey:!1,metaKey:!1},this._subscriptions.add(e.Event.runAndSubscribe(t.onDidRegisterWindow,(({window:O,disposables:x})=>this.registerListeners(O,x)),{window:a.mainWindow,disposables:this._subscriptions}))}registerListeners(O,x){x.add(R(O,"keydown",(U=>{if(U.defaultPrevented)return;const z=new u.StandardKeyboardEvent(U);if(z.keyCode!==l.KeyCode.Alt||!U.repeat){if(U.altKey&&!this._keyStatus.altKey)this._keyStatus.lastKeyPressed="alt";else if(U.ctrlKey&&!this._keyStatus.ctrlKey)this._keyStatus.lastKeyPressed="ctrl";else if(U.metaKey&&!this._keyStatus.metaKey)this._keyStatus.lastKeyPressed="meta";else if(U.shiftKey&&!this._keyStatus.shiftKey)this._keyStatus.lastKeyPressed="shift";else{if(z.keyCode===l.KeyCode.Alt)return;this._keyStatus.lastKeyPressed=void 0}this._keyStatus.altKey=U.altKey,this._keyStatus.ctrlKey=U.ctrlKey,this._keyStatus.metaKey=U.metaKey,this._keyStatus.shiftKey=U.shiftKey,this._keyStatus.lastKeyPressed&&(this._keyStatus.event=U,this.fire(this._keyStatus))}}),!0)),x.add(R(O,"keyup",(U=>{U.defaultPrevented||(!U.altKey&&this._keyStatus.altKey?this._keyStatus.lastKeyReleased="alt":!U.ctrlKey&&this._keyStatus.ctrlKey?this._keyStatus.lastKeyReleased="ctrl":!U.metaKey&&this._keyStatus.metaKey?this._keyStatus.lastKeyReleased="meta":!U.shiftKey&&this._keyStatus.shiftKey?this._keyStatus.lastKeyReleased="shift":this._keyStatus.lastKeyReleased=void 0,this._keyStatus.lastKeyPressed!==this._keyStatus.lastKeyReleased&&(this._keyStatus.lastKeyPressed=void 0),this._keyStatus.altKey=U.altKey,this._keyStatus.ctrlKey=U.ctrlKey,this._keyStatus.metaKey=U.metaKey,this._keyStatus.shiftKey=U.shiftKey,this._keyStatus.lastKeyReleased&&(this._keyStatus.event=U,this.fire(this._keyStatus)))}),!0)),x.add(R(O.document.body,"mousedown",(()=>{this._keyStatus.lastKeyPressed=void 0}),!0)),x.add(R(O.document.body,"mouseup",(()=>{this._keyStatus.lastKeyPressed=void 0}),!0)),x.add(R(O.document.body,"mousemove",(U=>{U.buttons&&(this._keyStatus.lastKeyPressed=void 0)}),!0)),x.add(R(O,"blur",(()=>{this.resetKeyStatus()})))}get keyStatus(){return this._keyStatus}get isModifierPressed(){return this._keyStatus.altKey||this._keyStatus.ctrlKey||this._keyStatus.metaKey||this._keyStatus.shiftKey}resetKeyStatus(){this.doResetKeyStatus(),this.fire(this._keyStatus)}doResetKeyStatus(){this._keyStatus={altKey:!1,shiftKey:!1,ctrlKey:!1,metaKey:!1}}static getInstance(){return ie.instance||(ie.instance=new ie),ie.instance}dispose(){super.dispose(),this._subscriptions.dispose()}}t.ModifierKeyEmitter=ie;class Te extends o.Disposable{constructor(O,x){super(),this.element=O,this.callbacks=x,this.counter=0,this.dragStartTime=0,this.registerListeners()}registerListeners(){this.callbacks.onDragStart&&this._register(R(this.element,t.EventType.DRAG_START,(O=>{var x,U;(U=(x=this.callbacks).onDragStart)==null||U.call(x,O)}))),this.callbacks.onDrag&&this._register(R(this.element,t.EventType.DRAG,(O=>{var x,U;(U=(x=this.callbacks).onDrag)==null||U.call(x,O)}))),this._register(R(this.element,t.EventType.DRAG_ENTER,(O=>{var x,U;this.counter++,this.dragStartTime=O.timeStamp,(U=(x=this.callbacks).onDragEnter)==null||U.call(x,O)}))),this._register(R(this.element,t.EventType.DRAG_OVER,(O=>{var x,U;O.preventDefault(),(U=(x=this.callbacks).onDragOver)==null||U.call(x,O,O.timeStamp-this.dragStartTime)}))),this._register(R(this.element,t.EventType.DRAG_LEAVE,(O=>{var x,U;this.counter--,this.counter===0&&(this.dragStartTime=0,(U=(x=this.callbacks).onDragLeave)==null||U.call(x,O))}))),this._register(R(this.element,t.EventType.DRAG_END,(O=>{var x,U;this.counter=0,this.dragStartTime=0,(U=(x=this.callbacks).onDragEnd)==null||U.call(x,O)}))),this._register(R(this.element,t.EventType.DROP,(O=>{var x,U;this.counter=0,this.dragStartTime=0,(U=(x=this.callbacks).onDrop)==null||U.call(x,O)})))}}t.DragAndDropObserver=Te;const Me=/(?<tag>[\w\-]+)?(?:#(?<id>[\w\-]+))?(?<class>(?:\.(?:[\w\-]+))*)(?:@(?<name>(?:[\w\_])+))?/;function ke(L){return L.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Ie(L,O,x){for(const{name:U,value:z}of L.attributes)x&&!x.includes(U)||O.setAttribute(U,z)}function Pe(L,O,x){const U=L.getAttribute(x);U?O.setAttribute(x,U):O.removeAttribute(x)}t.SafeTriangle=class{constructor(L,O,x){this.originX=L,this.originY=O,this.triangles=[];const{top:U,left:z,right:G,bottom:q}=x.getBoundingClientRect(),Y=this.triangles;let Q=0;Y[Q++]=z,Y[Q++]=U,Y[Q++]=G,Y[Q++]=U,Y[Q++]=z,Y[Q++]=U,Y[Q++]=z,Y[Q++]=q,Y[Q++]=G,Y[Q++]=U,Y[Q++]=G,Y[Q++]=q,Y[Q++]=z,Y[Q++]=q,Y[Q++]=G,Y[Q++]=q}contains(L,O){const{triangles:x,originX:U,originY:z}=this;for(let G=0;G<4;G++)if((0,m.isPointWithinTriangle)(L,O,U,z,x[2*G],x[2*G+1],x[2*G+2],x[2*G+3]))return!0;return!1}}},9675:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FastDomNode=void 0,t.createFastDomNode=function(v){return new _(v)};class _{constructor(n){this.domNode=n,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(n){const f=i(n);this._maxWidth!==f&&(this._maxWidth=f,this.domNode.style.maxWidth=this._maxWidth)}setWidth(n){const f=i(n);this._width!==f&&(this._width=f,this.domNode.style.width=this._width)}setHeight(n){const f=i(n);this._height!==f&&(this._height=f,this.domNode.style.height=this._height)}setTop(n){const f=i(n);this._top!==f&&(this._top=f,this.domNode.style.top=this._top)}setLeft(n){const f=i(n);this._left!==f&&(this._left=f,this.domNode.style.left=this._left)}setBottom(n){const f=i(n);this._bottom!==f&&(this._bottom=f,this.domNode.style.bottom=this._bottom)}setRight(n){const f=i(n);this._right!==f&&(this._right=f,this.domNode.style.right=this._right)}setPaddingTop(n){const f=i(n);this._paddingTop!==f&&(this._paddingTop=f,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(n){const f=i(n);this._paddingLeft!==f&&(this._paddingLeft=f,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(n){const f=i(n);this._paddingBottom!==f&&(this._paddingBottom=f,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(n){const f=i(n);this._paddingRight!==f&&(this._paddingRight=f,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(n){this._fontFamily!==n&&(this._fontFamily=n,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(n){this._fontWeight!==n&&(this._fontWeight=n,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(n){const f=i(n);this._fontSize!==f&&(this._fontSize=f,this.domNode.style.fontSize=this._fontSize)}setFontStyle(n){this._fontStyle!==n&&(this._fontStyle=n,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(n){this._fontFeatureSettings!==n&&(this._fontFeatureSettings=n,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(n){this._fontVariationSettings!==n&&(this._fontVariationSettings=n,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(n){this._textDecoration!==n&&(this._textDecoration=n,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(n){const f=i(n);this._lineHeight!==f&&(this._lineHeight=f,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(n){const f=i(n);this._letterSpacing!==f&&(this._letterSpacing=f,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(n){this._className!==n&&(this._className=n,this.domNode.className=this._className)}toggleClassName(n,f){this.domNode.classList.toggle(n,f),this._className=this.domNode.className}setDisplay(n){this._display!==n&&(this._display=n,this.domNode.style.display=this._display)}setPosition(n){this._position!==n&&(this._position=n,this.domNode.style.position=this._position)}setVisibility(n){this._visibility!==n&&(this._visibility=n,this.domNode.style.visibility=this._visibility)}setColor(n){this._color!==n&&(this._color=n,this.domNode.style.color=this._color)}setBackgroundColor(n){this._backgroundColor!==n&&(this._backgroundColor=n,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(n){this._layerHint!==n&&(this._layerHint=n,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(n){this._boxShadow!==n&&(this._boxShadow=n,this.domNode.style.boxShadow=n)}setContain(n){this._contain!==n&&(this._contain=n,this.domNode.style.contain=this._contain)}setAttribute(n,f){this.domNode.setAttribute(n,f)}removeAttribute(n){this.domNode.removeAttribute(n)}appendChild(n){this.domNode.appendChild(n.domNode)}removeChild(n){this.domNode.removeChild(n.domNode)}}function i(v){return typeof v=="number"?`${v}px`:v}t.FastDomNode=_},8328:function(K,t,_){var i=this&&this.__createBinding||(Object.create?function(p,u,r,h){h===void 0&&(h=r);var s=Object.getOwnPropertyDescriptor(u,r);s&&!("get"in s?!u.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return u[r]}}),Object.defineProperty(p,h,s)}:function(p,u,r,h){h===void 0&&(h=r),p[h]=u[r]}),v=this&&this.__setModuleDefault||(Object.create?function(p,u){Object.defineProperty(p,"default",{enumerable:!0,value:u})}:function(p,u){p.default=u}),n=this&&this.__importStar||function(p){if(p&&p.__esModule)return p;var u={};if(p!=null)for(var r in p)r!=="default"&&Object.prototype.hasOwnProperty.call(p,r)&&i(u,p,r);return v(u,p),u};Object.defineProperty(t,"__esModule",{value:!0}),t.GlobalPointerMoveMonitor=void 0;const f=n(_(7093)),g=_(7150);t.GlobalPointerMoveMonitor=class{constructor(){this._hooks=new g.DisposableStore,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(p,u){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;const r=this._onStopCallback;this._onStopCallback=null,p&&r&&r(u)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(p,u,r,h,s){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=h,this._onStopCallback=s;let e=p;try{p.setPointerCapture(u),this._hooks.add((0,g.toDisposable)((()=>{try{p.releasePointerCapture(u)}catch{}})))}catch{e=f.getWindow(p)}this._hooks.add(f.addDisposableListener(e,f.EventType.POINTER_MOVE,(l=>{l.buttons===r?(l.preventDefault(),this._pointerMoveCallback(l)):this.stopMonitoring(!0)}))),this._hooks.add(f.addDisposableListener(e,f.EventType.POINTER_UP,(l=>this.stopMonitoring(!0))))}}},6609:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IframeUtils=void 0,t.parentOriginHash=async function(v,n){if(!crypto.subtle)throw new Error("'crypto.subtle' is not available so webviews will not work. This is likely because the editor is not running in a secure context (https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).");const f=JSON.stringify({parentOrigin:v,salt:n}),g=new TextEncoder().encode(f);return(function(p){const u=Array.from(new Uint8Array(p)).map((r=>r.toString(16).padStart(2,"0"))).join("");return BigInt(`0x${u}`).toString(32).padStart(52,"0")})(await crypto.subtle.digest("sha-256",g))};const _=new WeakMap;function i(v){if(!v.parent||v.parent===v)return null;try{const n=v.location,f=v.parent.location;if(n.origin!=="null"&&f.origin!=="null"&&n.origin!==f.origin)return null}catch{return null}return v.parent}t.IframeUtils=class{static getSameOriginWindowChain(v){let n=_.get(v);if(!n){n=[],_.set(v,n);let f,g=v;do f=i(g),f?n.push({window:new WeakRef(g),iframeElement:g.frameElement||null}):n.push({window:new WeakRef(g),iframeElement:null}),g=f;while(g)}return n.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(v,n){if(!n||v===n)return{top:0,left:0};let f=0,g=0;const p=this.getSameOriginWindowChain(v);for(const u of p){const r=u.window.deref();if(f+=(r==null?void 0:r.scrollY)??0,g+=(r==null?void 0:r.scrollX)??0,r===n||!u.iframeElement)break;const h=u.iframeElement.getBoundingClientRect();f+=h.top,g+=h.left}return{top:f,left:g}}}},5394:function(K,t,_){var i=this&&this.__createBinding||(Object.create?function(l,o,d,c){c===void 0&&(c=d);var a=Object.getOwnPropertyDescriptor(o,d);a&&!("get"in a?!o.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return o[d]}}),Object.defineProperty(l,c,a)}:function(l,o,d,c){c===void 0&&(c=d),l[c]=o[d]}),v=this&&this.__setModuleDefault||(Object.create?function(l,o){Object.defineProperty(l,"default",{enumerable:!0,value:o})}:function(l,o){l.default=o}),n=this&&this.__importStar||function(l){if(l&&l.__esModule)return l;var o={};if(l!=null)for(var d in l)d!=="default"&&Object.prototype.hasOwnProperty.call(l,d)&&i(o,l,d);return v(o,l),o};Object.defineProperty(t,"__esModule",{value:!0}),t.StandardKeyboardEvent=void 0,t.printKeyboardEvent=function(l){const o=[];return l.ctrlKey&&o.push("ctrl"),l.shiftKey&&o.push("shift"),l.altKey&&o.push("alt"),l.metaKey&&o.push("meta"),`modifiers: [${o.join(",")}], code: ${l.code}, keyCode: ${l.keyCode}, key: ${l.key}`},t.printStandardKeyboardEvent=function(l){const o=[];return l.ctrlKey&&o.push("ctrl"),l.shiftKey&&o.push("shift"),l.altKey&&o.push("alt"),l.metaKey&&o.push("meta"),`modifiers: [${o.join(",")}], code: ${l.code}, keyCode: ${l.keyCode} ('${g.KeyCodeUtils.toString(l.keyCode)}')`};const f=n(_(4333)),g=_(7883),p=_(2811),u=n(_(8163)),r=u.isMacintosh?g.KeyMod.WinCtrl:g.KeyMod.CtrlCmd,h=g.KeyMod.Alt,s=g.KeyMod.Shift,e=u.isMacintosh?g.KeyMod.CtrlCmd:g.KeyMod.WinCtrl;t.StandardKeyboardEvent=class{constructor(l){var d;this._standardKeyboardEventBrand=!0;const o=l;this.browserEvent=o,this.target=o.target,this.ctrlKey=o.ctrlKey,this.shiftKey=o.shiftKey,this.altKey=o.altKey,this.metaKey=o.metaKey,this.altGraphKey=(d=o.getModifierState)==null?void 0:d.call(o,"AltGraph"),this.keyCode=(function(c){if(c.charCode){const m=String.fromCharCode(c.charCode).toUpperCase();return g.KeyCodeUtils.fromString(m)}const a=c.keyCode;if(a===3)return g.KeyCode.PauseBreak;if(f.isFirefox)switch(a){case 59:return g.KeyCode.Semicolon;case 60:if(u.isLinux)return g.KeyCode.IntlBackslash;break;case 61:return g.KeyCode.Equal;case 107:return g.KeyCode.NumpadAdd;case 109:return g.KeyCode.NumpadSubtract;case 173:return g.KeyCode.Minus;case 224:if(u.isMacintosh)return g.KeyCode.Meta}else if(f.isWebKit&&(u.isMacintosh&&a===93||!u.isMacintosh&&a===92))return g.KeyCode.Meta;return g.EVENT_KEY_CODE_MAP[a]||g.KeyCode.Unknown})(o),this.code=o.code,this.ctrlKey=this.ctrlKey||this.keyCode===g.KeyCode.Ctrl,this.altKey=this.altKey||this.keyCode===g.KeyCode.Alt,this.shiftKey=this.shiftKey||this.keyCode===g.KeyCode.Shift,this.metaKey=this.metaKey||this.keyCode===g.KeyCode.Meta,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(l){return this._asKeybinding===l}_computeKeybinding(){let l=g.KeyCode.Unknown;this.keyCode!==g.KeyCode.Ctrl&&this.keyCode!==g.KeyCode.Shift&&this.keyCode!==g.KeyCode.Alt&&this.keyCode!==g.KeyCode.Meta&&(l=this.keyCode);let o=0;return this.ctrlKey&&(o|=r),this.altKey&&(o|=h),this.shiftKey&&(o|=s),this.metaKey&&(o|=e),o|=l,o}_computeKeyCodeChord(){let l=g.KeyCode.Unknown;return this.keyCode!==g.KeyCode.Ctrl&&this.keyCode!==g.KeyCode.Shift&&this.keyCode!==g.KeyCode.Alt&&this.keyCode!==g.KeyCode.Meta&&(l=this.keyCode),new p.KeyCodeChord(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,l)}}},5964:function(K,t,_){var i=this&&this.__createBinding||(Object.create?function(r,h,s,e){e===void 0&&(e=s);var l=Object.getOwnPropertyDescriptor(h,s);l&&!("get"in l?!h.__esModule:l.writable||l.configurable)||(l={enumerable:!0,get:function(){return h[s]}}),Object.defineProperty(r,e,l)}:function(r,h,s,e){e===void 0&&(e=s),r[e]=h[s]}),v=this&&this.__setModuleDefault||(Object.create?function(r,h){Object.defineProperty(r,"default",{enumerable:!0,value:h})}:function(r,h){r.default=h}),n=this&&this.__importStar||function(r){if(r&&r.__esModule)return r;var h={};if(r!=null)for(var s in r)s!=="default"&&Object.prototype.hasOwnProperty.call(r,s)&&i(h,r,s);return v(h,r),h};Object.defineProperty(t,"__esModule",{value:!0}),t.StandardWheelEvent=t.DragMouseEvent=t.StandardMouseEvent=void 0;const f=n(_(4333)),g=_(6609),p=n(_(8163));class u{constructor(h,s){this.timestamp=Date.now(),this.browserEvent=s,this.leftButton=s.button===0,this.middleButton=s.button===1,this.rightButton=s.button===2,this.buttons=s.buttons,this.target=s.target,this.detail=s.detail||1,s.type==="dblclick"&&(this.detail=2),this.ctrlKey=s.ctrlKey,this.shiftKey=s.shiftKey,this.altKey=s.altKey,this.metaKey=s.metaKey,typeof s.pageX=="number"?(this.posx=s.pageX,this.posy=s.pageY):(this.posx=s.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=s.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);const e=g.IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(h,s.view);this.posx-=e.left,this.posy-=e.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}}t.StandardMouseEvent=u,t.DragMouseEvent=class extends u{constructor(r,h){super(r,h),this.dataTransfer=h.dataTransfer}},t.StandardWheelEvent=class{constructor(r,h=0,s=0){var l;this.browserEvent=r||null,this.target=r?r.target||r.targetNode||r.srcElement:null,this.deltaY=s,this.deltaX=h;let e=!1;if(f.isChrome){const o=navigator.userAgent.match(/Chrome\/(\d+)/);e=(o?parseInt(o[1]):123)<=122}if(r){const o=r,d=r,c=((l=r.view)==null?void 0:l.devicePixelRatio)||1;if(o.wheelDeltaY!==void 0)this.deltaY=e?o.wheelDeltaY/(120*c):o.wheelDeltaY/120;else if(d.VERTICAL_AXIS!==void 0&&d.axis===d.VERTICAL_AXIS)this.deltaY=-d.detail/3;else if(r.type==="wheel"){const a=r;a.deltaMode===a.DOM_DELTA_LINE?f.isFirefox&&!p.isMacintosh?this.deltaY=-r.deltaY/3:this.deltaY=-r.deltaY:this.deltaY=-r.deltaY/40}if(o.wheelDeltaX!==void 0)f.isSafari&&p.isWindows?this.deltaX=-o.wheelDeltaX/120:this.deltaX=e?o.wheelDeltaX/(120*c):o.wheelDeltaX/120;else if(d.HORIZONTAL_AXIS!==void 0&&d.axis===d.HORIZONTAL_AXIS)this.deltaX=-r.detail/3;else if(r.type==="wheel"){const a=r;a.deltaMode===a.DOM_DELTA_LINE?f.isFirefox&&!p.isMacintosh?this.deltaX=-r.deltaX/3:this.deltaX=-r.deltaX:this.deltaX=-r.deltaX/40}this.deltaY===0&&this.deltaX===0&&r.wheelDelta&&(this.deltaY=e?r.wheelDelta/(120*c):r.wheelDelta/120)}}preventDefault(){var r;(r=this.browserEvent)==null||r.preventDefault()}stopPropagation(){var r;(r=this.browserEvent)==null||r.stopPropagation()}}},8594:function(K,t,_){var i=this&&this.__createBinding||(Object.create?function(c,a,m,b){b===void 0&&(b=m);var R=Object.getOwnPropertyDescriptor(a,m);R&&!("get"in R?!a.__esModule:R.writable||R.configurable)||(R={enumerable:!0,get:function(){return a[m]}}),Object.defineProperty(c,b,R)}:function(c,a,m,b){b===void 0&&(b=m),c[b]=a[m]}),v=this&&this.__setModuleDefault||(Object.create?function(c,a){Object.defineProperty(c,"default",{enumerable:!0,value:a})}:function(c,a){c.default=a}),n=this&&this.__decorate||function(c,a,m,b){var R,T=arguments.length,C=T<3?a:b===null?b=Object.getOwnPropertyDescriptor(a,m):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(c,a,m,b);else for(var E=c.length-1;E>=0;E--)(R=c[E])&&(C=(T<3?R(C):T>3?R(a,m,C):R(a,m))||C);return T>3&&C&&Object.defineProperty(a,m,C),C},f=this&&this.__importStar||function(c){if(c&&c.__esModule)return c;var a={};if(c!=null)for(var m in c)m!=="default"&&Object.prototype.hasOwnProperty.call(c,m)&&i(a,c,m);return v(a,c),a};Object.defineProperty(t,"__esModule",{value:!0}),t.Gesture=t.EventType=void 0;const g=f(_(7093)),p=_(4693),u=f(_(3058)),r=_(4838),h=_(802),s=_(7150),e=_(6317);var l;(function(c){c.Tap="-xterm-gesturetap",c.Change="-xterm-gesturechange",c.Start="-xterm-gesturestart",c.End="-xterm-gesturesend",c.Contextmenu="-xterm-gesturecontextmenu"})(l||(t.EventType=l={}));const d=class d extends s.Disposable{constructor(){super(),this.dispatched=!1,this.targets=new e.LinkedList,this.ignoreTargets=new e.LinkedList,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(h.Event.runAndSubscribe(g.onDidRegisterWindow,(({window:a,disposables:m})=>{m.add(g.addDisposableListener(a.document,"touchstart",(b=>this.onTouchStart(b)),{passive:!1})),m.add(g.addDisposableListener(a.document,"touchend",(b=>this.onTouchEnd(a,b)))),m.add(g.addDisposableListener(a.document,"touchmove",(b=>this.onTouchMove(b)),{passive:!1}))}),{window:p.mainWindow,disposables:this._store}))}static addTarget(a){if(!d.isTouchDevice())return s.Disposable.None;d.INSTANCE||(d.INSTANCE=(0,s.markAsSingleton)(new d));const m=d.INSTANCE.targets.push(a);return(0,s.toDisposable)(m)}static ignoreTarget(a){if(!d.isTouchDevice())return s.Disposable.None;d.INSTANCE||(d.INSTANCE=(0,s.markAsSingleton)(new d));const m=d.INSTANCE.ignoreTargets.push(a);return(0,s.toDisposable)(m)}static isTouchDevice(){return"ontouchstart"in p.mainWindow||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(a){const m=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let b=0,R=a.targetTouches.length;b<R;b++){const T=a.targetTouches.item(b);this.activeTouches[T.identifier]={id:T.identifier,initialTarget:T.target,initialTimeStamp:m,initialPageX:T.pageX,initialPageY:T.pageY,rollingTimestamps:[m],rollingPageX:[T.pageX],rollingPageY:[T.pageY]};const C=this.newGestureEvent(l.Start,T.target);C.pageX=T.pageX,C.pageY=T.pageY,this.dispatchEvent(C)}this.dispatched&&(a.preventDefault(),a.stopPropagation(),this.dispatched=!1)}onTouchEnd(a,m){const b=Date.now(),R=Object.keys(this.activeTouches).length;for(let T=0,C=m.changedTouches.length;T<C;T++){const E=m.changedTouches.item(T);if(!this.activeTouches.hasOwnProperty(String(E.identifier))){console.warn("move of an UNKNOWN touch",E);continue}const A=this.activeTouches[E.identifier],N=Date.now()-A.initialTimeStamp;if(N<d.HOLD_DELAY&&Math.abs(A.initialPageX-u.tail(A.rollingPageX))<30&&Math.abs(A.initialPageY-u.tail(A.rollingPageY))<30){const P=this.newGestureEvent(l.Tap,A.initialTarget);P.pageX=u.tail(A.rollingPageX),P.pageY=u.tail(A.rollingPageY),this.dispatchEvent(P)}else if(N>=d.HOLD_DELAY&&Math.abs(A.initialPageX-u.tail(A.rollingPageX))<30&&Math.abs(A.initialPageY-u.tail(A.rollingPageY))<30){const P=this.newGestureEvent(l.Contextmenu,A.initialTarget);P.pageX=u.tail(A.rollingPageX),P.pageY=u.tail(A.rollingPageY),this.dispatchEvent(P)}else if(R===1){const P=u.tail(A.rollingPageX),W=u.tail(A.rollingPageY),w=u.tail(A.rollingTimestamps)-A.rollingTimestamps[0],y=P-A.rollingPageX[0],S=W-A.rollingPageY[0],D=[...this.targets].filter((M=>A.initialTarget instanceof Node&&M.contains(A.initialTarget)));this.inertia(a,D,b,Math.abs(y)/w,y>0?1:-1,P,Math.abs(S)/w,S>0?1:-1,W)}this.dispatchEvent(this.newGestureEvent(l.End,A.initialTarget)),delete this.activeTouches[E.identifier]}this.dispatched&&(m.preventDefault(),m.stopPropagation(),this.dispatched=!1)}newGestureEvent(a,m){const b=document.createEvent("CustomEvent");return b.initEvent(a,!1,!0),b.initialTarget=m,b.tapCount=0,b}dispatchEvent(a){if(a.type===l.Tap){const m=new Date().getTime();let b=0;b=m-this._lastSetTapCountTime>d.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=m,a.tapCount=b}else a.type!==l.Change&&a.type!==l.Contextmenu||(this._lastSetTapCountTime=0);if(a.initialTarget instanceof Node){for(const b of this.ignoreTargets)if(b.contains(a.initialTarget))return;const m=[];for(const b of this.targets)if(b.contains(a.initialTarget)){let R=0,T=a.initialTarget;for(;T&&T!==b;)R++,T=T.parentElement;m.push([R,b])}m.sort(((b,R)=>b[0]-R[0]));for(const[b,R]of m)R.dispatchEvent(a),this.dispatched=!0}}inertia(a,m,b,R,T,C,E,A,N){this.handle=g.scheduleAtNextAnimationFrame(a,(()=>{const P=Date.now(),W=P-b;let w=0,y=0,S=!0;R+=d.SCROLL_FRICTION*W,E+=d.SCROLL_FRICTION*W,R>0&&(S=!1,w=T*R*W),E>0&&(S=!1,y=A*E*W);const D=this.newGestureEvent(l.Change);D.translationX=w,D.translationY=y,m.forEach((M=>M.dispatchEvent(D))),S||this.inertia(a,m,P,R,T,C+w,E,A,N+y)}))}onTouchMove(a){const m=Date.now();for(let b=0,R=a.changedTouches.length;b<R;b++){const T=a.changedTouches.item(b);if(!this.activeTouches.hasOwnProperty(String(T.identifier))){console.warn("end of an UNKNOWN touch",T);continue}const C=this.activeTouches[T.identifier],E=this.newGestureEvent(l.Change,C.initialTarget);E.translationX=T.pageX-u.tail(C.rollingPageX),E.translationY=T.pageY-u.tail(C.rollingPageY),E.pageX=T.pageX,E.pageY=T.pageY,this.dispatchEvent(E),C.rollingPageX.length>3&&(C.rollingPageX.shift(),C.rollingPageY.shift(),C.rollingTimestamps.shift()),C.rollingPageX.push(T.pageX),C.rollingPageY.push(T.pageY),C.rollingTimestamps.push(m)}this.dispatched&&(a.preventDefault(),a.stopPropagation(),this.dispatched=!1)}};d.SCROLL_FRICTION=-.005,d.HOLD_DELAY=700,d.CLEAR_TAP_COUNT_TIME=400;let o=d;t.Gesture=o,n([r.memoize],o,"isTouchDevice",null)},8801:function(K,t,_){var i=this&&this.__createBinding||(Object.create?function(l,o,d,c){c===void 0&&(c=d);var a=Object.getOwnPropertyDescriptor(o,d);a&&!("get"in a?!o.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return o[d]}}),Object.defineProperty(l,c,a)}:function(l,o,d,c){c===void 0&&(c=d),l[c]=o[d]}),v=this&&this.__setModuleDefault||(Object.create?function(l,o){Object.defineProperty(l,"default",{enumerable:!0,value:o})}:function(l,o){l.default=o}),n=this&&this.__importStar||function(l){if(l&&l.__esModule)return l;var o={};if(l!=null)for(var d in l)d!=="default"&&Object.prototype.hasOwnProperty.call(l,d)&&i(o,l,d);return v(o,l),o};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractScrollbar=void 0;const f=n(_(7093)),g=_(9675),p=_(8328),u=_(8974),r=_(79),h=_(8286),s=n(_(8163));class e extends h.Widget{constructor(o){super(),this._lazyRender=o.lazyRender,this._host=o.host,this._scrollable=o.scrollable,this._scrollByPage=o.scrollByPage,this._scrollbarState=o.scrollbarState,this._visibilityController=this._register(new r.ScrollbarVisibilityController(o.visibility,"visible scrollbar "+o.extraScrollbarClassName,"invisible scrollbar "+o.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new p.GlobalPointerMoveMonitor),this._shouldRender=!0,this.domNode=(0,g.createFastDomNode)(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(f.addDisposableListener(this.domNode.domNode,f.EventType.POINTER_DOWN,(d=>this._domNodePointerDown(d))))}_createArrow(o){const d=this._register(new u.ScrollbarArrow(o));this.domNode.domNode.appendChild(d.bgDomNode),this.domNode.domNode.appendChild(d.domNode)}_createSlider(o,d,c,a){this.slider=(0,g.createFastDomNode)(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(o),this.slider.setLeft(d),typeof c=="number"&&this.slider.setWidth(c),typeof a=="number"&&this.slider.setHeight(a),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(f.addDisposableListener(this.slider.domNode,f.EventType.POINTER_DOWN,(m=>{m.button===0&&(m.preventDefault(),this._sliderPointerDown(m))}))),this.onclick(this.slider.domNode,(m=>{m.leftButton&&m.stopPropagation()}))}_onElementSize(o){return this._scrollbarState.setVisibleSize(o)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(o){return this._scrollbarState.setScrollSize(o)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(o){return this._scrollbarState.setScrollPosition(o)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(o){o.target===this.domNode.domNode&&this._onPointerDown(o)}delegatePointerDown(o){const d=this.domNode.domNode.getClientRects()[0].top,c=d+this._scrollbarState.getSliderPosition(),a=d+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),m=this._sliderPointerPosition(o);c<=m&&m<=a?o.button===0&&(o.preventDefault(),this._sliderPointerDown(o)):this._onPointerDown(o)}_onPointerDown(o){let d,c;if(o.target===this.domNode.domNode&&typeof o.offsetX=="number"&&typeof o.offsetY=="number")d=o.offsetX,c=o.offsetY;else{const m=f.getDomNodePagePosition(this.domNode.domNode);d=o.pageX-m.left,c=o.pageY-m.top}const a=this._pointerDownRelativePosition(d,c);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(a):this._scrollbarState.getDesiredScrollPositionFromOffset(a)),o.button===0&&(o.preventDefault(),this._sliderPointerDown(o))}_sliderPointerDown(o){if(!(o.target&&o.target instanceof Element))return;const d=this._sliderPointerPosition(o),c=this._sliderOrthogonalPointerPosition(o),a=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(o.target,o.pointerId,o.buttons,(m=>{const b=this._sliderOrthogonalPointerPosition(m),R=Math.abs(b-c);if(s.isWindows&&R>140)return void this._setDesiredScrollPositionNow(a.getScrollPosition());const T=this._sliderPointerPosition(m)-d;this._setDesiredScrollPositionNow(a.getDesiredScrollPositionFromDelta(T))}),(()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()})),this._host.onDragStart()}_setDesiredScrollPositionNow(o){const d={};this.writeScrollPosition(d,o),this._scrollable.setScrollPositionNow(d)}updateScrollbarSize(o){this._updateScrollbarSize(o),this._scrollbarState.setScrollbarSize(o),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}}t.AbstractScrollbar=e},151:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HorizontalScrollbar=void 0;const i=_(8801),v=_(8245),n=_(9881);class f extends i.AbstractScrollbar{constructor(p,u,r){const h=p.getScrollDimensions(),s=p.getCurrentScrollPosition();if(super({lazyRender:u.lazyRender,host:r,scrollbarState:new v.ScrollbarState(u.horizontalHasArrows?u.arrowSize:0,u.horizontal===n.ScrollbarVisibility.Hidden?0:u.horizontalScrollbarSize,u.vertical===n.ScrollbarVisibility.Hidden?0:u.verticalScrollbarSize,h.width,h.scrollWidth,s.scrollLeft),visibility:u.horizontal,extraScrollbarClassName:"horizontal",scrollable:p,scrollByPage:u.scrollByPage}),u.horizontalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(Math.floor((u.horizontalScrollbarSize-u.horizontalSliderSize)/2),0,void 0,u.horizontalSliderSize)}_updateSlider(p,u){this.slider.setWidth(p),this.slider.setLeft(u)}_renderDomNode(p,u){this.domNode.setWidth(p),this.domNode.setHeight(u),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(p){return this._shouldRender=this._onElementScrollSize(p.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(p.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(p.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(p,u){return p}_sliderPointerPosition(p){return p.pageX}_sliderOrthogonalPointerPosition(p){return p.pageY}_updateScrollbarSize(p){this.slider.setHeight(p)}writeScrollPosition(p,u){p.scrollLeft=u}updateOptions(p){this.updateScrollbarSize(p.horizontal===n.ScrollbarVisibility.Hidden?0:p.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(p.vertical===n.ScrollbarVisibility.Hidden?0:p.verticalScrollbarSize),this._visibilityController.setVisibility(p.horizontal),this._scrollByPage=p.scrollByPage}}t.HorizontalScrollbar=f},8234:function(K,t,_){var i=this&&this.__createBinding||(Object.create?function(T,C,E,A){A===void 0&&(A=E);var N=Object.getOwnPropertyDescriptor(C,E);N&&!("get"in N?!C.__esModule:N.writable||N.configurable)||(N={enumerable:!0,get:function(){return C[E]}}),Object.defineProperty(T,A,N)}:function(T,C,E,A){A===void 0&&(A=E),T[A]=C[E]}),v=this&&this.__setModuleDefault||(Object.create?function(T,C){Object.defineProperty(T,"default",{enumerable:!0,value:C})}:function(T,C){T.default=C}),n=this&&this.__importStar||function(T){if(T&&T.__esModule)return T;var C={};if(T!=null)for(var E in T)E!=="default"&&Object.prototype.hasOwnProperty.call(T,E)&&i(C,T,E);return v(C,T),C};Object.defineProperty(t,"__esModule",{value:!0}),t.DomScrollableElement=t.SmoothScrollableElement=t.ScrollableElement=t.AbstractScrollableElement=t.MouseWheelClassifier=void 0;const f=_(4333),g=n(_(7093)),p=_(9675),u=_(5964),r=_(151),h=_(5473),s=_(8286),e=_(1758),l=_(802),o=_(7150),d=n(_(8163)),c=_(9881);class a{constructor(C,E,A){this.timestamp=C,this.deltaX=E,this.deltaY=A,this.score=0}}const R=class R{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let C=1,E=0,A=1,N=this._rear;for(;;){const P=N===this._front?C:Math.pow(2,-A);if(C-=P,E+=this._memory[N].score*P,N===this._front)break;N=(this._capacity+N-1)%this._capacity,A++}return E<=.5}acceptStandardWheelEvent(C){if(f.isChrome){const E=g.getWindow(C.browserEvent),A=(0,f.getZoomFactor)(E);this.accept(Date.now(),C.deltaX*A,C.deltaY*A)}else this.accept(Date.now(),C.deltaX,C.deltaY)}accept(C,E,A){let N=null;const P=new a(C,E,A);this._front===-1&&this._rear===-1?(this._memory[0]=P,this._front=0,this._rear=0):(N=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=P),P.score=this._computeScore(P,N)}_computeScore(C,E){if(Math.abs(C.deltaX)>0&&Math.abs(C.deltaY)>0)return 1;let A=.5;if(this._isAlmostInt(C.deltaX)&&this._isAlmostInt(C.deltaY)||(A+=.25),E){const N=Math.abs(C.deltaX),P=Math.abs(C.deltaY),W=Math.abs(E.deltaX),w=Math.abs(E.deltaY),y=Math.max(Math.min(N,W),1),S=Math.max(Math.min(P,w),1),D=Math.max(N,W),M=Math.max(P,w);D%y==0&&M%S==0&&(A-=.5)}return Math.min(Math.max(A,0),1)}_isAlmostInt(C){return Math.abs(Math.round(C)-C)<.01}};R.INSTANCE=new R;let m=R;t.MouseWheelClassifier=m;class b extends s.Widget{get options(){return this._options}constructor(C,E,A){super(),this._onScroll=this._register(new l.Emitter),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new l.Emitter),this.onWillScroll=this._onWillScroll.event,this._options=(function(P){const W={lazyRender:P.lazyRender!==void 0&&P.lazyRender,className:P.className!==void 0?P.className:"",useShadows:P.useShadows===void 0||P.useShadows,handleMouseWheel:P.handleMouseWheel===void 0||P.handleMouseWheel,flipAxes:P.flipAxes!==void 0&&P.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:P.consumeMouseWheelIfScrollbarIsNeeded!==void 0&&P.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:P.alwaysConsumeMouseWheel!==void 0&&P.alwaysConsumeMouseWheel,scrollYToX:P.scrollYToX!==void 0&&P.scrollYToX,mouseWheelScrollSensitivity:P.mouseWheelScrollSensitivity!==void 0?P.mouseWheelScrollSensitivity:1,fastScrollSensitivity:P.fastScrollSensitivity!==void 0?P.fastScrollSensitivity:5,scrollPredominantAxis:P.scrollPredominantAxis===void 0||P.scrollPredominantAxis,mouseWheelSmoothScroll:P.mouseWheelSmoothScroll===void 0||P.mouseWheelSmoothScroll,arrowSize:P.arrowSize!==void 0?P.arrowSize:11,listenOnDomNode:P.listenOnDomNode!==void 0?P.listenOnDomNode:null,horizontal:P.horizontal!==void 0?P.horizontal:c.ScrollbarVisibility.Auto,horizontalScrollbarSize:P.horizontalScrollbarSize!==void 0?P.horizontalScrollbarSize:10,horizontalSliderSize:P.horizontalSliderSize!==void 0?P.horizontalSliderSize:0,horizontalHasArrows:P.horizontalHasArrows!==void 0&&P.horizontalHasArrows,vertical:P.vertical!==void 0?P.vertical:c.ScrollbarVisibility.Auto,verticalScrollbarSize:P.verticalScrollbarSize!==void 0?P.verticalScrollbarSize:10,verticalHasArrows:P.verticalHasArrows!==void 0&&P.verticalHasArrows,verticalSliderSize:P.verticalSliderSize!==void 0?P.verticalSliderSize:0,scrollByPage:P.scrollByPage!==void 0&&P.scrollByPage};return W.horizontalSliderSize=P.horizontalSliderSize!==void 0?P.horizontalSliderSize:W.horizontalScrollbarSize,W.verticalSliderSize=P.verticalSliderSize!==void 0?P.verticalSliderSize:W.verticalScrollbarSize,d.isMacintosh&&(W.className+=" mac"),W})(E),this._scrollable=A,this._register(this._scrollable.onScroll((P=>{this._onWillScroll.fire(P),this._onDidScroll(P),this._onScroll.fire(P)})));const N={onMouseWheel:P=>this._onMouseWheel(P),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new h.VerticalScrollbar(this._scrollable,this._options,N)),this._horizontalScrollbar=this._register(new r.HorizontalScrollbar(this._scrollable,this._options,N)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(C),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=(0,p.createFastDomNode)(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=(0,p.createFastDomNode)(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=(0,p.createFastDomNode)(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,(P=>this._onMouseOver(P))),this.onmouseleave(this._listenOnDomNode,(P=>this._onMouseLeave(P))),this._hideTimeout=this._register(new e.TimeoutTimer),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}dispose(){this._mouseWheelToDispose=(0,o.dispose)(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(C){this._verticalScrollbar.delegatePointerDown(C)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(C){this._scrollable.setScrollDimensions(C,!1)}updateClassName(C){this._options.className=C,d.isMacintosh&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(C){C.handleMouseWheel!==void 0&&(this._options.handleMouseWheel=C.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),C.mouseWheelScrollSensitivity!==void 0&&(this._options.mouseWheelScrollSensitivity=C.mouseWheelScrollSensitivity),C.fastScrollSensitivity!==void 0&&(this._options.fastScrollSensitivity=C.fastScrollSensitivity),C.scrollPredominantAxis!==void 0&&(this._options.scrollPredominantAxis=C.scrollPredominantAxis),C.horizontal!==void 0&&(this._options.horizontal=C.horizontal),C.vertical!==void 0&&(this._options.vertical=C.vertical),C.horizontalScrollbarSize!==void 0&&(this._options.horizontalScrollbarSize=C.horizontalScrollbarSize),C.verticalScrollbarSize!==void 0&&(this._options.verticalScrollbarSize=C.verticalScrollbarSize),C.scrollByPage!==void 0&&(this._options.scrollByPage=C.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(C){this._revealOnScroll=C}delegateScrollFromMouseWheelEvent(C){this._onMouseWheel(new u.StandardWheelEvent(C))}_setListeningToMouseWheel(C){if(this._mouseWheelToDispose.length>0!==C&&(this._mouseWheelToDispose=(0,o.dispose)(this._mouseWheelToDispose),C)){const E=A=>{this._onMouseWheel(new u.StandardWheelEvent(A))};this._mouseWheelToDispose.push(g.addDisposableListener(this._listenOnDomNode,g.EventType.MOUSE_WHEEL,E,{passive:!1}))}}_onMouseWheel(C){var P;if((P=C.browserEvent)!=null&&P.defaultPrevented)return;const E=m.INSTANCE;E.acceptStandardWheelEvent(C);let A=!1;if(C.deltaY||C.deltaX){let W=C.deltaY*this._options.mouseWheelScrollSensitivity,w=C.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&w+W===0?w=W=0:Math.abs(W)>=Math.abs(w)?w=0:W=0),this._options.flipAxes&&([W,w]=[w,W]);const y=!d.isMacintosh&&C.browserEvent&&C.browserEvent.shiftKey;!this._options.scrollYToX&&!y||w||(w=W,W=0),C.browserEvent&&C.browserEvent.altKey&&(w*=this._options.fastScrollSensitivity,W*=this._options.fastScrollSensitivity);const S=this._scrollable.getFutureScrollPosition();let D={};if(W){const M=50*W,I=S.scrollTop-(M<0?Math.floor(M):Math.ceil(M));this._verticalScrollbar.writeScrollPosition(D,I)}if(w){const M=50*w,I=S.scrollLeft-(M<0?Math.floor(M):Math.ceil(M));this._horizontalScrollbar.writeScrollPosition(D,I)}D=this._scrollable.validateScrollPosition(D),(S.scrollLeft!==D.scrollLeft||S.scrollTop!==D.scrollTop)&&(this._options.mouseWheelSmoothScroll&&E.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(D):this._scrollable.setScrollPositionNow(D),A=!0)}let N=A;!N&&this._options.alwaysConsumeMouseWheel&&(N=!0),!N&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(N=!0),N&&(C.preventDefault(),C.stopPropagation())}_onDidScroll(C){this._shouldRender=this._horizontalScrollbar.onDidScroll(C)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(C)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){const C=this._scrollable.getCurrentScrollPosition(),E=C.scrollTop>0,A=C.scrollLeft>0,N=A?" left":"",P=E?" top":"",W=A||E?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${N}`),this._topShadowDomNode.setClassName(`shadow${P}`),this._topLeftShadowDomNode.setClassName(`shadow${W}${P}${N}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(C){this._mouseIsOver=!1,this._hide()}_onMouseOver(C){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){this._mouseIsOver||this._isDragging||(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){this._mouseIsOver||this._isDragging||this._hideTimeout.cancelAndSet((()=>this._hide()),500)}}t.AbstractScrollableElement=b,t.ScrollableElement=class extends b{constructor(T,C){(C=C||{}).mouseWheelSmoothScroll=!1;const E=new c.Scrollable({forceIntegerValues:!0,smoothScrollDuration:0,scheduleAtNextAnimationFrame:A=>g.scheduleAtNextAnimationFrame(g.getWindow(T),A)});super(T,C,E),this._register(E)}setScrollPosition(T){this._scrollable.setScrollPositionNow(T)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}},t.SmoothScrollableElement=class extends b{constructor(T,C,E){super(T,C,E)}setScrollPosition(T){T.reuseAnimation?this._scrollable.setScrollPositionSmooth(T,T.reuseAnimation):this._scrollable.setScrollPositionNow(T)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}},t.DomScrollableElement=class extends b{constructor(T,C){(C=C||{}).mouseWheelSmoothScroll=!1;const E=new c.Scrollable({forceIntegerValues:!1,smoothScrollDuration:0,scheduleAtNextAnimationFrame:A=>g.scheduleAtNextAnimationFrame(g.getWindow(T),A)});super(T,C,E),this._register(E),this._element=T,this._register(this.onScroll((A=>{A.scrollTopChanged&&(this._element.scrollTop=A.scrollTop),A.scrollLeftChanged&&(this._element.scrollLeft=A.scrollLeft)}))),this.scanDomNode()}setScrollPosition(T){this._scrollable.setScrollPositionNow(T)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}scanDomNode(){this.setScrollDimensions({width:this._element.clientWidth,scrollWidth:this._element.scrollWidth,height:this._element.clientHeight,scrollHeight:this._element.scrollHeight}),this.setScrollPosition({scrollLeft:this._element.scrollLeft,scrollTop:this._element.scrollTop})}}},8974:function(K,t,_){var i=this&&this.__createBinding||(Object.create?function(h,s,e,l){l===void 0&&(l=e);var o=Object.getOwnPropertyDescriptor(s,e);o&&!("get"in o?!s.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return s[e]}}),Object.defineProperty(h,l,o)}:function(h,s,e,l){l===void 0&&(l=e),h[l]=s[e]}),v=this&&this.__setModuleDefault||(Object.create?function(h,s){Object.defineProperty(h,"default",{enumerable:!0,value:s})}:function(h,s){h.default=s}),n=this&&this.__importStar||function(h){if(h&&h.__esModule)return h;var s={};if(h!=null)for(var e in h)e!=="default"&&Object.prototype.hasOwnProperty.call(h,e)&&i(s,h,e);return v(s,h),s};Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollbarArrow=t.ARROW_IMG_SIZE=void 0;const f=_(8328),g=_(8286),p=_(1758),u=n(_(7093));t.ARROW_IMG_SIZE=11;class r extends g.Widget{constructor(s){super(),this._onActivate=s.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=s.bgWidth+"px",this.bgDomNode.style.height=s.bgHeight+"px",s.top!==void 0&&(this.bgDomNode.style.top="0px"),s.left!==void 0&&(this.bgDomNode.style.left="0px"),s.bottom!==void 0&&(this.bgDomNode.style.bottom="0px"),s.right!==void 0&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=s.className,this.domNode.style.position="absolute",this.domNode.style.width=t.ARROW_IMG_SIZE+"px",this.domNode.style.height=t.ARROW_IMG_SIZE+"px",s.top!==void 0&&(this.domNode.style.top=s.top+"px"),s.left!==void 0&&(this.domNode.style.left=s.left+"px"),s.bottom!==void 0&&(this.domNode.style.bottom=s.bottom+"px"),s.right!==void 0&&(this.domNode.style.right=s.right+"px"),this._pointerMoveMonitor=this._register(new f.GlobalPointerMoveMonitor),this._register(u.addStandardDisposableListener(this.bgDomNode,u.EventType.POINTER_DOWN,(e=>this._arrowPointerDown(e)))),this._register(u.addStandardDisposableListener(this.domNode,u.EventType.POINTER_DOWN,(e=>this._arrowPointerDown(e)))),this._pointerdownRepeatTimer=this._register(new u.WindowIntervalTimer),this._pointerdownScheduleRepeatTimer=this._register(new p.TimeoutTimer)}_arrowPointerDown(s){s.target&&s.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet((()=>{this._pointerdownRepeatTimer.cancelAndSet((()=>this._onActivate()),41.666666666666664,u.getWindow(s))}),200),this._pointerMoveMonitor.startMonitoring(s.target,s.pointerId,s.buttons,(e=>{}),(()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()})),s.preventDefault())}}t.ScrollbarArrow=r},8245:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollbarState=void 0;class _{constructor(v,n,f,g,p,u){this._scrollbarSize=Math.round(n),this._oppositeScrollbarSize=Math.round(f),this._arrowSize=Math.round(v),this._visibleSize=g,this._scrollSize=p,this._scrollPosition=u,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new _(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(v){const n=Math.round(v);return this._visibleSize!==n&&(this._visibleSize=n,this._refreshComputedValues(),!0)}setScrollSize(v){const n=Math.round(v);return this._scrollSize!==n&&(this._scrollSize=n,this._refreshComputedValues(),!0)}setScrollPosition(v){const n=Math.round(v);return this._scrollPosition!==n&&(this._scrollPosition=n,this._refreshComputedValues(),!0)}setScrollbarSize(v){this._scrollbarSize=Math.round(v)}setOppositeScrollbarSize(v){this._oppositeScrollbarSize=Math.round(v)}static _computeValues(v,n,f,g,p){const u=Math.max(0,f-v),r=Math.max(0,u-2*n),h=g>0&&g>f;if(!h)return{computedAvailableSize:Math.round(u),computedIsNeeded:h,computedSliderSize:Math.round(r),computedSliderRatio:0,computedSliderPosition:0};const s=Math.round(Math.max(20,Math.floor(f*r/g))),e=(r-s)/(g-f),l=p*e;return{computedAvailableSize:Math.round(u),computedIsNeeded:h,computedSliderSize:Math.round(s),computedSliderRatio:e,computedSliderPosition:Math.round(l)}}_refreshComputedValues(){const v=_._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=v.computedAvailableSize,this._computedIsNeeded=v.computedIsNeeded,this._computedSliderSize=v.computedSliderSize,this._computedSliderRatio=v.computedSliderRatio,this._computedSliderPosition=v.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(v){if(!this._computedIsNeeded)return 0;const n=v-this._arrowSize-this._computedSliderSize/2;return Math.round(n/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(v){if(!this._computedIsNeeded)return 0;const n=v-this._arrowSize;let f=this._scrollPosition;return n<this._computedSliderPosition?f-=this._visibleSize:f+=this._visibleSize,f}getDesiredScrollPositionFromDelta(v){if(!this._computedIsNeeded)return 0;const n=this._computedSliderPosition+v;return Math.round(n/this._computedSliderRatio)}}t.ScrollbarState=_},79:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollbarVisibilityController=void 0;const i=_(1758),v=_(7150),n=_(9881);class f extends v.Disposable{constructor(p,u,r){super(),this._visibility=p,this._visibleClassName=u,this._invisibleClassName=r,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new i.TimeoutTimer)}setVisibility(p){this._visibility!==p&&(this._visibility=p,this._updateShouldBeVisible())}setShouldBeVisible(p){this._rawShouldBeVisible=p,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility!==n.ScrollbarVisibility.Hidden&&(this._visibility===n.ScrollbarVisibility.Visible||this._rawShouldBeVisible)}_updateShouldBeVisible(){const p=this._applyVisibilitySetting();this._shouldBeVisible!==p&&(this._shouldBeVisible=p,this.ensureVisibility())}setIsNeeded(p){this._isNeeded!==p&&(this._isNeeded=p,this.ensureVisibility())}setDomNode(p){this._domNode=p,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet((()=>{var p;(p=this._domNode)==null||p.setClassName(this._visibleClassName)}),0))}_hide(p){var u;this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,(u=this._domNode)==null||u.setClassName(this._invisibleClassName+(p?" fade":"")))}}t.ScrollbarVisibilityController=f},5473:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.VerticalScrollbar=void 0;const i=_(8801),v=_(8245),n=_(9881);class f extends i.AbstractScrollbar{constructor(p,u,r){const h=p.getScrollDimensions(),s=p.getCurrentScrollPosition();if(super({lazyRender:u.lazyRender,host:r,scrollbarState:new v.ScrollbarState(u.verticalHasArrows?u.arrowSize:0,u.vertical===n.ScrollbarVisibility.Hidden?0:u.verticalScrollbarSize,0,h.height,h.scrollHeight,s.scrollTop),visibility:u.vertical,extraScrollbarClassName:"vertical",scrollable:p,scrollByPage:u.scrollByPage}),u.verticalHasArrows)throw new Error("horizontalHasArrows is not supported in xterm.js");this._createSlider(0,Math.floor((u.verticalScrollbarSize-u.verticalSliderSize)/2),u.verticalSliderSize,void 0)}_updateSlider(p,u){this.slider.setHeight(p),this.slider.setTop(u)}_renderDomNode(p,u){this.domNode.setWidth(u),this.domNode.setHeight(p),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(p){return this._shouldRender=this._onElementScrollSize(p.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(p.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(p.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(p,u){return u}_sliderPointerPosition(p){return p.pageY}_sliderOrthogonalPointerPosition(p){return p.pageX}_updateScrollbarSize(p){this.slider.setWidth(p)}writeScrollPosition(p,u){p.scrollTop=u}updateOptions(p){this.updateScrollbarSize(p.vertical===n.ScrollbarVisibility.Hidden?0:p.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(p.vertical),this._scrollByPage=p.scrollByPage}}t.VerticalScrollbar=f},8286:function(K,t,_){var i=this&&this.__createBinding||(Object.create?function(s,e,l,o){o===void 0&&(o=l);var d=Object.getOwnPropertyDescriptor(e,l);d&&!("get"in d?!e.__esModule:d.writable||d.configurable)||(d={enumerable:!0,get:function(){return e[l]}}),Object.defineProperty(s,o,d)}:function(s,e,l,o){o===void 0&&(o=l),s[o]=e[l]}),v=this&&this.__setModuleDefault||(Object.create?function(s,e){Object.defineProperty(s,"default",{enumerable:!0,value:e})}:function(s,e){s.default=e}),n=this&&this.__importStar||function(s){if(s&&s.__esModule)return s;var e={};if(s!=null)for(var l in s)l!=="default"&&Object.prototype.hasOwnProperty.call(s,l)&&i(e,s,l);return v(e,s),e};Object.defineProperty(t,"__esModule",{value:!0}),t.Widget=void 0;const f=n(_(7093)),g=_(5394),p=_(5964),u=_(8594),r=_(7150);class h extends r.Disposable{onclick(e,l){this._register(f.addDisposableListener(e,f.EventType.CLICK,(o=>l(new p.StandardMouseEvent(f.getWindow(e),o)))))}onmousedown(e,l){this._register(f.addDisposableListener(e,f.EventType.MOUSE_DOWN,(o=>l(new p.StandardMouseEvent(f.getWindow(e),o)))))}onmouseover(e,l){this._register(f.addDisposableListener(e,f.EventType.MOUSE_OVER,(o=>l(new p.StandardMouseEvent(f.getWindow(e),o)))))}onmouseleave(e,l){this._register(f.addDisposableListener(e,f.EventType.MOUSE_LEAVE,(o=>l(new p.StandardMouseEvent(f.getWindow(e),o)))))}onkeydown(e,l){this._register(f.addDisposableListener(e,f.EventType.KEY_DOWN,(o=>l(new g.StandardKeyboardEvent(o)))))}onkeyup(e,l){this._register(f.addDisposableListener(e,f.EventType.KEY_UP,(o=>l(new g.StandardKeyboardEvent(o)))))}oninput(e,l){this._register(f.addDisposableListener(e,f.EventType.INPUT,l))}onblur(e,l){this._register(f.addDisposableListener(e,f.EventType.BLUR,l))}onfocus(e,l){this._register(f.addDisposableListener(e,f.EventType.FOCUS,l))}onchange(e,l){this._register(f.addDisposableListener(e,f.EventType.CHANGE,l))}ignoreGesture(e){return u.Gesture.ignoreTarget(e)}}t.Widget=h},4693:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mainWindow=void 0,t.ensureCodeWindow=function(_,i){},t.mainWindow=typeof window=="object"?window:globalThis},3058:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Permutation=t.CallbackIterable=t.ArrayQueue=t.booleanComparator=t.numberComparator=t.CompareResult=void 0,t.tail=function(o,d=0){return o[o.length-(1+d)]},t.tail2=function(o){if(o.length===0)throw new Error("Invalid tail call");return[o.slice(0,o.length-1),o[o.length-1]]},t.equals=function(o,d,c=(a,m)=>a===m){if(o===d)return!0;if(!o||!d||o.length!==d.length)return!1;for(let a=0,m=o.length;a<m;a++)if(!c(o[a],d[a]))return!1;return!0},t.removeFastWithoutKeepingOrder=function(o,d){const c=o.length-1;d<c&&(o[d]=o[c]),o.pop()},t.binarySearch=function(o,d,c){return n(o.length,(a=>c(o[a],d)))},t.binarySearch2=n,t.quickSelect=function o(d,c,a){if((d|=0)>=c.length)throw new TypeError("invalid index");const m=c[Math.floor(c.length*Math.random())],b=[],R=[],T=[];for(const C of c){const E=a(C,m);E<0?b.push(C):E>0?R.push(C):T.push(C)}return d<b.length?o(d,b,a):d<b.length+T.length?T[0]:o(d-(b.length+T.length),R,a)},t.groupBy=function(o,d){const c=[];let a;for(const m of o.slice(0).sort(d))a&&d(a[0],m)===0?a.push(m):(a=[m],c.push(a));return c},t.groupAdjacentBy=function*(o,d){let c,a;for(const m of o)a!==void 0&&d(a,m)?c.push(m):(c&&(yield c),c=[m]),a=m;c&&(yield c)},t.forEachAdjacent=function(o,d){for(let c=0;c<=o.length;c++)d(c===0?void 0:o[c-1],c===o.length?void 0:o[c])},t.forEachWithNeighbors=function(o,d){for(let c=0;c<o.length;c++)d(c===0?void 0:o[c-1],o[c],c+1===o.length?void 0:o[c+1])},t.sortedDiff=f,t.delta=function(o,d,c){const a=f(o,d,c),m=[],b=[];for(const R of a)m.push(...o.slice(R.start,R.start+R.deleteCount)),b.push(...R.toInsert);return{removed:m,added:b}},t.top=function(o,d,c){if(c===0)return[];const a=o.slice(0,c).sort(d);return g(o,d,a,c,o.length),a},t.topAsync=function(o,d,c,a,m){return c===0?Promise.resolve([]):new Promise(((b,R)=>{(async()=>{const T=o.length,C=o.slice(0,c).sort(d);for(let E=c,A=Math.min(c+a,T);E<T;E=A,A=Math.min(A+a,T)){if(E>c&&await new Promise((N=>setTimeout(N))),m&&m.isCancellationRequested)throw new i.CancellationError;g(o,d,C,E,A)}return C})().then(b,R)}))},t.coalesce=function(o){return o.filter((d=>!!d))},t.coalesceInPlace=function(o){let d=0;for(let c=0;c<o.length;c++)o[c]&&(o[d]=o[c],d+=1);o.length=d},t.move=function(o,d,c){o.splice(c,0,o.splice(d,1)[0])},t.isFalsyOrEmpty=function(o){return!Array.isArray(o)||o.length===0},t.isNonEmptyArray=function(o){return Array.isArray(o)&&o.length>0},t.distinct=function(o,d=c=>c){const c=new Set;return o.filter((a=>{const m=d(a);return!c.has(m)&&(c.add(m),!0)}))},t.uniqueFilter=function(o){const d=new Set;return c=>{const a=o(c);return!d.has(a)&&(d.add(a),!0)}},t.firstOrDefault=function(o,d){return o.length>0?o[0]:d},t.lastOrDefault=function(o,d){return o.length>0?o[o.length-1]:d},t.commonPrefixLength=function(o,d,c=(a,m)=>a===m){let a=0;for(let m=0,b=Math.min(o.length,d.length);m<b&&c(o[m],d[m]);m++)a++;return a},t.range=function(o,d){let c=typeof d=="number"?o:0;typeof d=="number"?c=o:(c=0,d=o);const a=[];if(c<=d)for(let m=c;m<d;m++)a.push(m);else for(let m=c;m>d;m--)a.push(m);return a},t.index=function(o,d,c){return o.reduce(((a,m)=>(a[d(m)]=c?c(m):m,a)),Object.create(null))},t.insert=function(o,d){return o.push(d),()=>p(o,d)},t.remove=p,t.arrayInsert=function(o,d,c){const a=o.slice(0,d),m=o.slice(d);return a.concat(c,m)},t.shuffle=function(o,d){let c;if(typeof d=="number"){let a=d;c=()=>{const m=179426549*Math.sin(a++);return m-Math.floor(m)}}else c=Math.random;for(let a=o.length-1;a>0;a-=1){const m=Math.floor(c()*(a+1)),b=o[a];o[a]=o[m],o[m]=b}},t.pushToStart=function(o,d){const c=o.indexOf(d);c>-1&&(o.splice(c,1),o.unshift(d))},t.pushToEnd=function(o,d){const c=o.indexOf(d);c>-1&&(o.splice(c,1),o.push(d))},t.pushMany=function(o,d){for(const c of d)o.push(c)},t.mapArrayOrNot=function(o,d){return Array.isArray(o)?o.map(d):d(o)},t.asArray=function(o){return Array.isArray(o)?o:[o]},t.getRandomElement=function(o){return o[Math.floor(Math.random()*o.length)]},t.insertInto=u,t.splice=function(o,d,c,a){const m=r(o,d);let b=o.splice(m,c);return b===void 0&&(b=[]),u(o,m,a),b},t.compareBy=function(o,d){return(c,a)=>d(o(c),o(a))},t.tieBreakComparators=function(...o){return(d,c)=>{for(const a of o){const m=a(d,c);if(!h.isNeitherLessOrGreaterThan(m))return m}return h.neitherLessOrGreaterThan}},t.reverseOrder=function(o){return(d,c)=>-o(d,c)};const i=_(9807),v=_(8297);function n(o,d){let c=0,a=o-1;for(;c<=a;){const m=(c+a)/2|0,b=d(m);if(b<0)c=m+1;else{if(!(b>0))return m;a=m-1}}return-(c+1)}function f(o,d,c){const a=[];function m(T,C,E){if(C===0&&E.length===0)return;const A=a[a.length-1];A&&A.start+A.deleteCount===T?(A.deleteCount+=C,A.toInsert.push(...E)):a.push({start:T,deleteCount:C,toInsert:E})}let b=0,R=0;for(;;){if(b===o.length){m(b,0,d.slice(R));break}if(R===d.length){m(b,o.length-b,[]);break}const T=o[b],C=d[R],E=c(T,C);E===0?(b+=1,R+=1):E<0?(m(b,1,[]),b+=1):E>0&&(m(b,0,[C]),R+=1)}return a}function g(o,d,c,a,m){for(const b=c.length;a<m;a++){const R=o[a];if(d(R,c[b-1])<0){c.pop();const T=(0,v.findFirstIdxMonotonousOrArrLen)(c,(C=>d(R,C)<0));c.splice(T,0,R)}}}function p(o,d){const c=o.indexOf(d);if(c>-1)return o.splice(c,1),d}function u(o,d,c){const a=r(o,d),m=o.length,b=c.length;o.length=m+b;for(let R=m-1;R>=a;R--)o[R+b]=o[R];for(let R=0;R<b;R++)o[R+a]=c[R]}function r(o,d){return d<0?Math.max(d+o.length,0):Math.min(d,o.length)}var h;(function(o){o.isLessThan=function(d){return d<0},o.isLessThanOrEqual=function(d){return d<=0},o.isGreaterThan=function(d){return d>0},o.isNeitherLessOrGreaterThan=function(d){return d===0},o.greaterThan=1,o.lessThan=-1,o.neitherLessOrGreaterThan=0})(h||(t.CompareResult=h={})),t.numberComparator=(o,d)=>o-d,t.booleanComparator=(o,d)=>(0,t.numberComparator)(o?1:0,d?1:0),t.ArrayQueue=class{constructor(o){this.items=o,this.firstIdx=0,this.lastIdx=this.items.length-1}get length(){return this.lastIdx-this.firstIdx+1}takeWhile(o){let d=this.firstIdx;for(;d<this.items.length&&o(this.items[d]);)d++;const c=d===this.firstIdx?null:this.items.slice(this.firstIdx,d);return this.firstIdx=d,c}takeFromEndWhile(o){let d=this.lastIdx;for(;d>=0&&o(this.items[d]);)d--;const c=d===this.lastIdx?null:this.items.slice(d+1,this.lastIdx+1);return this.lastIdx=d,c}peek(){if(this.length!==0)return this.items[this.firstIdx]}peekLast(){if(this.length!==0)return this.items[this.lastIdx]}dequeue(){const o=this.items[this.firstIdx];return this.firstIdx++,o}removeLast(){const o=this.items[this.lastIdx];return this.lastIdx--,o}takeCount(o){const d=this.items.slice(this.firstIdx,this.firstIdx+o);return this.firstIdx+=o,d}};const l=class l{constructor(d){this.iterate=d}forEach(d){this.iterate((c=>(d(c),!0)))}toArray(){const d=[];return this.iterate((c=>(d.push(c),!0))),d}filter(d){return new l((c=>this.iterate((a=>!d(a)||c(a)))))}map(d){return new l((c=>this.iterate((a=>c(d(a))))))}some(d){let c=!1;return this.iterate((a=>(c=d(a),!c))),c}findFirst(d){let c;return this.iterate((a=>!d(a)||(c=a,!1))),c}findLast(d){let c;return this.iterate((a=>(d(a)&&(c=a),!0))),c}findLastMaxBy(d){let c,a=!0;return this.iterate((m=>((a||h.isGreaterThan(d(m,c)))&&(a=!1,c=m),!0))),c}};l.empty=new l((d=>{}));let s=l;t.CallbackIterable=s;class e{constructor(d){this._indexMap=d}static createSortPermutation(d,c){const a=Array.from(d.keys()).sort(((m,b)=>c(d[m],d[b])));return new e(a)}apply(d){return d.map(((c,a)=>d[this._indexMap[a]]))}inverse(){const d=this._indexMap.slice();for(let c=0;c<this._indexMap.length;c++)d[this._indexMap[c]]=c;return new e(d)}}t.Permutation=e},8297:(K,t)=>{function _(p,u,r=p.length-1){for(let h=r;h>=0;h--)if(u(p[h]))return h;return-1}function i(p,u,r=0,h=p.length){let s=r,e=h;for(;s<e;){const l=Math.floor((s+e)/2);u(p[l])?s=l+1:e=l}return s-1}function v(p,u,r=0,h=p.length){let s=r,e=h;for(;s<e;){const l=Math.floor((s+e)/2);u(p[l])?e=l:s=l+1}return s}Object.defineProperty(t,"__esModule",{value:!0}),t.MonotonousArray=void 0,t.findLast=function(p,u){const r=_(p,u);if(r!==-1)return p[r]},t.findLastIdx=_,t.findLastMonotonous=function(p,u){const r=i(p,u);return r===-1?void 0:p[r]},t.findLastIdxMonotonous=i,t.findFirstMonotonous=function(p,u){const r=v(p,u);return r===p.length?void 0:p[r]},t.findFirstIdxMonotonousOrArrLen=v,t.findFirstIdxMonotonous=function(p,u,r=0,h=p.length){const s=v(p,u,r,h);return s===p.length?-1:s},t.findFirstMax=f,t.findLastMax=function(p,u){if(p.length===0)return;let r=p[0];for(let h=1;h<p.length;h++){const s=p[h];u(s,r)>=0&&(r=s)}return r},t.findFirstMin=function(p,u){return f(p,((r,h)=>-u(r,h)))},t.findMaxIdx=function(p,u){if(p.length===0)return-1;let r=0;for(let h=1;h<p.length;h++)u(p[h],p[r])>0&&(r=h);return r},t.mapFindFirst=function(p,u){for(const r of p){const h=u(r);if(h!==void 0)return h}};const g=class g{constructor(u){this._array=u,this._findLastMonotonousLastIdx=0}findLastMonotonous(u){if(g.assertInvariants){if(this._prevFindLastPredicate){for(const h of this._array)if(this._prevFindLastPredicate(h)&&!u(h))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=u}const r=i(this._array,u,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=r+1,r===-1?void 0:this._array[r]}};g.assertInvariants=!1;let n=g;function f(p,u){if(p.length===0)return;let r=p[0];for(let h=1;h<p.length;h++){const s=p[h];u(s,r)>0&&(r=s)}return r}t.MonotonousArray=n},1758:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AsyncIterableSource=t.CancelableAsyncIterableObject=t.AsyncIterableObject=t.LazyStatefulPromise=t.StatefulPromise=t.Promises=t.DeferredPromise=t.IntervalCounter=t.TaskSequentializer=t.GlobalIdleValue=t.AbstractIdleValue=t._runWhenIdle=t.runWhenGlobalIdle=t.ThrottledWorker=t.RunOnceWorker=t.ProcessTimeRunOnceScheduler=t.RunOnceScheduler=t.IntervalTimer=t.TimeoutTimer=t.LimitedQueue=t.Queue=t.Limiter=t.AutoOpenBarrier=t.Barrier=t.ThrottledDelayer=t.Delayer=t.SequencerByKey=t.Sequencer=t.Throttler=void 0,t.isThenable=r,t.createCancelablePromise=h,t.raceCancellation=function(y,S,D){return new Promise(((M,I)=>{const F=S.onCancellationRequested((()=>{F.dispose(),M(D)}));y.then(M,I).finally((()=>F.dispose()))}))},t.raceCancellationError=function(y,S){return new Promise(((D,M)=>{const I=S.onCancellationRequested((()=>{I.dispose(),M(new v.CancellationError)}));y.then(D,M).finally((()=>I.dispose()))}))},t.raceCancellablePromises=async function(y){let S=-1;const D=y.map(((M,I)=>M.then((F=>(S=I,F)))));try{return await Promise.race(D)}finally{y.forEach(((M,I)=>{I!==S&&M.cancel()}))}},t.raceTimeout=function(y,S,D){let M;const I=setTimeout((()=>{M==null||M(void 0),D==null||D()}),S);return Promise.race([y.finally((()=>clearTimeout(I))),new Promise((F=>M=F))])},t.asPromise=function(y){return new Promise(((S,D)=>{const M=y();r(M)?M.then(S,D):S(M)}))},t.promiseWithResolvers=s,t.timeout=d,t.disposableTimeout=function(y,S=0,D){const M=setTimeout((()=>{y(),D&&I.dispose()}),S),I=(0,f.toDisposable)((()=>{clearTimeout(M),D==null||D.deleteAndLeak(I)}));return D==null||D.add(I),I},t.sequence=function(y){const S=[];let D=0;const M=y.length;return Promise.resolve(null).then((function I(F){F!=null&&S.push(F);const H=D<M?y[D++]():null;return H?H.then(I):Promise.resolve(S)}))},t.first=function(y,S=M=>!!M,D=null){let M=0;const I=y.length,F=()=>{if(M>=I)return Promise.resolve(D);const H=y[M++];return Promise.resolve(H()).then((B=>S(B)?Promise.resolve(B):F()))};return F()},t.firstParallel=function(y,S=M=>!!M,D=null){if(y.length===0)return Promise.resolve(D);let M=y.length;const I=()=>{var F;M=-1;for(const H of y)(F=H.cancel)==null||F.call(H)};return new Promise(((F,H)=>{for(const B of y)B.then((k=>{--M>=0&&S(k)?(I(),F(k)):M===0&&F(D)})).catch((k=>{--M>=0&&(I(),H(k))}))}))},t.retry=async function(y,S,D){let M;for(let I=0;I<D;I++)try{return await y()}catch(F){M=F,await d(S)}throw M},t.createCancelableAsyncIterable=function(y){const S=new i.CancellationTokenSource,D=y(S.token);return new W(S,(async M=>{const I=S.token.onCancellationRequested((()=>{I.dispose(),S.dispose(),M.reject(new v.CancellationError)}));try{for await(const F of D){if(S.token.isCancellationRequested)return;M.emitOne(F)}I.dispose(),S.dispose()}catch(F){I.dispose(),S.dispose(),M.reject(F)}}))};const i=_(8447),v=_(9807),n=_(802),f=_(7150),g=_(8163),p=_(5015),u=_(626);function r(y){return!!y&&typeof y.then=="function"}function h(y){const S=new i.CancellationTokenSource,D=y(S.token),M=new Promise(((I,F)=>{const H=S.token.onCancellationRequested((()=>{H.dispose(),F(new v.CancellationError)}));Promise.resolve(D).then((B=>{H.dispose(),S.dispose(),I(B)}),(B=>{H.dispose(),S.dispose(),F(B)}))}));return new class{cancel(){S.cancel(),S.dispose()}then(I,F){return M.then(I,F)}catch(I){return this.then(void 0,I)}finally(I){return M.finally(I)}}}function s(){let y,S;return{promise:new Promise(((D,M)=>{y=D,S=M})),resolve:y,reject:S}}class e{constructor(){this.isDisposed=!1,this.activePromise=null,this.queuedPromise=null,this.queuedPromiseFactory=null}queue(S){if(this.isDisposed)return Promise.reject(new Error("Throttler is disposed"));if(this.activePromise){if(this.queuedPromiseFactory=S,!this.queuedPromise){const D=()=>{if(this.queuedPromise=null,this.isDisposed)return;const M=this.queue(this.queuedPromiseFactory);return this.queuedPromiseFactory=null,M};this.queuedPromise=new Promise((M=>{this.activePromise.then(D,D).then(M)}))}return new Promise(((D,M)=>{this.queuedPromise.then(D,M)}))}return this.activePromise=S(),new Promise(((D,M)=>{this.activePromise.then((I=>{this.activePromise=null,D(I)}),(I=>{this.activePromise=null,M(I)}))}))}dispose(){this.isDisposed=!0}}t.Throttler=e,t.Sequencer=class{constructor(){this.current=Promise.resolve(null)}queue(y){return this.current=this.current.then((()=>y()),(()=>y()))}},t.SequencerByKey=class{constructor(){this.promiseMap=new Map}queue(y,S){const D=(this.promiseMap.get(y)??Promise.resolve()).catch((()=>{})).then(S).finally((()=>{this.promiseMap.get(y)===D&&this.promiseMap.delete(y)}));return this.promiseMap.set(y,D),D}};class l{constructor(S){this.defaultDelay=S,this.deferred=null,this.completionPromise=null,this.doResolve=null,this.doReject=null,this.task=null}trigger(S,D=this.defaultDelay){this.task=S,this.cancelTimeout(),this.completionPromise||(this.completionPromise=new Promise(((I,F)=>{this.doResolve=I,this.doReject=F})).then((()=>{if(this.completionPromise=null,this.doResolve=null,this.task){const I=this.task;return this.task=null,I()}})));const M=()=>{var I;this.deferred=null,(I=this.doResolve)==null||I.call(this,null)};return this.deferred=D===p.MicrotaskDelay?(I=>{let F=!0;return queueMicrotask((()=>{F&&(F=!1,I())})),{isTriggered:()=>F,dispose:()=>{F=!1}}})(M):((I,F)=>{let H=!0;const B=setTimeout((()=>{H=!1,F()}),I);return{isTriggered:()=>H,dispose:()=>{clearTimeout(B),H=!1}}})(D,M),this.completionPromise}isTriggered(){var S;return!!((S=this.deferred)!=null&&S.isTriggered())}cancel(){var S;this.cancelTimeout(),this.completionPromise&&((S=this.doReject)==null||S.call(this,new v.CancellationError),this.completionPromise=null)}cancelTimeout(){var S;(S=this.deferred)==null||S.dispose(),this.deferred=null}dispose(){this.cancel()}}t.Delayer=l,t.ThrottledDelayer=class{constructor(y){this.delayer=new l(y),this.throttler=new e}trigger(y,S){return this.delayer.trigger((()=>this.throttler.queue(y)),S)}isTriggered(){return this.delayer.isTriggered()}cancel(){this.delayer.cancel()}dispose(){this.delayer.dispose(),this.throttler.dispose()}};class o{constructor(){this._isOpen=!1,this._promise=new Promise(((S,D)=>{this._completePromise=S}))}isOpen(){return this._isOpen}open(){this._isOpen=!0,this._completePromise(!0)}wait(){return this._promise}}function d(y,S){return S?new Promise(((D,M)=>{const I=setTimeout((()=>{F.dispose(),D()}),y),F=S.onCancellationRequested((()=>{clearTimeout(I),F.dispose(),M(new v.CancellationError)}))})):h((D=>d(y,D)))}t.Barrier=o,t.AutoOpenBarrier=class extends o{constructor(y){super(),this._timeout=setTimeout((()=>this.open()),y)}open(){clearTimeout(this._timeout),super.open()}};class c{constructor(S){this._size=0,this._isDisposed=!1,this.maxDegreeOfParalellism=S,this.outstandingPromises=[],this.runningPromises=0,this._onDrained=new n.Emitter}whenIdle(){return this.size>0?n.Event.toPromise(this.onDrained):Promise.resolve()}get onDrained(){return this._onDrained.event}get size(){return this._size}queue(S){if(this._isDisposed)throw new Error("Object has been disposed");return this._size++,new Promise(((D,M)=>{this.outstandingPromises.push({factory:S,c:D,e:M}),this.consume()}))}consume(){for(;this.outstandingPromises.length&&this.runningPromises<this.maxDegreeOfParalellism;){const S=this.outstandingPromises.shift();this.runningPromises++;const D=S.factory();D.then(S.c,S.e),D.then((()=>this.consumed()),(()=>this.consumed()))}}consumed(){this._isDisposed||(this.runningPromises--,--this._size==0&&this._onDrained.fire(),this.outstandingPromises.length>0&&this.consume())}clear(){if(this._isDisposed)throw new Error("Object has been disposed");this.outstandingPromises.length=0,this._size=this.runningPromises}dispose(){this._isDisposed=!0,this.outstandingPromises.length=0,this._size=0,this._onDrained.dispose()}}t.Limiter=c,t.Queue=class extends c{constructor(){super(1)}},t.LimitedQueue=class{constructor(){this.sequentializer=new R,this.tasks=0}queue(y){return this.sequentializer.isRunning()?this.sequentializer.queue((()=>this.sequentializer.run(this.tasks++,y()))):this.sequentializer.run(this.tasks++,y())}},t.TimeoutTimer=class{constructor(y,S){this._isDisposed=!1,this._token=-1,typeof y=="function"&&typeof S=="number"&&this.setIfNotSet(y,S)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(y,S){if(this._isDisposed)throw new v.BugIndicatingError("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout((()=>{this._token=-1,y()}),S)}setIfNotSet(y,S){if(this._isDisposed)throw new v.BugIndicatingError("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout((()=>{this._token=-1,y()}),S))}},t.IntervalTimer=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){var y;(y=this.disposable)==null||y.dispose(),this.disposable=void 0}cancelAndSet(y,S,D=globalThis){if(this.isDisposed)throw new v.BugIndicatingError("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();const M=D.setInterval((()=>{y()}),S);this.disposable=(0,f.toDisposable)((()=>{D.clearInterval(M),this.disposable=void 0}))}dispose(){this.cancel(),this.isDisposed=!0}};class a{constructor(S,D){this.timeoutToken=-1,this.runner=S,this.timeout=D,this.timeoutHandler=this.onTimeout.bind(this)}dispose(){this.cancel(),this.runner=null}cancel(){this.isScheduled()&&(clearTimeout(this.timeoutToken),this.timeoutToken=-1)}schedule(S=this.timeout){this.cancel(),this.timeoutToken=setTimeout(this.timeoutHandler,S)}get delay(){return this.timeout}set delay(S){this.timeout=S}isScheduled(){return this.timeoutToken!==-1}flush(){this.isScheduled()&&(this.cancel(),this.doRun())}onTimeout(){this.timeoutToken=-1,this.runner&&this.doRun()}doRun(){var S;(S=this.runner)==null||S.call(this)}}t.RunOnceScheduler=a,t.ProcessTimeRunOnceScheduler=class{constructor(y,S){S%1e3!=0&&console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${S}ms is not a multiple of 1000ms.`),this.runner=y,this.timeout=S,this.counter=0,this.intervalToken=-1,this.intervalHandler=this.onInterval.bind(this)}dispose(){this.cancel(),this.runner=null}cancel(){this.isScheduled()&&(clearInterval(this.intervalToken),this.intervalToken=-1)}schedule(y=this.timeout){y%1e3!=0&&console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${y}ms is not a multiple of 1000ms.`),this.cancel(),this.counter=Math.ceil(y/1e3),this.intervalToken=setInterval(this.intervalHandler,1e3)}isScheduled(){return this.intervalToken!==-1}onInterval(){var y;this.counter--,this.counter>0||(clearInterval(this.intervalToken),this.intervalToken=-1,(y=this.runner)==null||y.call(this))}},t.RunOnceWorker=class extends a{constructor(y,S){super(y,S),this.units=[]}work(y){this.units.push(y),this.isScheduled()||this.schedule()}doRun(){var S;const y=this.units;this.units=[],(S=this.runner)==null||S.call(this,y)}dispose(){this.units=[],super.dispose()}};class m extends f.Disposable{constructor(S,D){super(),this.options=S,this.handler=D,this.pendingWork=[],this.throttler=this._register(new f.MutableDisposable),this.disposed=!1}get pending(){return this.pendingWork.length}work(S){if(this.disposed)return!1;if(typeof this.options.maxBufferedWork=="number"){if(this.throttler.value){if(this.pending+S.length>this.options.maxBufferedWork)return!1}else if(this.pending+S.length-this.options.maxWorkChunkSize>this.options.maxBufferedWork)return!1}for(const D of S)this.pendingWork.push(D);return this.throttler.value||this.doWork(),!0}doWork(){this.handler(this.pendingWork.splice(0,this.options.maxWorkChunkSize)),this.pendingWork.length>0&&(this.throttler.value=new a((()=>{this.throttler.clear(),this.doWork()}),this.options.throttleDelay),this.throttler.value.schedule())}dispose(){super.dispose(),this.disposed=!0}}t.ThrottledWorker=m,typeof globalThis.requestIdleCallback!="function"||typeof globalThis.cancelIdleCallback!="function"?t._runWhenIdle=(y,S)=>{(0,g.setTimeout0)((()=>{if(D)return;const M=Date.now()+15;S(Object.freeze({didTimeout:!0,timeRemaining:()=>Math.max(0,M-Date.now())}))}));let D=!1;return{dispose(){D||(D=!0)}}}:t._runWhenIdle=(y,S,D)=>{const M=y.requestIdleCallback(S,typeof D=="number"?{timeout:D}:void 0);let I=!1;return{dispose(){I||(I=!0,y.cancelIdleCallback(M))}}},t.runWhenGlobalIdle=y=>(0,t._runWhenIdle)(globalThis,y);class b{constructor(S,D){this._didRun=!1,this._executor=()=>{try{this._value=D()}catch(M){this._error=M}finally{this._didRun=!0}},this._handle=(0,t._runWhenIdle)(S,(()=>this._executor()))}dispose(){this._handle.dispose()}get value(){if(this._didRun||(this._handle.dispose(),this._executor()),this._error)throw this._error;return this._value}get isInitialized(){return this._didRun}}t.AbstractIdleValue=b,t.GlobalIdleValue=class extends b{constructor(y){super(globalThis,y)}};class R{isRunning(S){var D;return typeof S=="number"?((D=this._running)==null?void 0:D.taskId)===S:!!this._running}get running(){var S;return(S=this._running)==null?void 0:S.promise}cancelRunning(){var S;(S=this._running)==null||S.cancel()}run(S,D,M){return this._running={taskId:S,cancel:()=>M==null?void 0:M(),promise:D},D.then((()=>this.doneRunning(S)),(()=>this.doneRunning(S))),D}doneRunning(S){this._running&&S===this._running.taskId&&(this._running=void 0,this.runQueued())}runQueued(){if(this._queued){const S=this._queued;this._queued=void 0,S.run().then(S.promiseResolve,S.promiseReject)}}queue(S){if(this._queued)this._queued.run=S;else{const{promise:D,resolve:M,reject:I}=s();this._queued={run:S,promise:D,promiseResolve:M,promiseReject:I}}return this._queued.promise}hasQueued(){return!!this._queued}async join(){var S,D;return((S=this._queued)==null?void 0:S.promise)??((D=this._running)==null?void 0:D.promise)}}var T,C,E;t.TaskSequentializer=R,t.IntervalCounter=class{constructor(y,S=()=>Date.now()){this.interval=y,this.nowFn=S,this.lastIncrementTime=0,this.value=0}increment(){const y=this.nowFn();return y-this.lastIncrementTime>this.interval&&(this.lastIncrementTime=y,this.value=0),this.value++,this.value}},(function(y){y[y.Resolved=0]="Resolved",y[y.Rejected=1]="Rejected"})(T||(T={}));class A{get isRejected(){var S;return((S=this.outcome)==null?void 0:S.outcome)===T.Rejected}get isResolved(){var S;return((S=this.outcome)==null?void 0:S.outcome)===T.Resolved}get isSettled(){return!!this.outcome}get value(){var S,D;return((S=this.outcome)==null?void 0:S.outcome)===T.Resolved?(D=this.outcome)==null?void 0:D.value:void 0}constructor(){this.p=new Promise(((S,D)=>{this.completeCallback=S,this.errorCallback=D}))}complete(S){return new Promise((D=>{this.completeCallback(S),this.outcome={outcome:T.Resolved,value:S},D()}))}error(S){return new Promise((D=>{this.errorCallback(S),this.outcome={outcome:T.Rejected,value:S},D()}))}cancel(){return this.error(new v.CancellationError)}}t.DeferredPromise=A,(function(y){y.settled=async function(S){let D;const M=await Promise.all(S.map((I=>I.then((F=>F),(F=>{D||(D=F)})))));if(D!==void 0)throw D;return M},y.withAsyncBody=function(S){return new Promise((async(D,M)=>{try{await S(D,M)}catch(I){M(I)}}))}})(C||(t.Promises=C={}));class N{get value(){return this._value}get error(){return this._error}get isResolved(){return this._isResolved}constructor(S){this._value=void 0,this._error=void 0,this._isResolved=!1,this.promise=S.then((D=>(this._value=D,this._isResolved=!0,D)),(D=>{throw this._error=D,this._isResolved=!0,D}))}requireValue(){if(!this._isResolved)throw new v.BugIndicatingError("Promise is not resolved yet");if(this._error)throw this._error;return this._value}}t.StatefulPromise=N,t.LazyStatefulPromise=class{constructor(y){this._compute=y,this._promise=new u.Lazy((()=>new N(this._compute())))}requireValue(){return this._promise.value.requireValue()}getPromise(){return this._promise.value.promise}get currentValue(){var y;return(y=this._promise.rawValue)==null?void 0:y.value}},(function(y){y[y.Initial=0]="Initial",y[y.DoneOK=1]="DoneOK",y[y.DoneError=2]="DoneError"})(E||(E={}));const w=class w{static fromArray(S){return new w((D=>{D.emitMany(S)}))}static fromPromise(S){return new w((async D=>{D.emitMany(await S)}))}static fromPromises(S){return new w((async D=>{await Promise.all(S.map((async M=>D.emitOne(await M))))}))}static merge(S){return new w((async D=>{await Promise.all(S.map((async M=>{for await(const I of M)D.emitOne(I)})))}))}constructor(S,D){this._state=E.Initial,this._results=[],this._error=null,this._onReturn=D,this._onStateChanged=new n.Emitter,queueMicrotask((async()=>{const M={emitOne:I=>this.emitOne(I),emitMany:I=>this.emitMany(I),reject:I=>this.reject(I)};try{await Promise.resolve(S(M)),this.resolve()}catch(I){this.reject(I)}finally{M.emitOne=void 0,M.emitMany=void 0,M.reject=void 0}}))}[Symbol.asyncIterator](){let S=0;return{next:async()=>{for(;;){if(this._state===E.DoneError)throw this._error;if(S<this._results.length)return{done:!1,value:this._results[S++]};if(this._state===E.DoneOK)return{done:!0,value:void 0};await n.Event.toPromise(this._onStateChanged.event)}},return:async()=>{var D;return(D=this._onReturn)==null||D.call(this),{done:!0,value:void 0}}}}static map(S,D){return new w((async M=>{for await(const I of S)M.emitOne(D(I))}))}map(S){return w.map(this,S)}static filter(S,D){return new w((async M=>{for await(const I of S)D(I)&&M.emitOne(I)}))}filter(S){return w.filter(this,S)}static coalesce(S){return w.filter(S,(D=>!!D))}coalesce(){return w.coalesce(this)}static async toPromise(S){const D=[];for await(const M of S)D.push(M);return D}toPromise(){return w.toPromise(this)}emitOne(S){this._state===E.Initial&&(this._results.push(S),this._onStateChanged.fire())}emitMany(S){this._state===E.Initial&&(this._results=this._results.concat(S),this._onStateChanged.fire())}resolve(){this._state===E.Initial&&(this._state=E.DoneOK,this._onStateChanged.fire())}reject(S){this._state===E.Initial&&(this._state=E.DoneError,this._error=S,this._onStateChanged.fire())}};w.EMPTY=w.fromArray([]);let P=w;t.AsyncIterableObject=P;class W extends P{constructor(S,D){super(D),this._source=S}cancel(){this._source.cancel()}}t.CancelableAsyncIterableObject=W,t.AsyncIterableSource=class{constructor(y){let S,D;this._deferred=new A,this._asyncIterable=new P((M=>{if(!S)return D&&M.emitMany(D),this._errorFn=I=>M.reject(I),this._emitFn=I=>M.emitOne(I),this._deferred.p;M.reject(S)}),y),this._emitFn=M=>{D||(D=[]),D.push(M)},this._errorFn=M=>{S||(S=M)}}get asyncIterable(){return this._asyncIterable}resolve(){this._deferred.complete()}reject(y){this._errorFn(y),this._deferred.complete()}emitOne(y){this._emitFn(y)}}},8447:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CancellationTokenSource=t.CancellationToken=void 0,t.cancelOnDispose=function(p){const u=new g;return p.add({dispose(){u.cancel()}}),u.token};const i=_(802),v=Object.freeze((function(p,u){const r=setTimeout(p.bind(u),0);return{dispose(){clearTimeout(r)}}}));var n;(function(p){p.isCancellationToken=function(u){return u===p.None||u===p.Cancelled||u instanceof f||!(!u||typeof u!="object")&&typeof u.isCancellationRequested=="boolean"&&typeof u.onCancellationRequested=="function"},p.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:i.Event.None}),p.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:v})})(n||(t.CancellationToken=n={}));class f{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?v:(this._emitter||(this._emitter=new i.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}}class g{constructor(u){this._token=void 0,this._parentListener=void 0,this._parentListener=u&&u.onCancellationRequested(this.cancel,this)}get token(){return this._token||(this._token=new f),this._token}cancel(){this._token?this._token instanceof f&&this._token.cancel():this._token=n.Cancelled}dispose(u=!1){var r;u&&this.cancel(),(r=this._parentListener)==null||r.dispose(),this._token?this._token instanceof f&&this._token.dispose():this._token=n.None}}t.CancellationTokenSource=g},4869:(K,t)=>{var _;Object.defineProperty(t,"__esModule",{value:!0}),t.CharCode=void 0,(function(i){i[i.Null=0]="Null",i[i.Backspace=8]="Backspace",i[i.Tab=9]="Tab",i[i.LineFeed=10]="LineFeed",i[i.CarriageReturn=13]="CarriageReturn",i[i.Space=32]="Space",i[i.ExclamationMark=33]="ExclamationMark",i[i.DoubleQuote=34]="DoubleQuote",i[i.Hash=35]="Hash",i[i.DollarSign=36]="DollarSign",i[i.PercentSign=37]="PercentSign",i[i.Ampersand=38]="Ampersand",i[i.SingleQuote=39]="SingleQuote",i[i.OpenParen=40]="OpenParen",i[i.CloseParen=41]="CloseParen",i[i.Asterisk=42]="Asterisk",i[i.Plus=43]="Plus",i[i.Comma=44]="Comma",i[i.Dash=45]="Dash",i[i.Period=46]="Period",i[i.Slash=47]="Slash",i[i.Digit0=48]="Digit0",i[i.Digit1=49]="Digit1",i[i.Digit2=50]="Digit2",i[i.Digit3=51]="Digit3",i[i.Digit4=52]="Digit4",i[i.Digit5=53]="Digit5",i[i.Digit6=54]="Digit6",i[i.Digit7=55]="Digit7",i[i.Digit8=56]="Digit8",i[i.Digit9=57]="Digit9",i[i.Colon=58]="Colon",i[i.Semicolon=59]="Semicolon",i[i.LessThan=60]="LessThan",i[i.Equals=61]="Equals",i[i.GreaterThan=62]="GreaterThan",i[i.QuestionMark=63]="QuestionMark",i[i.AtSign=64]="AtSign",i[i.A=65]="A",i[i.B=66]="B",i[i.C=67]="C",i[i.D=68]="D",i[i.E=69]="E",i[i.F=70]="F",i[i.G=71]="G",i[i.H=72]="H",i[i.I=73]="I",i[i.J=74]="J",i[i.K=75]="K",i[i.L=76]="L",i[i.M=77]="M",i[i.N=78]="N",i[i.O=79]="O",i[i.P=80]="P",i[i.Q=81]="Q",i[i.R=82]="R",i[i.S=83]="S",i[i.T=84]="T",i[i.U=85]="U",i[i.V=86]="V",i[i.W=87]="W",i[i.X=88]="X",i[i.Y=89]="Y",i[i.Z=90]="Z",i[i.OpenSquareBracket=91]="OpenSquareBracket",i[i.Backslash=92]="Backslash",i[i.CloseSquareBracket=93]="CloseSquareBracket",i[i.Caret=94]="Caret",i[i.Underline=95]="Underline",i[i.BackTick=96]="BackTick",i[i.a=97]="a",i[i.b=98]="b",i[i.c=99]="c",i[i.d=100]="d",i[i.e=101]="e",i[i.f=102]="f",i[i.g=103]="g",i[i.h=104]="h",i[i.i=105]="i",i[i.j=106]="j",i[i.k=107]="k",i[i.l=108]="l",i[i.m=109]="m",i[i.n=110]="n",i[i.o=111]="o",i[i.p=112]="p",i[i.q=113]="q",i[i.r=114]="r",i[i.s=115]="s",i[i.t=116]="t",i[i.u=117]="u",i[i.v=118]="v",i[i.w=119]="w",i[i.x=120]="x",i[i.y=121]="y",i[i.z=122]="z",i[i.OpenCurlyBrace=123]="OpenCurlyBrace",i[i.Pipe=124]="Pipe",i[i.CloseCurlyBrace=125]="CloseCurlyBrace",i[i.Tilde=126]="Tilde",i[i.NoBreakSpace=160]="NoBreakSpace",i[i.U_Combining_Grave_Accent=768]="U_Combining_Grave_Accent",i[i.U_Combining_Acute_Accent=769]="U_Combining_Acute_Accent",i[i.U_Combining_Circumflex_Accent=770]="U_Combining_Circumflex_Accent",i[i.U_Combining_Tilde=771]="U_Combining_Tilde",i[i.U_Combining_Macron=772]="U_Combining_Macron",i[i.U_Combining_Overline=773]="U_Combining_Overline",i[i.U_Combining_Breve=774]="U_Combining_Breve",i[i.U_Combining_Dot_Above=775]="U_Combining_Dot_Above",i[i.U_Combining_Diaeresis=776]="U_Combining_Diaeresis",i[i.U_Combining_Hook_Above=777]="U_Combining_Hook_Above",i[i.U_Combining_Ring_Above=778]="U_Combining_Ring_Above",i[i.U_Combining_Double_Acute_Accent=779]="U_Combining_Double_Acute_Accent",i[i.U_Combining_Caron=780]="U_Combining_Caron",i[i.U_Combining_Vertical_Line_Above=781]="U_Combining_Vertical_Line_Above",i[i.U_Combining_Double_Vertical_Line_Above=782]="U_Combining_Double_Vertical_Line_Above",i[i.U_Combining_Double_Grave_Accent=783]="U_Combining_Double_Grave_Accent",i[i.U_Combining_Candrabindu=784]="U_Combining_Candrabindu",i[i.U_Combining_Inverted_Breve=785]="U_Combining_Inverted_Breve",i[i.U_Combining_Turned_Comma_Above=786]="U_Combining_Turned_Comma_Above",i[i.U_Combining_Comma_Above=787]="U_Combining_Comma_Above",i[i.U_Combining_Reversed_Comma_Above=788]="U_Combining_Reversed_Comma_Above",i[i.U_Combining_Comma_Above_Right=789]="U_Combining_Comma_Above_Right",i[i.U_Combining_Grave_Accent_Below=790]="U_Combining_Grave_Accent_Below",i[i.U_Combining_Acute_Accent_Below=791]="U_Combining_Acute_Accent_Below",i[i.U_Combining_Left_Tack_Below=792]="U_Combining_Left_Tack_Below",i[i.U_Combining_Right_Tack_Below=793]="U_Combining_Right_Tack_Below",i[i.U_Combining_Left_Angle_Above=794]="U_Combining_Left_Angle_Above",i[i.U_Combining_Horn=795]="U_Combining_Horn",i[i.U_Combining_Left_Half_Ring_Below=796]="U_Combining_Left_Half_Ring_Below",i[i.U_Combining_Up_Tack_Below=797]="U_Combining_Up_Tack_Below",i[i.U_Combining_Down_Tack_Below=798]="U_Combining_Down_Tack_Below",i[i.U_Combining_Plus_Sign_Below=799]="U_Combining_Plus_Sign_Below",i[i.U_Combining_Minus_Sign_Below=800]="U_Combining_Minus_Sign_Below",i[i.U_Combining_Palatalized_Hook_Below=801]="U_Combining_Palatalized_Hook_Below",i[i.U_Combining_Retroflex_Hook_Below=802]="U_Combining_Retroflex_Hook_Below",i[i.U_Combining_Dot_Below=803]="U_Combining_Dot_Below",i[i.U_Combining_Diaeresis_Below=804]="U_Combining_Diaeresis_Below",i[i.U_Combining_Ring_Below=805]="U_Combining_Ring_Below",i[i.U_Combining_Comma_Below=806]="U_Combining_Comma_Below",i[i.U_Combining_Cedilla=807]="U_Combining_Cedilla",i[i.U_Combining_Ogonek=808]="U_Combining_Ogonek",i[i.U_Combining_Vertical_Line_Below=809]="U_Combining_Vertical_Line_Below",i[i.U_Combining_Bridge_Below=810]="U_Combining_Bridge_Below",i[i.U_Combining_Inverted_Double_Arch_Below=811]="U_Combining_Inverted_Double_Arch_Below",i[i.U_Combining_Caron_Below=812]="U_Combining_Caron_Below",i[i.U_Combining_Circumflex_Accent_Below=813]="U_Combining_Circumflex_Accent_Below",i[i.U_Combining_Breve_Below=814]="U_Combining_Breve_Below",i[i.U_Combining_Inverted_Breve_Below=815]="U_Combining_Inverted_Breve_Below",i[i.U_Combining_Tilde_Below=816]="U_Combining_Tilde_Below",i[i.U_Combining_Macron_Below=817]="U_Combining_Macron_Below",i[i.U_Combining_Low_Line=818]="U_Combining_Low_Line",i[i.U_Combining_Double_Low_Line=819]="U_Combining_Double_Low_Line",i[i.U_Combining_Tilde_Overlay=820]="U_Combining_Tilde_Overlay",i[i.U_Combining_Short_Stroke_Overlay=821]="U_Combining_Short_Stroke_Overlay",i[i.U_Combining_Long_Stroke_Overlay=822]="U_Combining_Long_Stroke_Overlay",i[i.U_Combining_Short_Solidus_Overlay=823]="U_Combining_Short_Solidus_Overlay",i[i.U_Combining_Long_Solidus_Overlay=824]="U_Combining_Long_Solidus_Overlay",i[i.U_Combining_Right_Half_Ring_Below=825]="U_Combining_Right_Half_Ring_Below",i[i.U_Combining_Inverted_Bridge_Below=826]="U_Combining_Inverted_Bridge_Below",i[i.U_Combining_Square_Below=827]="U_Combining_Square_Below",i[i.U_Combining_Seagull_Below=828]="U_Combining_Seagull_Below",i[i.U_Combining_X_Above=829]="U_Combining_X_Above",i[i.U_Combining_Vertical_Tilde=830]="U_Combining_Vertical_Tilde",i[i.U_Combining_Double_Overline=831]="U_Combining_Double_Overline",i[i.U_Combining_Grave_Tone_Mark=832]="U_Combining_Grave_Tone_Mark",i[i.U_Combining_Acute_Tone_Mark=833]="U_Combining_Acute_Tone_Mark",i[i.U_Combining_Greek_Perispomeni=834]="U_Combining_Greek_Perispomeni",i[i.U_Combining_Greek_Koronis=835]="U_Combining_Greek_Koronis",i[i.U_Combining_Greek_Dialytika_Tonos=836]="U_Combining_Greek_Dialytika_Tonos",i[i.U_Combining_Greek_Ypogegrammeni=837]="U_Combining_Greek_Ypogegrammeni",i[i.U_Combining_Bridge_Above=838]="U_Combining_Bridge_Above",i[i.U_Combining_Equals_Sign_Below=839]="U_Combining_Equals_Sign_Below",i[i.U_Combining_Double_Vertical_Line_Below=840]="U_Combining_Double_Vertical_Line_Below",i[i.U_Combining_Left_Angle_Below=841]="U_Combining_Left_Angle_Below",i[i.U_Combining_Not_Tilde_Above=842]="U_Combining_Not_Tilde_Above",i[i.U_Combining_Homothetic_Above=843]="U_Combining_Homothetic_Above",i[i.U_Combining_Almost_Equal_To_Above=844]="U_Combining_Almost_Equal_To_Above",i[i.U_Combining_Left_Right_Arrow_Below=845]="U_Combining_Left_Right_Arrow_Below",i[i.U_Combining_Upwards_Arrow_Below=846]="U_Combining_Upwards_Arrow_Below",i[i.U_Combining_Grapheme_Joiner=847]="U_Combining_Grapheme_Joiner",i[i.U_Combining_Right_Arrowhead_Above=848]="U_Combining_Right_Arrowhead_Above",i[i.U_Combining_Left_Half_Ring_Above=849]="U_Combining_Left_Half_Ring_Above",i[i.U_Combining_Fermata=850]="U_Combining_Fermata",i[i.U_Combining_X_Below=851]="U_Combining_X_Below",i[i.U_Combining_Left_Arrowhead_Below=852]="U_Combining_Left_Arrowhead_Below",i[i.U_Combining_Right_Arrowhead_Below=853]="U_Combining_Right_Arrowhead_Below",i[i.U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below=854]="U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below",i[i.U_Combining_Right_Half_Ring_Above=855]="U_Combining_Right_Half_Ring_Above",i[i.U_Combining_Dot_Above_Right=856]="U_Combining_Dot_Above_Right",i[i.U_Combining_Asterisk_Below=857]="U_Combining_Asterisk_Below",i[i.U_Combining_Double_Ring_Below=858]="U_Combining_Double_Ring_Below",i[i.U_Combining_Zigzag_Above=859]="U_Combining_Zigzag_Above",i[i.U_Combining_Double_Breve_Below=860]="U_Combining_Double_Breve_Below",i[i.U_Combining_Double_Breve=861]="U_Combining_Double_Breve",i[i.U_Combining_Double_Macron=862]="U_Combining_Double_Macron",i[i.U_Combining_Double_Macron_Below=863]="U_Combining_Double_Macron_Below",i[i.U_Combining_Double_Tilde=864]="U_Combining_Double_Tilde",i[i.U_Combining_Double_Inverted_Breve=865]="U_Combining_Double_Inverted_Breve",i[i.U_Combining_Double_Rightwards_Arrow_Below=866]="U_Combining_Double_Rightwards_Arrow_Below",i[i.U_Combining_Latin_Small_Letter_A=867]="U_Combining_Latin_Small_Letter_A",i[i.U_Combining_Latin_Small_Letter_E=868]="U_Combining_Latin_Small_Letter_E",i[i.U_Combining_Latin_Small_Letter_I=869]="U_Combining_Latin_Small_Letter_I",i[i.U_Combining_Latin_Small_Letter_O=870]="U_Combining_Latin_Small_Letter_O",i[i.U_Combining_Latin_Small_Letter_U=871]="U_Combining_Latin_Small_Letter_U",i[i.U_Combining_Latin_Small_Letter_C=872]="U_Combining_Latin_Small_Letter_C",i[i.U_Combining_Latin_Small_Letter_D=873]="U_Combining_Latin_Small_Letter_D",i[i.U_Combining_Latin_Small_Letter_H=874]="U_Combining_Latin_Small_Letter_H",i[i.U_Combining_Latin_Small_Letter_M=875]="U_Combining_Latin_Small_Letter_M",i[i.U_Combining_Latin_Small_Letter_R=876]="U_Combining_Latin_Small_Letter_R",i[i.U_Combining_Latin_Small_Letter_T=877]="U_Combining_Latin_Small_Letter_T",i[i.U_Combining_Latin_Small_Letter_V=878]="U_Combining_Latin_Small_Letter_V",i[i.U_Combining_Latin_Small_Letter_X=879]="U_Combining_Latin_Small_Letter_X",i[i.LINE_SEPARATOR=8232]="LINE_SEPARATOR",i[i.PARAGRAPH_SEPARATOR=8233]="PARAGRAPH_SEPARATOR",i[i.NEXT_LINE=133]="NEXT_LINE",i[i.U_CIRCUMFLEX=94]="U_CIRCUMFLEX",i[i.U_GRAVE_ACCENT=96]="U_GRAVE_ACCENT",i[i.U_DIAERESIS=168]="U_DIAERESIS",i[i.U_MACRON=175]="U_MACRON",i[i.U_ACUTE_ACCENT=180]="U_ACUTE_ACCENT",i[i.U_CEDILLA=184]="U_CEDILLA",i[i.U_MODIFIER_LETTER_LEFT_ARROWHEAD=706]="U_MODIFIER_LETTER_LEFT_ARROWHEAD",i[i.U_MODIFIER_LETTER_RIGHT_ARROWHEAD=707]="U_MODIFIER_LETTER_RIGHT_ARROWHEAD",i[i.U_MODIFIER_LETTER_UP_ARROWHEAD=708]="U_MODIFIER_LETTER_UP_ARROWHEAD",i[i.U_MODIFIER_LETTER_DOWN_ARROWHEAD=709]="U_MODIFIER_LETTER_DOWN_ARROWHEAD",i[i.U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING=722]="U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING",i[i.U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING=723]="U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING",i[i.U_MODIFIER_LETTER_UP_TACK=724]="U_MODIFIER_LETTER_UP_TACK",i[i.U_MODIFIER_LETTER_DOWN_TACK=725]="U_MODIFIER_LETTER_DOWN_TACK",i[i.U_MODIFIER_LETTER_PLUS_SIGN=726]="U_MODIFIER_LETTER_PLUS_SIGN",i[i.U_MODIFIER_LETTER_MINUS_SIGN=727]="U_MODIFIER_LETTER_MINUS_SIGN",i[i.U_BREVE=728]="U_BREVE",i[i.U_DOT_ABOVE=729]="U_DOT_ABOVE",i[i.U_RING_ABOVE=730]="U_RING_ABOVE",i[i.U_OGONEK=731]="U_OGONEK",i[i.U_SMALL_TILDE=732]="U_SMALL_TILDE",i[i.U_DOUBLE_ACUTE_ACCENT=733]="U_DOUBLE_ACUTE_ACCENT",i[i.U_MODIFIER_LETTER_RHOTIC_HOOK=734]="U_MODIFIER_LETTER_RHOTIC_HOOK",i[i.U_MODIFIER_LETTER_CROSS_ACCENT=735]="U_MODIFIER_LETTER_CROSS_ACCENT",i[i.U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR=741]="U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR",i[i.U_MODIFIER_LETTER_HIGH_TONE_BAR=742]="U_MODIFIER_LETTER_HIGH_TONE_BAR",i[i.U_MODIFIER_LETTER_MID_TONE_BAR=743]="U_MODIFIER_LETTER_MID_TONE_BAR",i[i.U_MODIFIER_LETTER_LOW_TONE_BAR=744]="U_MODIFIER_LETTER_LOW_TONE_BAR",i[i.U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR=745]="U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR",i[i.U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK=746]="U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK",i[i.U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK=747]="U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK",i[i.U_MODIFIER_LETTER_UNASPIRATED=749]="U_MODIFIER_LETTER_UNASPIRATED",i[i.U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD=751]="U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD",i[i.U_MODIFIER_LETTER_LOW_UP_ARROWHEAD=752]="U_MODIFIER_LETTER_LOW_UP_ARROWHEAD",i[i.U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD=753]="U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD",i[i.U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD=754]="U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD",i[i.U_MODIFIER_LETTER_LOW_RING=755]="U_MODIFIER_LETTER_LOW_RING",i[i.U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT=756]="U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT",i[i.U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT=757]="U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT",i[i.U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT=758]="U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT",i[i.U_MODIFIER_LETTER_LOW_TILDE=759]="U_MODIFIER_LETTER_LOW_TILDE",i[i.U_MODIFIER_LETTER_RAISED_COLON=760]="U_MODIFIER_LETTER_RAISED_COLON",i[i.U_MODIFIER_LETTER_BEGIN_HIGH_TONE=761]="U_MODIFIER_LETTER_BEGIN_HIGH_TONE",i[i.U_MODIFIER_LETTER_END_HIGH_TONE=762]="U_MODIFIER_LETTER_END_HIGH_TONE",i[i.U_MODIFIER_LETTER_BEGIN_LOW_TONE=763]="U_MODIFIER_LETTER_BEGIN_LOW_TONE",i[i.U_MODIFIER_LETTER_END_LOW_TONE=764]="U_MODIFIER_LETTER_END_LOW_TONE",i[i.U_MODIFIER_LETTER_SHELF=765]="U_MODIFIER_LETTER_SHELF",i[i.U_MODIFIER_LETTER_OPEN_SHELF=766]="U_MODIFIER_LETTER_OPEN_SHELF",i[i.U_MODIFIER_LETTER_LOW_LEFT_ARROW=767]="U_MODIFIER_LETTER_LOW_LEFT_ARROW",i[i.U_GREEK_LOWER_NUMERAL_SIGN=885]="U_GREEK_LOWER_NUMERAL_SIGN",i[i.U_GREEK_TONOS=900]="U_GREEK_TONOS",i[i.U_GREEK_DIALYTIKA_TONOS=901]="U_GREEK_DIALYTIKA_TONOS",i[i.U_GREEK_KORONIS=8125]="U_GREEK_KORONIS",i[i.U_GREEK_PSILI=8127]="U_GREEK_PSILI",i[i.U_GREEK_PERISPOMENI=8128]="U_GREEK_PERISPOMENI",i[i.U_GREEK_DIALYTIKA_AND_PERISPOMENI=8129]="U_GREEK_DIALYTIKA_AND_PERISPOMENI",i[i.U_GREEK_PSILI_AND_VARIA=8141]="U_GREEK_PSILI_AND_VARIA",i[i.U_GREEK_PSILI_AND_OXIA=8142]="U_GREEK_PSILI_AND_OXIA",i[i.U_GREEK_PSILI_AND_PERISPOMENI=8143]="U_GREEK_PSILI_AND_PERISPOMENI",i[i.U_GREEK_DASIA_AND_VARIA=8157]="U_GREEK_DASIA_AND_VARIA",i[i.U_GREEK_DASIA_AND_OXIA=8158]="U_GREEK_DASIA_AND_OXIA",i[i.U_GREEK_DASIA_AND_PERISPOMENI=8159]="U_GREEK_DASIA_AND_PERISPOMENI",i[i.U_GREEK_DIALYTIKA_AND_VARIA=8173]="U_GREEK_DIALYTIKA_AND_VARIA",i[i.U_GREEK_DIALYTIKA_AND_OXIA=8174]="U_GREEK_DIALYTIKA_AND_OXIA",i[i.U_GREEK_VARIA=8175]="U_GREEK_VARIA",i[i.U_GREEK_OXIA=8189]="U_GREEK_OXIA",i[i.U_GREEK_DASIA=8190]="U_GREEK_DASIA",i[i.U_IDEOGRAPHIC_FULL_STOP=12290]="U_IDEOGRAPHIC_FULL_STOP",i[i.U_LEFT_CORNER_BRACKET=12300]="U_LEFT_CORNER_BRACKET",i[i.U_RIGHT_CORNER_BRACKET=12301]="U_RIGHT_CORNER_BRACKET",i[i.U_LEFT_BLACK_LENTICULAR_BRACKET=12304]="U_LEFT_BLACK_LENTICULAR_BRACKET",i[i.U_RIGHT_BLACK_LENTICULAR_BRACKET=12305]="U_RIGHT_BLACK_LENTICULAR_BRACKET",i[i.U_OVERLINE=8254]="U_OVERLINE",i[i.UTF8_BOM=65279]="UTF8_BOM",i[i.U_FULLWIDTH_SEMICOLON=65307]="U_FULLWIDTH_SEMICOLON",i[i.U_FULLWIDTH_COMMA=65292]="U_FULLWIDTH_COMMA"})(_||(t.CharCode=_={}))},9087:(K,t)=>{var _;Object.defineProperty(t,"__esModule",{value:!0}),t.SetWithKey=void 0,t.groupBy=function(v,n){const f=Object.create(null);for(const g of v){const p=n(g);let u=f[p];u||(u=f[p]=[]),u.push(g)}return f},t.diffSets=function(v,n){const f=[],g=[];for(const p of v)n.has(p)||f.push(p);for(const p of n)v.has(p)||g.push(p);return{removed:f,added:g}},t.diffMaps=function(v,n){const f=[],g=[];for(const[p,u]of v)n.has(p)||f.push(u);for(const[p,u]of n)v.has(p)||g.push(u);return{removed:f,added:g}},t.intersection=function(v,n){const f=new Set;for(const g of n)v.has(g)&&f.add(g);return f};class i{constructor(n,f){this.toKey=f,this._map=new Map,this[_]="SetWithKey";for(const g of n)this.add(g)}get size(){return this._map.size}add(n){const f=this.toKey(n);return this._map.set(f,n),this}delete(n){return this._map.delete(this.toKey(n))}has(n){return this._map.has(this.toKey(n))}*entries(){for(const n of this._map.values())yield[n,n]}keys(){return this.values()}*values(){for(const n of this._map.values())yield n}clear(){this._map.clear()}forEach(n,f){this._map.forEach((g=>n.call(f,g,g,this)))}[Symbol.iterator](){return this.values()}}_=Symbol.toStringTag,t.SetWithKey=i},4838:(K,t)=>{function _(i){return(v,n,f)=>{let g=null,p=null;if(typeof f.value=="function"?(g="value",p=f.value):typeof f.get=="function"&&(g="get",p=f.get),!p)throw new Error("not supported");f[g]=i(p,n)}}Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=function(i,v,n){let f=null,g=null;if(typeof n.value=="function"?(f="value",g=n.value,g.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof n.get=="function"&&(f="get",g=n.get),!g)throw new Error("not supported");const p=`$memoize$${v}`;n[f]=function(...u){return this.hasOwnProperty(p)||Object.defineProperty(this,p,{configurable:!1,enumerable:!1,writable:!1,value:g.apply(this,u)}),this[p]}},t.debounce=function(i,v,n){return _(((f,g)=>{const p=`$debounce$${g}`,u=`$debounce$result$${g}`;return function(...r){this[u]||(this[u]=n?n():void 0),clearTimeout(this[p]),v&&(this[u]=v(this[u],...r),r=[this[u]]),this[p]=setTimeout((()=>{f.apply(this,r),this[u]=n?n():void 0}),i)}}))},t.throttle=function(i,v,n){return _(((f,g)=>{const p=`$throttle$timer$${g}`,u=`$throttle$result$${g}`,r=`$throttle$lastRun$${g}`,h=`$throttle$pending$${g}`;return function(...s){if(this[u]||(this[u]=n?n():void 0),this[r]!==null&&this[r]!==void 0||(this[r]=-Number.MAX_VALUE),v&&(this[u]=v(this[u],...s)),this[h])return;const e=this[r]+i;e<=Date.now()?(this[r]=Date.now(),f.apply(this,[this[u]]),this[u]=n?n():void 0):(this[h]=!0,this[p]=setTimeout((()=>{this[h]=!1,this[r]=Date.now(),f.apply(this,[this[u]]),this[u]=n?n():void 0}),e-Date.now()))}}))}},9807:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BugIndicatingError=t.ErrorNoTelemetry=t.ExpectedError=t.NotSupportedError=t.NotImplementedError=t.ReadonlyError=t.CancellationError=t.errorHandler=t.ErrorHandler=void 0,t.setUnexpectedErrorHandler=function(s){t.errorHandler.setUnexpectedErrorHandler(s)},t.isSigPipeError=function(s){var l;if(!s||typeof s!="object")return!1;const e=s;return e.code==="EPIPE"&&((l=e.syscall)==null?void 0:l.toUpperCase())==="WRITE"},t.onUnexpectedError=function(s){v(s)||t.errorHandler.onUnexpectedError(s)},t.onUnexpectedExternalError=function(s){v(s)||t.errorHandler.onUnexpectedExternalError(s)},t.transformErrorForSerialization=function(s){if(s instanceof Error){const{name:e,message:l}=s;return{$isError:!0,name:e,message:l,stack:s.stacktrace||s.stack,noTelemetry:r.isErrorNoTelemetry(s)}}return s},t.transformErrorFromSerialization=function(s){let e;return s.noTelemetry?e=new r:(e=new Error,e.name=s.name),e.message=s.message,e.stack=s.stack,e},t.isCancellationError=v,t.canceled=function(){const s=new Error(i);return s.name=s.message,s},t.illegalArgument=function(s){return s?new Error(`Illegal argument: ${s}`):new Error("Illegal argument")},t.illegalState=function(s){return s?new Error(`Illegal state: ${s}`):new Error("Illegal state")},t.getErrorMessage=function(s){return s?s.message?s.message:s.stack?s.stack.split(`
+`)[0]:String(s):"Error"};class _{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout((()=>{throw e.stack?r.isErrorNoTelemetry(e)?new r(e.message+`
+
+`+e.stack):new Error(e.message+`
+
+`+e.stack):e}),0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach((l=>{l(e)}))}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}}t.ErrorHandler=_,t.errorHandler=new _;const i="Canceled";function v(s){return s instanceof n||s instanceof Error&&s.name===i&&s.message===i}class n extends Error{constructor(){super(i),this.name=this.message}}t.CancellationError=n;class f extends TypeError{constructor(e){super(e?`${e} is read-only and cannot be changed`:"Cannot change read-only property")}}t.ReadonlyError=f;class g extends Error{constructor(e){super("NotImplemented"),e&&(this.message=e)}}t.NotImplementedError=g;class p extends Error{constructor(e){super("NotSupported"),e&&(this.message=e)}}t.NotSupportedError=p;class u extends Error{constructor(){super(...arguments),this.isExpected=!0}}t.ExpectedError=u;class r extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(e){if(e instanceof r)return e;const l=new r;return l.message=e.message,l.stack=e.stack,l}static isErrorNoTelemetry(e){return e.name==="CodeExpectedError"}}t.ErrorNoTelemetry=r;class h extends Error{constructor(e){super(e||"An unexpected bug occurred."),Object.setPrototypeOf(this,h.prototype)}}t.BugIndicatingError=h},802:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueWithChangeEvent=t.Relay=t.EventBufferer=t.DynamicListEventMultiplexer=t.EventMultiplexer=t.MicrotaskEmitter=t.DebounceEmitter=t.PauseableEmitter=t.AsyncEmitter=t.createEventDeliveryQueue=t.Emitter=t.ListenerRefusalError=t.ListenerLeakError=t.EventProfiling=t.Event=void 0,t.setGlobalLeakWarningThreshold=function(E){const A=r;return r=E,{dispose(){r=A}}};const i=_(9807),v=_(8841),n=_(7150),f=_(6317),g=_(9725);var p;(function(E){function A(M){return(I,F=null,H)=>{let B,k=!1;return B=M((j=>{if(!k)return B?B.dispose():k=!0,I.call(F,j)}),null,H),k&&B.dispose(),B}}function N(M,I,F){return W(((H,B=null,k)=>M((j=>H.call(B,I(j))),null,k)),F)}function P(M,I,F){return W(((H,B=null,k)=>M((j=>I(j)&&H.call(B,j)),null,k)),F)}function W(M,I){let F;const H=new c({onWillAddFirstListener(){F=M(H.fire,H)},onDidRemoveLastListener(){F==null||F.dispose()}});return I==null||I.add(H),H.event}function w(M,I,F=100,H=!1,B=!1,k,j){let $,X,V,Z,se=0;const te=new c({leakWarningThreshold:k,onWillAddFirstListener(){$=M((re=>{se++,X=I(X,re),H&&!V&&(te.fire(X),X=void 0),Z=()=>{const ne=X;X=void 0,V=void 0,(!H||se>1)&&te.fire(ne),se=0},typeof F=="number"?(clearTimeout(V),V=setTimeout(Z,F)):V===void 0&&(V=0,queueMicrotask(Z))}))},onWillRemoveListener(){B&&se>0&&(Z==null||Z())},onDidRemoveLastListener(){Z=void 0,$.dispose()}});return j==null||j.add(te),te.event}E.None=()=>n.Disposable.None,E.defer=function(M,I){return w(M,(()=>{}),0,void 0,!0,void 0,I)},E.once=A,E.map=N,E.forEach=function(M,I,F){return W(((H,B=null,k)=>M((j=>{I(j),H.call(B,j)}),null,k)),F)},E.filter=P,E.signal=function(M){return M},E.any=function(...M){return(I,F=null,H)=>{return B=(0,n.combinedDisposable)(...M.map((j=>j(($=>I.call(F,$)))))),(k=H)instanceof Array?k.push(B):k&&k.add(B),B;var B,k}},E.reduce=function(M,I,F,H){let B=F;return N(M,(k=>(B=I(B,k),B)),H)},E.debounce=w,E.accumulate=function(M,I=0,F){return E.debounce(M,((H,B)=>H?(H.push(B),H):[B]),I,void 0,!0,void 0,F)},E.latch=function(M,I=(H,B)=>H===B,F){let H,B=!0;return P(M,(k=>{const j=B||!I(k,H);return B=!1,H=k,j}),F)},E.split=function(M,I,F){return[E.filter(M,I,F),E.filter(M,(H=>!I(H)),F)]},E.buffer=function(M,I=!1,F=[],H){let B=F.slice(),k=M((X=>{B?B.push(X):$.fire(X)}));H&&H.add(k);const j=()=>{B==null||B.forEach((X=>$.fire(X))),B=null},$=new c({onWillAddFirstListener(){k||(k=M((X=>$.fire(X))),H&&H.add(k))},onDidAddFirstListener(){B&&(I?setTimeout(j):j())},onDidRemoveLastListener(){k&&k.dispose(),k=null}});return H&&H.add($),$.event},E.chain=function(M,I){return(F,H,B)=>{const k=I(new S);return M((function(j){const $=k.evaluate(j);$!==y&&F.call(H,$)}),void 0,B)}};const y=Symbol("HaltChainable");class S{constructor(){this.steps=[]}map(I){return this.steps.push(I),this}forEach(I){return this.steps.push((F=>(I(F),F))),this}filter(I){return this.steps.push((F=>I(F)?F:y)),this}reduce(I,F){let H=F;return this.steps.push((B=>(H=I(H,B),H))),this}latch(I=(F,H)=>F===H){let F,H=!0;return this.steps.push((B=>{const k=H||!I(B,F);return H=!1,F=B,k?B:y})),this}evaluate(I){for(const F of this.steps)if((I=F(I))===y)break;return I}}E.fromNodeEventEmitter=function(M,I,F=H=>H){const H=(...k)=>B.fire(F(...k)),B=new c({onWillAddFirstListener:()=>M.on(I,H),onDidRemoveLastListener:()=>M.removeListener(I,H)});return B.event},E.fromDOMEventEmitter=function(M,I,F=H=>H){const H=(...k)=>B.fire(F(...k)),B=new c({onWillAddFirstListener:()=>M.addEventListener(I,H),onDidRemoveLastListener:()=>M.removeEventListener(I,H)});return B.event},E.toPromise=function(M){return new Promise((I=>A(M)(I)))},E.fromPromise=function(M){const I=new c;return M.then((F=>{I.fire(F)}),(()=>{I.fire(void 0)})).finally((()=>{I.dispose()})),I.event},E.forward=function(M,I){return M((F=>I.fire(F)))},E.runAndSubscribe=function(M,I,F){return I(F),M((H=>I(H)))};class D{constructor(I,F){this._observable=I,this._counter=0,this._hasChanged=!1;const H={onWillAddFirstListener:()=>{I.addObserver(this)},onDidRemoveLastListener:()=>{I.removeObserver(this)}};this.emitter=new c(H),F&&F.add(this.emitter)}beginUpdate(I){this._counter++}handlePossibleChange(I){}handleChange(I,F){this._hasChanged=!0}endUpdate(I){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}E.fromObservable=function(M,I){return new D(M,I).emitter.event},E.fromObservableLight=function(M){return(I,F,H)=>{let B=0,k=!1;const j={beginUpdate(){B++},endUpdate(){B--,B===0&&(M.reportChanges(),k&&(k=!1,I.call(F)))},handlePossibleChange(){},handleChange(){k=!0}};M.addObserver(j),M.reportChanges();const $={dispose(){M.removeObserver(j)}};return H instanceof n.DisposableStore?H.add($):Array.isArray(H)&&H.push($),$}}})(p||(t.Event=p={}));const T=class T{constructor(A){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${A}_${T._idPool++}`,T.all.add(this)}start(A){this._stopWatch=new g.StopWatch,this.listenerCount=A}stop(){if(this._stopWatch){const A=this._stopWatch.elapsed();this.durations.push(A),this.elapsedOverall+=A,this.invocationCount+=1,this._stopWatch=void 0}}};T.all=new Set,T._idPool=0;let u=T;t.EventProfiling=u;let r=-1;const C=class C{constructor(A,N,P=(C._idPool++).toString(16).padStart(3,"0")){this._errorHandler=A,this.threshold=N,this.name=P,this._warnCountdown=0}dispose(){var A;(A=this._stacks)==null||A.clear()}check(A,N){const P=this.threshold;if(P<=0||N<P)return;this._stacks||(this._stacks=new Map);const W=this._stacks.get(A.value)||0;if(this._stacks.set(A.value,W+1),this._warnCountdown-=1,this._warnCountdown<=0){this._warnCountdown=.5*P;const[w,y]=this.getMostFrequentStack(),S=`[${this.name}] potential listener LEAK detected, having ${N} listeners already. MOST frequent listener (${y}):`;console.warn(S),console.warn(w);const D=new e(S,w);this._errorHandler(D)}return()=>{const w=this._stacks.get(A.value)||0;this._stacks.set(A.value,w-1)}}getMostFrequentStack(){if(!this._stacks)return;let A,N=0;for(const[P,W]of this._stacks)(!A||N<W)&&(A=[P,W],N=W);return A}};C._idPool=1;let h=C;class s{static create(){const A=new Error;return new s(A.stack??"")}constructor(A){this.value=A}print(){console.warn(this.value.split(`
+`).slice(2).join(`
+`))}}class e extends Error{constructor(A,N){super(A),this.name="ListenerLeakError",this.stack=N}}t.ListenerLeakError=e;class l extends Error{constructor(A,N){super(A),this.name="ListenerRefusalError",this.stack=N}}t.ListenerRefusalError=l;let o=0;class d{constructor(A){this.value=A,this.id=o++}}class c{constructor(A){var N,P,W,w;this._size=0,this._options=A,this._leakageMon=r>0||(N=this._options)!=null&&N.leakWarningThreshold?new h((A==null?void 0:A.onListenerError)??i.onUnexpectedError,((P=this._options)==null?void 0:P.leakWarningThreshold)??r):void 0,this._perfMon=(W=this._options)!=null&&W._profName?new u(this._options._profName):void 0,this._deliveryQueue=(w=this._options)==null?void 0:w.deliveryQueue}dispose(){var A,N,P,W;this._disposed||(this._disposed=!0,((A=this._deliveryQueue)==null?void 0:A.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),(P=(N=this._options)==null?void 0:N.onDidRemoveLastListener)==null||P.call(N),(W=this._leakageMon)==null||W.dispose())}get event(){return this._event??(this._event=(A,N,P)=>{var S,D,M,I,F;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){const H=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(H);const B=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],k=new l(`${H}. HINT: Stack shows most frequent listener (${B[1]}-times)`,B[0]);return(((S=this._options)==null?void 0:S.onListenerError)||i.onUnexpectedError)(k),n.Disposable.None}if(this._disposed)return n.Disposable.None;N&&(A=A.bind(N));const W=new d(A);let w;this._leakageMon&&this._size>=Math.ceil(.2*this._leakageMon.threshold)&&(W.stack=s.create(),w=this._leakageMon.check(W.stack,this._size+1)),this._listeners?this._listeners instanceof d?(this._deliveryQueue??(this._deliveryQueue=new a),this._listeners=[this._listeners,W]):this._listeners.push(W):((M=(D=this._options)==null?void 0:D.onWillAddFirstListener)==null||M.call(D,this),this._listeners=W,(F=(I=this._options)==null?void 0:I.onDidAddFirstListener)==null||F.call(I,this)),this._size++;const y=(0,n.toDisposable)((()=>{w==null||w(),this._removeListener(W)}));return P instanceof n.DisposableStore?P.add(y):Array.isArray(P)&&P.push(y),y}),this._event}_removeListener(A){var w,y,S,D;if((y=(w=this._options)==null?void 0:w.onWillRemoveListener)==null||y.call(w,this),!this._listeners)return;if(this._size===1)return this._listeners=void 0,(D=(S=this._options)==null?void 0:S.onDidRemoveLastListener)==null||D.call(S,this),void(this._size=0);const N=this._listeners,P=N.indexOf(A);if(P===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,N[P]=void 0;const W=this._deliveryQueue.current===this;if(2*this._size<=N.length){let M=0;for(let I=0;I<N.length;I++)N[I]?N[M++]=N[I]:W&&(this._deliveryQueue.end--,M<this._deliveryQueue.i&&this._deliveryQueue.i--);N.length=M}}_deliver(A,N){var W;if(!A)return;const P=((W=this._options)==null?void 0:W.onListenerError)||i.onUnexpectedError;if(P)try{A.value(N)}catch(w){P(w)}else A.value(N)}_deliverQueue(A){const N=A.current._listeners;for(;A.i<A.end;)this._deliver(N[A.i++],A.value);A.reset()}fire(A){var N,P,W,w;if((N=this._deliveryQueue)!=null&&N.current&&(this._deliverQueue(this._deliveryQueue),(P=this._perfMon)==null||P.stop()),(W=this._perfMon)==null||W.start(this._size),this._listeners)if(this._listeners instanceof d)this._deliver(this._listeners,A);else{const y=this._deliveryQueue;y.enqueue(this,A,this._listeners.length),this._deliverQueue(y)}(w=this._perfMon)==null||w.stop()}hasListeners(){return this._size>0}}t.Emitter=c,t.createEventDeliveryQueue=()=>new a;class a{constructor(){this.i=-1,this.end=0}enqueue(A,N,P){this.i=0,this.end=P,this.current=A,this.value=N}reset(){this.i=this.end,this.current=void 0,this.value=void 0}}t.AsyncEmitter=class extends c{async fireAsync(E,A,N){if(this._listeners)for(this._asyncDeliveryQueue||(this._asyncDeliveryQueue=new f.LinkedList),((P,W)=>{if(P instanceof d)W(P);else for(let w=0;w<P.length;w++){const y=P[w];y&&W(y)}})(this._listeners,(P=>this._asyncDeliveryQueue.push([P.value,E])));this._asyncDeliveryQueue.size>0&&!A.isCancellationRequested;){const[P,W]=this._asyncDeliveryQueue.shift(),w=[],y={...W,token:A,waitUntil:S=>{if(Object.isFrozen(w))throw new Error("waitUntil can NOT be called asynchronous");N&&(S=N(S,P)),w.push(S)}};try{P(y)}catch(S){(0,i.onUnexpectedError)(S);continue}Object.freeze(w),await Promise.allSettled(w).then((S=>{for(const D of S)D.status==="rejected"&&(0,i.onUnexpectedError)(D.reason)}))}}};class m extends c{get isPaused(){return this._isPaused!==0}constructor(A){super(A),this._isPaused=0,this._eventQueue=new f.LinkedList,this._mergeFn=A==null?void 0:A.merge}pause(){this._isPaused++}resume(){if(this._isPaused!==0&&--this._isPaused==0)if(this._mergeFn){if(this._eventQueue.size>0){const A=Array.from(this._eventQueue);this._eventQueue.clear(),super.fire(this._mergeFn(A))}}else for(;!this._isPaused&&this._eventQueue.size!==0;)super.fire(this._eventQueue.shift())}fire(A){this._size&&(this._isPaused!==0?this._eventQueue.push(A):super.fire(A))}}t.PauseableEmitter=m,t.DebounceEmitter=class extends m{constructor(E){super(E),this._delay=E.delay??100}fire(E){this._handle||(this.pause(),this._handle=setTimeout((()=>{this._handle=void 0,this.resume()}),this._delay)),super.fire(E)}},t.MicrotaskEmitter=class extends c{constructor(E){super(E),this._queuedEvents=[],this._mergeFn=E==null?void 0:E.merge}fire(E){this.hasListeners()&&(this._queuedEvents.push(E),this._queuedEvents.length===1&&queueMicrotask((()=>{this._mergeFn?super.fire(this._mergeFn(this._queuedEvents)):this._queuedEvents.forEach((A=>super.fire(A))),this._queuedEvents=[]})))}};class b{constructor(){this.hasListeners=!1,this.events=[],this.emitter=new c({onWillAddFirstListener:()=>this.onFirstListenerAdd(),onDidRemoveLastListener:()=>this.onLastListenerRemove()})}get event(){return this.emitter.event}add(A){const N={event:A,listener:null};return this.events.push(N),this.hasListeners&&this.hook(N),(0,n.toDisposable)((0,v.createSingleCallFunction)((()=>{this.hasListeners&&this.unhook(N);const P=this.events.indexOf(N);this.events.splice(P,1)})))}onFirstListenerAdd(){this.hasListeners=!0,this.events.forEach((A=>this.hook(A)))}onLastListenerRemove(){this.hasListeners=!1,this.events.forEach((A=>this.unhook(A)))}hook(A){A.listener=A.event((N=>this.emitter.fire(N)))}unhook(A){var N;(N=A.listener)==null||N.dispose(),A.listener=null}dispose(){var A;this.emitter.dispose();for(const N of this.events)(A=N.listener)==null||A.dispose();this.events=[]}}t.EventMultiplexer=b,t.DynamicListEventMultiplexer=class{constructor(E,A,N,P){this._store=new n.DisposableStore;const W=this._store.add(new b),w=this._store.add(new n.DisposableMap);function y(S){w.set(S,W.add(P(S)))}for(const S of E)y(S);this._store.add(A((S=>{y(S)}))),this._store.add(N((S=>{w.deleteAndDispose(S)}))),this.event=W.event}dispose(){this._store.dispose()}},t.EventBufferer=class{constructor(){this.data=[]}wrapEvent(E,A,N){return(P,W,w)=>E((y=>{const S=this.data[this.data.length-1];if(!A)return void(S?S.buffers.push((()=>P.call(W,y))):P.call(W,y));const D=S;D?(D.items??(D.items=[]),D.items.push(y),D.buffers.length===0&&S.buffers.push((()=>{D.reducedResult??(D.reducedResult=N?D.items.reduce(A,N):D.items.reduce(A)),P.call(W,D.reducedResult)}))):P.call(W,A(N,y))}),void 0,w)}bufferEvents(E){const A={buffers:new Array};this.data.push(A);const N=E();return this.data.pop(),A.buffers.forEach((P=>P())),N}},t.Relay=class{constructor(){this.listening=!1,this.inputEvent=p.None,this.inputEventListener=n.Disposable.None,this.emitter=new c({onDidAddFirstListener:()=>{this.listening=!0,this.inputEventListener=this.inputEvent(this.emitter.fire,this.emitter)},onDidRemoveLastListener:()=>{this.listening=!1,this.inputEventListener.dispose()}}),this.event=this.emitter.event}set input(E){this.inputEvent=E,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=E(this.emitter.fire,this.emitter))}dispose(){this.inputEventListener.dispose(),this.emitter.dispose()}},t.ValueWithChangeEvent=class{static const(E){return new R(E)}constructor(E){this._value=E,this._onDidChange=new c,this.onDidChange=this._onDidChange.event}get value(){return this._value}set value(E){E!==this._value&&(this._value=E,this._onDidChange.fire(void 0))}};class R{constructor(A){this.value=A,this.onDidChange=p.None}}},8841:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createSingleCallFunction=function(_,i){const v=this;let n,f=!1;return function(){if(f)return n;if(f=!0,i)try{n=_.apply(v,arguments)}finally{i()}else n=_.apply(v,arguments);return n}}},6304:function(K,t,_){var i=this&&this.__createBinding||(Object.create?function(d,c,a,m){m===void 0&&(m=a);var b=Object.getOwnPropertyDescriptor(c,a);b&&!("get"in b?!c.__esModule:b.writable||b.configurable)||(b={enumerable:!0,get:function(){return c[a]}}),Object.defineProperty(d,m,b)}:function(d,c,a,m){m===void 0&&(m=a),d[m]=c[a]}),v=this&&this.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),n=this&&this.__importStar||function(d){if(d&&d.__esModule)return d;var c={};if(d!=null)for(var a in d)a!=="default"&&Object.prototype.hasOwnProperty.call(d,a)&&i(c,d,a);return v(c,d),c};Object.defineProperty(t,"__esModule",{value:!0}),t.StringSHA1=t.Hasher=void 0,t.hash=function(d){return g(d,0)},t.doHash=g,t.numberHash=p,t.stringHash=u,t.toHexString=e;const f=n(_(1316));function g(d,c){switch(typeof d){case"object":return d===null?p(349,c):Array.isArray(d)?(a=d,m=p(104579,m=c),a.reduce(((b,R)=>g(R,b)),m)):(function(b,R){return R=p(181387,R),Object.keys(b).sort().reduce(((T,C)=>(T=u(C,T),g(b[C],T))),R)})(d,c);case"string":return u(d,c);case"boolean":return(function(b,R){return p(b?433:863,R)})(d,c);case"number":return p(d,c);case"undefined":return p(937,c);default:return p(617,c)}var a,m}function p(d,c){return(c<<5)-c+d|0}function u(d,c){c=p(149417,c);for(let a=0,m=d.length;a<m;a++)c=p(d.charCodeAt(a),c);return c}var r;function h(d,c,a=32){const m=a-c;return(d<<c|(~((1<<m)-1)&d)>>>m)>>>0}function s(d,c=0,a=d.byteLength,m=0){for(let b=0;b<a;b++)d[c+b]=m}function e(d,c=32){return d instanceof ArrayBuffer?Array.from(new Uint8Array(d)).map((a=>a.toString(16).padStart(2,"0"))).join(""):(function(a,m,b="0"){for(;a.length<m;)a=b+a;return a})((d>>>0).toString(16),c/4)}t.Hasher=class{constructor(){this._value=0}get value(){return this._value}hash(d){return this._value=g(d,this._value),this._value}},(function(d){d[d.BLOCK_SIZE=64]="BLOCK_SIZE",d[d.UNICODE_REPLACEMENT=65533]="UNICODE_REPLACEMENT"})(r||(r={}));const o=class o{constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(r.BLOCK_SIZE+3),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(c){const a=c.length;if(a===0)return;const m=this._buff;let b,R,T=this._buffLen,C=this._leftoverHighSurrogate;for(C!==0?(b=C,R=-1,C=0):(b=c.charCodeAt(0),R=0);;){let E=b;if(f.isHighSurrogate(b)){if(!(R+1<a)){C=b;break}{const A=c.charCodeAt(R+1);f.isLowSurrogate(A)?(R++,E=f.computeCodePoint(b,A)):E=r.UNICODE_REPLACEMENT}}else f.isLowSurrogate(b)&&(E=r.UNICODE_REPLACEMENT);if(T=this._push(m,T,E),R++,!(R<a))break;b=c.charCodeAt(R)}this._buffLen=T,this._leftoverHighSurrogate=C}_push(c,a,m){return m<128?c[a++]=m:m<2048?(c[a++]=192|(1984&m)>>>6,c[a++]=128|(63&m)>>>0):m<65536?(c[a++]=224|(61440&m)>>>12,c[a++]=128|(4032&m)>>>6,c[a++]=128|(63&m)>>>0):(c[a++]=240|(1835008&m)>>>18,c[a++]=128|(258048&m)>>>12,c[a++]=128|(4032&m)>>>6,c[a++]=128|(63&m)>>>0),a>=r.BLOCK_SIZE&&(this._step(),a-=r.BLOCK_SIZE,this._totalLen+=r.BLOCK_SIZE,c[0]=c[r.BLOCK_SIZE+0],c[1]=c[r.BLOCK_SIZE+1],c[2]=c[r.BLOCK_SIZE+2]),a}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,r.UNICODE_REPLACEMENT)),this._totalLen+=this._buffLen,this._wrapUp()),e(this._h0)+e(this._h1)+e(this._h2)+e(this._h3)+e(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,s(this._buff,this._buffLen),this._buffLen>56&&(this._step(),s(this._buff));const c=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(c/4294967296),!1),this._buffDV.setUint32(60,c%4294967296,!1),this._step()}_step(){const c=o._bigBlock32,a=this._buffDV;for(let P=0;P<64;P+=4)c.setUint32(P,a.getUint32(P,!1),!1);for(let P=64;P<320;P+=4)c.setUint32(P,h(c.getUint32(P-12,!1)^c.getUint32(P-32,!1)^c.getUint32(P-56,!1)^c.getUint32(P-64,!1),1),!1);let m,b,R,T=this._h0,C=this._h1,E=this._h2,A=this._h3,N=this._h4;for(let P=0;P<80;P++)P<20?(m=C&E|~C&A,b=1518500249):P<40?(m=C^E^A,b=1859775393):P<60?(m=C&E|C&A|E&A,b=2400959708):(m=C^E^A,b=3395469782),R=h(T,5)+m+N+b+c.getUint32(4*P,!1)&4294967295,N=A,A=E,E=h(C,30),C=T,T=R;this._h0=this._h0+T&4294967295,this._h1=this._h1+C&4294967295,this._h2=this._h2+E&4294967295,this._h3=this._h3+A&4294967295,this._h4=this._h4+N&4294967295}};o._bigBlock32=new DataView(new ArrayBuffer(320));let l=o;t.StringSHA1=l},4218:(K,t)=>{var _;Object.defineProperty(t,"__esModule",{value:!0}),t.Iterable=void 0,(function(i){function v(g){return g&&typeof g=="object"&&typeof g[Symbol.iterator]=="function"}i.is=v;const n=Object.freeze([]);function*f(g){yield g}i.empty=function(){return n},i.single=f,i.wrap=function(g){return v(g)?g:f(g)},i.from=function(g){return g||n},i.reverse=function*(g){for(let p=g.length-1;p>=0;p--)yield g[p]},i.isEmpty=function(g){return!g||g[Symbol.iterator]().next().done===!0},i.first=function(g){return g[Symbol.iterator]().next().value},i.some=function(g,p){let u=0;for(const r of g)if(p(r,u++))return!0;return!1},i.find=function(g,p){for(const u of g)if(p(u))return u},i.filter=function*(g,p){for(const u of g)p(u)&&(yield u)},i.map=function*(g,p){let u=0;for(const r of g)yield p(r,u++)},i.flatMap=function*(g,p){let u=0;for(const r of g)yield*p(r,u++)},i.concat=function*(...g){for(const p of g)yield*p},i.reduce=function(g,p,u){let r=u;for(const h of g)r=p(r,h);return r},i.slice=function*(g,p,u=g.length){for(p<0&&(p+=g.length),u<0?u+=g.length:u>g.length&&(u=g.length);p<u;p++)yield g[p]},i.consume=function(g,p=Number.POSITIVE_INFINITY){const u=[];if(p===0)return[u,g];const r=g[Symbol.iterator]();for(let h=0;h<p;h++){const s=r.next();if(s.done)return[u,i.empty()];u.push(s.value)}return[u,{[Symbol.iterator]:()=>r}]},i.asyncToArray=async function(g){const p=[];for await(const u of g)p.push(u);return Promise.resolve(p)}})(_||(t.Iterable=_={}))},7883:(K,t)=>{var _,i;Object.defineProperty(t,"__esModule",{value:!0}),t.KeyMod=t.KeyCodeUtils=t.ScanCodeUtils=t.NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE=t.EVENT_KEY_CODE_MAP=t.ScanCode=t.KeyCode=void 0,t.KeyChord=function(e,l){return(e|(65535&l)<<16>>>0)>>>0},(function(e){e[e.DependsOnKbLayout=-1]="DependsOnKbLayout",e[e.Unknown=0]="Unknown",e[e.Backspace=1]="Backspace",e[e.Tab=2]="Tab",e[e.Enter=3]="Enter",e[e.Shift=4]="Shift",e[e.Ctrl=5]="Ctrl",e[e.Alt=6]="Alt",e[e.PauseBreak=7]="PauseBreak",e[e.CapsLock=8]="CapsLock",e[e.Escape=9]="Escape",e[e.Space=10]="Space",e[e.PageUp=11]="PageUp",e[e.PageDown=12]="PageDown",e[e.End=13]="End",e[e.Home=14]="Home",e[e.LeftArrow=15]="LeftArrow",e[e.UpArrow=16]="UpArrow",e[e.RightArrow=17]="RightArrow",e[e.DownArrow=18]="DownArrow",e[e.Insert=19]="Insert",e[e.Delete=20]="Delete",e[e.Digit0=21]="Digit0",e[e.Digit1=22]="Digit1",e[e.Digit2=23]="Digit2",e[e.Digit3=24]="Digit3",e[e.Digit4=25]="Digit4",e[e.Digit5=26]="Digit5",e[e.Digit6=27]="Digit6",e[e.Digit7=28]="Digit7",e[e.Digit8=29]="Digit8",e[e.Digit9=30]="Digit9",e[e.KeyA=31]="KeyA",e[e.KeyB=32]="KeyB",e[e.KeyC=33]="KeyC",e[e.KeyD=34]="KeyD",e[e.KeyE=35]="KeyE",e[e.KeyF=36]="KeyF",e[e.KeyG=37]="KeyG",e[e.KeyH=38]="KeyH",e[e.KeyI=39]="KeyI",e[e.KeyJ=40]="KeyJ",e[e.KeyK=41]="KeyK",e[e.KeyL=42]="KeyL",e[e.KeyM=43]="KeyM",e[e.KeyN=44]="KeyN",e[e.KeyO=45]="KeyO",e[e.KeyP=46]="KeyP",e[e.KeyQ=47]="KeyQ",e[e.KeyR=48]="KeyR",e[e.KeyS=49]="KeyS",e[e.KeyT=50]="KeyT",e[e.KeyU=51]="KeyU",e[e.KeyV=52]="KeyV",e[e.KeyW=53]="KeyW",e[e.KeyX=54]="KeyX",e[e.KeyY=55]="KeyY",e[e.KeyZ=56]="KeyZ",e[e.Meta=57]="Meta",e[e.ContextMenu=58]="ContextMenu",e[e.F1=59]="F1",e[e.F2=60]="F2",e[e.F3=61]="F3",e[e.F4=62]="F4",e[e.F5=63]="F5",e[e.F6=64]="F6",e[e.F7=65]="F7",e[e.F8=66]="F8",e[e.F9=67]="F9",e[e.F10=68]="F10",e[e.F11=69]="F11",e[e.F12=70]="F12",e[e.F13=71]="F13",e[e.F14=72]="F14",e[e.F15=73]="F15",e[e.F16=74]="F16",e[e.F17=75]="F17",e[e.F18=76]="F18",e[e.F19=77]="F19",e[e.F20=78]="F20",e[e.F21=79]="F21",e[e.F22=80]="F22",e[e.F23=81]="F23",e[e.F24=82]="F24",e[e.NumLock=83]="NumLock",e[e.ScrollLock=84]="ScrollLock",e[e.Semicolon=85]="Semicolon",e[e.Equal=86]="Equal",e[e.Comma=87]="Comma",e[e.Minus=88]="Minus",e[e.Period=89]="Period",e[e.Slash=90]="Slash",e[e.Backquote=91]="Backquote",e[e.BracketLeft=92]="BracketLeft",e[e.Backslash=93]="Backslash",e[e.BracketRight=94]="BracketRight",e[e.Quote=95]="Quote",e[e.OEM_8=96]="OEM_8",e[e.IntlBackslash=97]="IntlBackslash",e[e.Numpad0=98]="Numpad0",e[e.Numpad1=99]="Numpad1",e[e.Numpad2=100]="Numpad2",e[e.Numpad3=101]="Numpad3",e[e.Numpad4=102]="Numpad4",e[e.Numpad5=103]="Numpad5",e[e.Numpad6=104]="Numpad6",e[e.Numpad7=105]="Numpad7",e[e.Numpad8=106]="Numpad8",e[e.Numpad9=107]="Numpad9",e[e.NumpadMultiply=108]="NumpadMultiply",e[e.NumpadAdd=109]="NumpadAdd",e[e.NUMPAD_SEPARATOR=110]="NUMPAD_SEPARATOR",e[e.NumpadSubtract=111]="NumpadSubtract",e[e.NumpadDecimal=112]="NumpadDecimal",e[e.NumpadDivide=113]="NumpadDivide",e[e.KEY_IN_COMPOSITION=114]="KEY_IN_COMPOSITION",e[e.ABNT_C1=115]="ABNT_C1",e[e.ABNT_C2=116]="ABNT_C2",e[e.AudioVolumeMute=117]="AudioVolumeMute",e[e.AudioVolumeUp=118]="AudioVolumeUp",e[e.AudioVolumeDown=119]="AudioVolumeDown",e[e.BrowserSearch=120]="BrowserSearch",e[e.BrowserHome=121]="BrowserHome",e[e.BrowserBack=122]="BrowserBack",e[e.BrowserForward=123]="BrowserForward",e[e.MediaTrackNext=124]="MediaTrackNext",e[e.MediaTrackPrevious=125]="MediaTrackPrevious",e[e.MediaStop=126]="MediaStop",e[e.MediaPlayPause=127]="MediaPlayPause",e[e.LaunchMediaPlayer=128]="LaunchMediaPlayer",e[e.LaunchMail=129]="LaunchMail",e[e.LaunchApp2=130]="LaunchApp2",e[e.Clear=131]="Clear",e[e.MAX_VALUE=132]="MAX_VALUE"})(_||(t.KeyCode=_={})),(function(e){e[e.DependsOnKbLayout=-1]="DependsOnKbLayout",e[e.None=0]="None",e[e.Hyper=1]="Hyper",e[e.Super=2]="Super",e[e.Fn=3]="Fn",e[e.FnLock=4]="FnLock",e[e.Suspend=5]="Suspend",e[e.Resume=6]="Resume",e[e.Turbo=7]="Turbo",e[e.Sleep=8]="Sleep",e[e.WakeUp=9]="WakeUp",e[e.KeyA=10]="KeyA",e[e.KeyB=11]="KeyB",e[e.KeyC=12]="KeyC",e[e.KeyD=13]="KeyD",e[e.KeyE=14]="KeyE",e[e.KeyF=15]="KeyF",e[e.KeyG=16]="KeyG",e[e.KeyH=17]="KeyH",e[e.KeyI=18]="KeyI",e[e.KeyJ=19]="KeyJ",e[e.KeyK=20]="KeyK",e[e.KeyL=21]="KeyL",e[e.KeyM=22]="KeyM",e[e.KeyN=23]="KeyN",e[e.KeyO=24]="KeyO",e[e.KeyP=25]="KeyP",e[e.KeyQ=26]="KeyQ",e[e.KeyR=27]="KeyR",e[e.KeyS=28]="KeyS",e[e.KeyT=29]="KeyT",e[e.KeyU=30]="KeyU",e[e.KeyV=31]="KeyV",e[e.KeyW=32]="KeyW",e[e.KeyX=33]="KeyX",e[e.KeyY=34]="KeyY",e[e.KeyZ=35]="KeyZ",e[e.Digit1=36]="Digit1",e[e.Digit2=37]="Digit2",e[e.Digit3=38]="Digit3",e[e.Digit4=39]="Digit4",e[e.Digit5=40]="Digit5",e[e.Digit6=41]="Digit6",e[e.Digit7=42]="Digit7",e[e.Digit8=43]="Digit8",e[e.Digit9=44]="Digit9",e[e.Digit0=45]="Digit0",e[e.Enter=46]="Enter",e[e.Escape=47]="Escape",e[e.Backspace=48]="Backspace",e[e.Tab=49]="Tab",e[e.Space=50]="Space",e[e.Minus=51]="Minus",e[e.Equal=52]="Equal",e[e.BracketLeft=53]="BracketLeft",e[e.BracketRight=54]="BracketRight",e[e.Backslash=55]="Backslash",e[e.IntlHash=56]="IntlHash",e[e.Semicolon=57]="Semicolon",e[e.Quote=58]="Quote",e[e.Backquote=59]="Backquote",e[e.Comma=60]="Comma",e[e.Period=61]="Period",e[e.Slash=62]="Slash",e[e.CapsLock=63]="CapsLock",e[e.F1=64]="F1",e[e.F2=65]="F2",e[e.F3=66]="F3",e[e.F4=67]="F4",e[e.F5=68]="F5",e[e.F6=69]="F6",e[e.F7=70]="F7",e[e.F8=71]="F8",e[e.F9=72]="F9",e[e.F10=73]="F10",e[e.F11=74]="F11",e[e.F12=75]="F12",e[e.PrintScreen=76]="PrintScreen",e[e.ScrollLock=77]="ScrollLock",e[e.Pause=78]="Pause",e[e.Insert=79]="Insert",e[e.Home=80]="Home",e[e.PageUp=81]="PageUp",e[e.Delete=82]="Delete",e[e.End=83]="End",e[e.PageDown=84]="PageDown",e[e.ArrowRight=85]="ArrowRight",e[e.ArrowLeft=86]="ArrowLeft",e[e.ArrowDown=87]="ArrowDown",e[e.ArrowUp=88]="ArrowUp",e[e.NumLock=89]="NumLock",e[e.NumpadDivide=90]="NumpadDivide",e[e.NumpadMultiply=91]="NumpadMultiply",e[e.NumpadSubtract=92]="NumpadSubtract",e[e.NumpadAdd=93]="NumpadAdd",e[e.NumpadEnter=94]="NumpadEnter",e[e.Numpad1=95]="Numpad1",e[e.Numpad2=96]="Numpad2",e[e.Numpad3=97]="Numpad3",e[e.Numpad4=98]="Numpad4",e[e.Numpad5=99]="Numpad5",e[e.Numpad6=100]="Numpad6",e[e.Numpad7=101]="Numpad7",e[e.Numpad8=102]="Numpad8",e[e.Numpad9=103]="Numpad9",e[e.Numpad0=104]="Numpad0",e[e.NumpadDecimal=105]="NumpadDecimal",e[e.IntlBackslash=106]="IntlBackslash",e[e.ContextMenu=107]="ContextMenu",e[e.Power=108]="Power",e[e.NumpadEqual=109]="NumpadEqual",e[e.F13=110]="F13",e[e.F14=111]="F14",e[e.F15=112]="F15",e[e.F16=113]="F16",e[e.F17=114]="F17",e[e.F18=115]="F18",e[e.F19=116]="F19",e[e.F20=117]="F20",e[e.F21=118]="F21",e[e.F22=119]="F22",e[e.F23=120]="F23",e[e.F24=121]="F24",e[e.Open=122]="Open",e[e.Help=123]="Help",e[e.Select=124]="Select",e[e.Again=125]="Again",e[e.Undo=126]="Undo",e[e.Cut=127]="Cut",e[e.Copy=128]="Copy",e[e.Paste=129]="Paste",e[e.Find=130]="Find",e[e.AudioVolumeMute=131]="AudioVolumeMute",e[e.AudioVolumeUp=132]="AudioVolumeUp",e[e.AudioVolumeDown=133]="AudioVolumeDown",e[e.NumpadComma=134]="NumpadComma",e[e.IntlRo=135]="IntlRo",e[e.KanaMode=136]="KanaMode",e[e.IntlYen=137]="IntlYen",e[e.Convert=138]="Convert",e[e.NonConvert=139]="NonConvert",e[e.Lang1=140]="Lang1",e[e.Lang2=141]="Lang2",e[e.Lang3=142]="Lang3",e[e.Lang4=143]="Lang4",e[e.Lang5=144]="Lang5",e[e.Abort=145]="Abort",e[e.Props=146]="Props",e[e.NumpadParenLeft=147]="NumpadParenLeft",e[e.NumpadParenRight=148]="NumpadParenRight",e[e.NumpadBackspace=149]="NumpadBackspace",e[e.NumpadMemoryStore=150]="NumpadMemoryStore",e[e.NumpadMemoryRecall=151]="NumpadMemoryRecall",e[e.NumpadMemoryClear=152]="NumpadMemoryClear",e[e.NumpadMemoryAdd=153]="NumpadMemoryAdd",e[e.NumpadMemorySubtract=154]="NumpadMemorySubtract",e[e.NumpadClear=155]="NumpadClear",e[e.NumpadClearEntry=156]="NumpadClearEntry",e[e.ControlLeft=157]="ControlLeft",e[e.ShiftLeft=158]="ShiftLeft",e[e.AltLeft=159]="AltLeft",e[e.MetaLeft=160]="MetaLeft",e[e.ControlRight=161]="ControlRight",e[e.ShiftRight=162]="ShiftRight",e[e.AltRight=163]="AltRight",e[e.MetaRight=164]="MetaRight",e[e.BrightnessUp=165]="BrightnessUp",e[e.BrightnessDown=166]="BrightnessDown",e[e.MediaPlay=167]="MediaPlay",e[e.MediaRecord=168]="MediaRecord",e[e.MediaFastForward=169]="MediaFastForward",e[e.MediaRewind=170]="MediaRewind",e[e.MediaTrackNext=171]="MediaTrackNext",e[e.MediaTrackPrevious=172]="MediaTrackPrevious",e[e.MediaStop=173]="MediaStop",e[e.Eject=174]="Eject",e[e.MediaPlayPause=175]="MediaPlayPause",e[e.MediaSelect=176]="MediaSelect",e[e.LaunchMail=177]="LaunchMail",e[e.LaunchApp2=178]="LaunchApp2",e[e.LaunchApp1=179]="LaunchApp1",e[e.SelectTask=180]="SelectTask",e[e.LaunchScreenSaver=181]="LaunchScreenSaver",e[e.BrowserSearch=182]="BrowserSearch",e[e.BrowserHome=183]="BrowserHome",e[e.BrowserBack=184]="BrowserBack",e[e.BrowserForward=185]="BrowserForward",e[e.BrowserStop=186]="BrowserStop",e[e.BrowserRefresh=187]="BrowserRefresh",e[e.BrowserFavorites=188]="BrowserFavorites",e[e.ZoomToggle=189]="ZoomToggle",e[e.MailReply=190]="MailReply",e[e.MailForward=191]="MailForward",e[e.MailSend=192]="MailSend",e[e.MAX_VALUE=193]="MAX_VALUE"})(i||(t.ScanCode=i={}));class v{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(l,o){this._keyCodeToStr[l]=o,this._strToKeyCode[o.toLowerCase()]=l}keyCodeToStr(l){return this._keyCodeToStr[l]}strToKeyCode(l){return this._strToKeyCode[l.toLowerCase()]||_.Unknown}}const n=new v,f=new v,g=new v;t.EVENT_KEY_CODE_MAP=new Array(230),t.NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE={};const p=[],u=Object.create(null),r=Object.create(null);var h,s;t.ScanCodeUtils={lowerCaseToEnum:e=>r[e]||i.None,toEnum:e=>u[e]||i.None,toString:e=>p[e]||"None"},(function(e){e.toString=function(l){return n.keyCodeToStr(l)},e.fromString=function(l){return n.strToKeyCode(l)},e.toUserSettingsUS=function(l){return f.keyCodeToStr(l)},e.toUserSettingsGeneral=function(l){return g.keyCodeToStr(l)},e.fromUserSettings=function(l){return f.strToKeyCode(l)||g.strToKeyCode(l)},e.toElectronAccelerator=function(l){if(l>=_.Numpad0&&l<=_.NumpadDivide)return null;switch(l){case _.UpArrow:return"Up";case _.DownArrow:return"Down";case _.LeftArrow:return"Left";case _.RightArrow:return"Right"}return n.keyCodeToStr(l)}})(h||(t.KeyCodeUtils=h={})),(function(e){e[e.CtrlCmd=2048]="CtrlCmd",e[e.Shift=1024]="Shift",e[e.Alt=512]="Alt",e[e.WinCtrl=256]="WinCtrl"})(s||(t.KeyMod=s={}))},2811:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ResolvedKeybinding=t.ResolvedChord=t.Keybinding=t.ScanCodeChord=t.KeyCodeChord=void 0,t.decodeKeybinding=function(h,s){if(typeof h=="number"){if(h===0)return null;const e=(65535&h)>>>0,l=(4294901760&h)>>>16;return new r(l!==0?[g(e,s),g(l,s)]:[g(e,s)])}{const e=[];for(let l=0;l<h.length;l++)e.push(g(h[l],s));return new r(e)}},t.createSimpleKeybinding=g;const i=_(9807),v=_(7883),n=_(8163);var f;function g(h,s){const e=!!(h&f.CtrlCmd),l=!!(h&f.WinCtrl),o=s===n.OperatingSystem.Macintosh?l:e,d=!!(h&f.Shift),c=!!(h&f.Alt),a=s===n.OperatingSystem.Macintosh?e:l,m=h&f.KeyCode;return new p(o,d,c,a,m)}(function(h){h[h.CtrlCmd=2048]="CtrlCmd",h[h.Shift=1024]="Shift",h[h.Alt=512]="Alt",h[h.WinCtrl=256]="WinCtrl",h[h.KeyCode=255]="KeyCode"})(f||(f={}));class p{constructor(s,e,l,o,d){this.ctrlKey=s,this.shiftKey=e,this.altKey=l,this.metaKey=o,this.keyCode=d}equals(s){return s instanceof p&&this.ctrlKey===s.ctrlKey&&this.shiftKey===s.shiftKey&&this.altKey===s.altKey&&this.metaKey===s.metaKey&&this.keyCode===s.keyCode}getHashCode(){return`K${this.ctrlKey?"1":"0"}${this.shiftKey?"1":"0"}${this.altKey?"1":"0"}${this.metaKey?"1":"0"}${this.keyCode}`}isModifierKey(){return this.keyCode===v.KeyCode.Unknown||this.keyCode===v.KeyCode.Ctrl||this.keyCode===v.KeyCode.Meta||this.keyCode===v.KeyCode.Alt||this.keyCode===v.KeyCode.Shift}toKeybinding(){return new r([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===v.KeyCode.Ctrl||this.shiftKey&&this.keyCode===v.KeyCode.Shift||this.altKey&&this.keyCode===v.KeyCode.Alt||this.metaKey&&this.keyCode===v.KeyCode.Meta}}t.KeyCodeChord=p;class u{constructor(s,e,l,o,d){this.ctrlKey=s,this.shiftKey=e,this.altKey=l,this.metaKey=o,this.scanCode=d}equals(s){return s instanceof u&&this.ctrlKey===s.ctrlKey&&this.shiftKey===s.shiftKey&&this.altKey===s.altKey&&this.metaKey===s.metaKey&&this.scanCode===s.scanCode}getHashCode(){return`S${this.ctrlKey?"1":"0"}${this.shiftKey?"1":"0"}${this.altKey?"1":"0"}${this.metaKey?"1":"0"}${this.scanCode}`}isDuplicateModifierCase(){return this.ctrlKey&&(this.scanCode===v.ScanCode.ControlLeft||this.scanCode===v.ScanCode.ControlRight)||this.shiftKey&&(this.scanCode===v.ScanCode.ShiftLeft||this.scanCode===v.ScanCode.ShiftRight)||this.altKey&&(this.scanCode===v.ScanCode.AltLeft||this.scanCode===v.ScanCode.AltRight)||this.metaKey&&(this.scanCode===v.ScanCode.MetaLeft||this.scanCode===v.ScanCode.MetaRight)}}t.ScanCodeChord=u;class r{constructor(s){if(s.length===0)throw(0,i.illegalArgument)("chords");this.chords=s}getHashCode(){let s="";for(let e=0,l=this.chords.length;e<l;e++)e!==0&&(s+=";"),s+=this.chords[e].getHashCode();return s}equals(s){if(s===null||this.chords.length!==s.chords.length)return!1;for(let e=0;e<this.chords.length;e++)if(!this.chords[e].equals(s.chords[e]))return!1;return!0}}t.Keybinding=r,t.ResolvedChord=class{constructor(h,s,e,l,o,d){this.ctrlKey=h,this.shiftKey=s,this.altKey=e,this.metaKey=l,this.keyLabel=o,this.keyAriaLabel=d}},t.ResolvedKeybinding=class{}},626:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Lazy=void 0,t.Lazy=class{constructor(_){this.executor=_,this._didRun=!1}get hasValue(){return this._didRun}get value(){if(!this._didRun)try{this._value=this.executor()}catch(_){this._error=_}finally{this._didRun=!0}if(this._error)throw this._error;return this._value}get rawValue(){return this._value}}},7150:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DisposableMap=t.ImmortalReference=t.AsyncReferenceCollection=t.ReferenceCollection=t.SafeDisposable=t.RefCountedDisposable=t.MandatoryMutableDisposable=t.MutableDisposable=t.Disposable=t.DisposableStore=t.DisposableTracker=void 0,t.setDisposableTracker=function(C){p=C},t.trackDisposable=r,t.markAsDisposed=h,t.markAsSingleton=function(C){return p==null||p.markAsSingleton(C),C},t.isDisposable=e,t.dispose=l,t.disposeIfDisposable=function(C){for(const E of C)e(E)&&E.dispose();return[]},t.combinedDisposable=function(...C){const E=o((()=>l(C)));return(function(A,N){if(p)for(const P of A)p.setParent(P,N)})(C,E),E},t.toDisposable=o,t.disposeOnReturn=function(C){const E=new d;try{C(E)}finally{E.dispose()}};const i=_(3058),v=_(9087),n=_(2608),f=_(8841),g=_(4218);let p=null;const b=class b{constructor(){this.livingDisposables=new Map}getDisposableData(E){let A=this.livingDisposables.get(E);return A||(A={parent:null,source:null,isSingleton:!1,value:E,idx:b.idx++},this.livingDisposables.set(E,A)),A}trackDisposable(E){const A=this.getDisposableData(E);A.source||(A.source=new Error().stack)}setParent(E,A){this.getDisposableData(E).parent=A}markAsDisposed(E){this.livingDisposables.delete(E)}markAsSingleton(E){this.getDisposableData(E).isSingleton=!0}getRootParent(E,A){const N=A.get(E);if(N)return N;const P=E.parent?this.getRootParent(this.getDisposableData(E.parent),A):E;return A.set(E,P),P}getTrackedDisposables(){const E=new Map;return[...this.livingDisposables.entries()].filter((([,A])=>A.source!==null&&!this.getRootParent(A,E).isSingleton)).flatMap((([A])=>A))}computeLeakingDisposables(E=10,A){let N;if(A)N=A;else{const S=new Map,D=[...this.livingDisposables.values()].filter((I=>I.source!==null&&!this.getRootParent(I,S).isSingleton));if(D.length===0)return;const M=new Set(D.map((I=>I.value)));if(N=D.filter((I=>!(I.parent&&M.has(I.parent)))),N.length===0)throw new Error("There are cyclic diposable chains!")}if(!N)return;function P(S){const D=S.source.split(`
+`).map((M=>M.trim().replace("at ",""))).filter((M=>M!==""));return(function(M,I){for(;M.length>0&&I.some((F=>typeof F=="string"?F===M[0]:M[0].match(F)));)M.shift()})(D,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),D.reverse()}const W=new n.SetMap;for(const S of N){const D=P(S);for(let M=0;M<=D.length;M++)W.add(D.slice(0,M).join(`
+`),S)}N.sort((0,i.compareBy)((S=>S.idx),i.numberComparator));let w="",y=0;for(const S of N.slice(0,E)){y++;const D=P(S),M=[];for(let I=0;I<D.length;I++){let F=D[I];F=`(shared with ${W.get(D.slice(0,I+1).join(`
+`)).size}/${N.length} leaks) at ${F}`;const H=W.get(D.slice(0,I).join(`
+`)),B=(0,v.groupBy)([...H].map((k=>P(k)[I])),(k=>k));delete B[D[I]];for(const[k,j]of Object.entries(B))M.unshift(` - stacktraces of ${j.length} other leaks continue with ${k}`);M.unshift(F)}w+=`
+
+
+==================== Leaking disposable ${y}/${N.length}: ${S.value.constructor.name} ====================
+${M.join(`
+`)}
+============================================================
+
+`}return N.length>E&&(w+=`
+
+
+... and ${N.length-E} more leaking disposables
+
+`),{leaks:N,details:w}}};b.idx=0;let u=b;function r(C){return p==null||p.trackDisposable(C),C}function h(C){p==null||p.markAsDisposed(C)}function s(C,E){p==null||p.setParent(C,E)}function e(C){return typeof C=="object"&&C!==null&&typeof C.dispose=="function"&&C.dispose.length===0}function l(C){if(g.Iterable.is(C)){const E=[];for(const A of C)if(A)try{A.dispose()}catch(N){E.push(N)}if(E.length===1)throw E[0];if(E.length>1)throw new AggregateError(E,"Encountered errors while disposing of store");return Array.isArray(C)?[]:C}if(C)return C.dispose(),C}function o(C){const E=r({dispose:(0,f.createSingleCallFunction)((()=>{h(E),C()}))});return E}t.DisposableTracker=u;const R=class R{constructor(){this._toDispose=new Set,this._isDisposed=!1,r(this)}dispose(){this._isDisposed||(h(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{l(this._toDispose)}finally{this._toDispose.clear()}}add(E){if(!E)return E;if(E===this)throw new Error("Cannot register a disposable on itself!");return s(E,this),this._isDisposed?R.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(E),E}delete(E){if(E){if(E===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(E),E.dispose()}}deleteAndLeak(E){E&&this._toDispose.has(E)&&(this._toDispose.delete(E),s(E,null))}};R.DISABLE_DISPOSED_WARNING=!1;let d=R;t.DisposableStore=d;const T=class T{constructor(){this._store=new d,r(this),s(this._store,this)}dispose(){h(this),this._store.dispose()}_register(E){if(E===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(E)}};T.None=Object.freeze({dispose(){}});let c=T;t.Disposable=c;class a{constructor(){this._isDisposed=!1,r(this)}get value(){return this._isDisposed?void 0:this._value}set value(E){var A;this._isDisposed||E===this._value||((A=this._value)==null||A.dispose(),E&&s(E,this),this._value=E)}clear(){this.value=void 0}dispose(){var E;this._isDisposed=!0,h(this),(E=this._value)==null||E.dispose(),this._value=void 0}clearAndLeak(){const E=this._value;return this._value=void 0,E&&s(E,null),E}}t.MutableDisposable=a,t.MandatoryMutableDisposable=class{constructor(C){this._disposable=new a,this._isDisposed=!1,this._disposable.value=C}get value(){return this._disposable.value}set value(C){this._isDisposed||C===this._disposable.value||(this._disposable.value=C)}dispose(){this._isDisposed=!0,this._disposable.dispose()}},t.RefCountedDisposable=class{constructor(C){this._disposable=C,this._counter=1}acquire(){return this._counter++,this}release(){return--this._counter==0&&this._disposable.dispose(),this}},t.SafeDisposable=class{constructor(){this.dispose=()=>{},this.unset=()=>{},this.isset=()=>!1,r(this)}set(C){let E=C;return this.unset=()=>E=void 0,this.isset=()=>E!==void 0,this.dispose=()=>{E&&(E(),E=void 0,h(this))},this}},t.ReferenceCollection=class{constructor(){this.references=new Map}acquire(C,...E){let A=this.references.get(C);A||(A={counter:0,object:this.createReferencedObject(C,...E)},this.references.set(C,A));const{object:N}=A,P=(0,f.createSingleCallFunction)((()=>{--A.counter==0&&(this.destroyReferencedObject(C,A.object),this.references.delete(C))}));return A.counter++,{object:N,dispose:P}}},t.AsyncReferenceCollection=class{constructor(C){this.referenceCollection=C}async acquire(C,...E){const A=this.referenceCollection.acquire(C,...E);try{return{object:await A.object,dispose:()=>A.dispose()}}catch(N){throw A.dispose(),N}}},t.ImmortalReference=class{constructor(C){this.object=C}dispose(){}};class m{constructor(){this._store=new Map,this._isDisposed=!1,r(this)}dispose(){h(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{l(this._store.values())}finally{this._store.clear()}}has(E){return this._store.has(E)}get size(){return this._store.size}get(E){return this._store.get(E)}set(E,A,N=!1){var P;this._isDisposed&&console.warn(new Error("Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!").stack),N||((P=this._store.get(E))==null||P.dispose()),this._store.set(E,A)}deleteAndDispose(E){var A;(A=this._store.get(E))==null||A.dispose(),this._store.delete(E)}deleteAndLeak(E){const A=this._store.get(E);return this._store.delete(E),A}keys(){return this._store.keys()}values(){return this._store.values()}[Symbol.iterator](){return this._store[Symbol.iterator]()}}t.DisposableMap=m},6317:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LinkedList=void 0;const v=class v{constructor(f){this.element=f,this.next=v.Undefined,this.prev=v.Undefined}};v.Undefined=new v(void 0);let _=v;class i{constructor(){this._first=_.Undefined,this._last=_.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===_.Undefined}clear(){let f=this._first;for(;f!==_.Undefined;){const g=f.next;f.prev=_.Undefined,f.next=_.Undefined,f=g}this._first=_.Undefined,this._last=_.Undefined,this._size=0}unshift(f){return this._insert(f,!1)}push(f){return this._insert(f,!0)}_insert(f,g){const p=new _(f);if(this._first===_.Undefined)this._first=p,this._last=p;else if(g){const r=this._last;this._last=p,p.prev=r,r.next=p}else{const r=this._first;this._first=p,p.next=r,r.prev=p}this._size+=1;let u=!1;return()=>{u||(u=!0,this._remove(p))}}shift(){if(this._first!==_.Undefined){const f=this._first.element;return this._remove(this._first),f}}pop(){if(this._last!==_.Undefined){const f=this._last.element;return this._remove(this._last),f}}_remove(f){if(f.prev!==_.Undefined&&f.next!==_.Undefined){const g=f.prev;g.next=f.next,f.next.prev=g}else f.prev===_.Undefined&&f.next===_.Undefined?(this._first=_.Undefined,this._last=_.Undefined):f.next===_.Undefined?(this._last=this._last.prev,this._last.next=_.Undefined):f.prev===_.Undefined&&(this._first=this._first.next,this._first.prev=_.Undefined);this._size-=1}*[Symbol.iterator](){let f=this._first;for(;f!==_.Undefined;)yield f.element,f=f.next}}t.LinkedList=i},2608:(K,t)=>{var _;Object.defineProperty(t,"__esModule",{value:!0}),t.SetMap=t.BidirectionalMap=t.CounterSet=t.Touch=void 0,t.getOrSet=function(i,v,n){let f=i.get(v);return f===void 0&&(f=n,i.set(v,f)),f},t.mapToString=function(i){const v=[];return i.forEach(((n,f)=>{v.push(`${f} => ${n}`)})),`Map(${i.size}) {${v.join(", ")}}`},t.setToString=function(i){const v=[];return i.forEach((n=>{v.push(n)})),`Set(${i.size}) {${v.join(", ")}}`},t.mapsStrictEqualIgnoreOrder=function(i,v){if(i===v)return!0;if(i.size!==v.size)return!1;for(const[n,f]of i)if(!v.has(n)||v.get(n)!==f)return!1;for(const[n]of v)if(!i.has(n))return!1;return!0},(function(i){i[i.None=0]="None",i[i.AsOld=1]="AsOld",i[i.AsNew=2]="AsNew"})(_||(t.Touch=_={})),t.CounterSet=class{constructor(){this.map=new Map}add(i){return this.map.set(i,(this.map.get(i)||0)+1),this}delete(i){let v=this.map.get(i)||0;return v!==0&&(v--,v===0?this.map.delete(i):this.map.set(i,v),!0)}has(i){return this.map.has(i)}},t.BidirectionalMap=class{constructor(i){if(this._m1=new Map,this._m2=new Map,i)for(const[v,n]of i)this.set(v,n)}clear(){this._m1.clear(),this._m2.clear()}set(i,v){this._m1.set(i,v),this._m2.set(v,i)}get(i){return this._m1.get(i)}getKey(i){return this._m2.get(i)}delete(i){const v=this._m1.get(i);return v!==void 0&&(this._m1.delete(i),this._m2.delete(v),!0)}forEach(i,v){this._m1.forEach(((n,f)=>{i.call(v,n,f,this)}))}keys(){return this._m1.keys()}values(){return this._m1.values()}},t.SetMap=class{constructor(){this.map=new Map}add(i,v){let n=this.map.get(i);n||(n=new Set,this.map.set(i,n)),n.add(v)}delete(i,v){const n=this.map.get(i);n&&(n.delete(v),n.size===0&&this.map.delete(i))}forEach(i,v){const n=this.map.get(i);n&&n.forEach(v)}get(i){return this.map.get(i)||new Set}}},7704:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SlidingWindowAverage=t.MovingAverage=t.Counter=void 0,t.clamp=function(_,i,v){return Math.min(Math.max(_,i),v)},t.rot=function(_,i){return(i+_%i)%i},t.isPointWithinTriangle=function(_,i,v,n,f,g,p,u){const r=p-v,h=u-n,s=f-v,e=g-n,l=_-v,o=i-n,d=r*r+h*h,c=r*s+h*e,a=r*l+h*o,m=s*s+e*e,b=s*l+e*o,R=1/(d*m-c*c),T=(m*a-c*b)*R,C=(d*b-c*a)*R;return T>=0&&C>=0&&T+C<1},t.Counter=class{constructor(){this._next=0}getNext(){return this._next++}},t.MovingAverage=class{constructor(){this._n=1,this._val=0}update(_){return this._val=this._val+(_-this._val)/this._n,this._n+=1,this._val}get value(){return this._val}},t.SlidingWindowAverage=class{constructor(_){this._n=0,this._val=0,this._values=[],this._index=0,this._sum=0,this._values=new Array(_),this._values.fill(0,0,_)}update(_){const i=this._values[this._index];return this._values[this._index]=_,this._index=(this._index+1)%this._values.length,this._sum-=i,this._sum+=_,this._n<this._values.length&&(this._n+=1),this._val=this._sum/this._n,this._val}get value(){return this._val}}},8163:(K,t)=>{var P,W,w;Object.defineProperty(t,"__esModule",{value:!0}),t.isAndroid=t.isEdge=t.isSafari=t.isFirefox=t.isChrome=t.OS=t.OperatingSystem=t.setTimeout0=t.setTimeout0IsFaster=t.translationsConfigFile=t.platformLocale=t.locale=t.Language=t.language=t.userAgent=t.platform=t.isCI=t.isMobile=t.isIOS=t.webWorkerOrigin=t.isWebWorker=t.isWeb=t.isElectron=t.isNative=t.isLinuxSnap=t.isLinux=t.isMacintosh=t.isWindows=t.Platform=t.LANGUAGE_DEFAULT=void 0,t.PlatformToString=function(y){switch(y){case R.Web:return"Web";case R.Mac:return"Mac";case R.Linux:return"Linux";case R.Windows:return"Windows"}},t.isLittleEndian=function(){if(!N){N=!0;const y=new Uint8Array(2);y[0]=1,y[1]=2,A=new Uint16Array(y.buffer)[0]===513}return A},t.isBigSurOrNewer=function(y){return parseFloat(y)>=20},t.LANGUAGE_DEFAULT="en";let _,i,v,n=!1,f=!1,g=!1,p=!1,u=!1,r=!1,h=!1,s=!1,e=!1,l=!1,o=t.LANGUAGE_DEFAULT,d=t.LANGUAGE_DEFAULT;const c=globalThis;let a;c.vscode!==void 0&&c.vscode.process!==void 0?a=c.vscode.process:typeof process<"u"&&typeof((P=process==null?void 0:process.versions)==null?void 0:P.node)=="string"&&(a=process);const m=typeof((W=a==null?void 0:a.versions)==null?void 0:W.electron)=="string",b=m&&(a==null?void 0:a.type)==="renderer";if(typeof a=="object"){n=a.platform==="win32",f=a.platform==="darwin",g=a.platform==="linux",p=g&&!!a.env.SNAP&&!!a.env.SNAP_REVISION,h=m,e=!!a.env.CI||!!a.env.BUILD_ARTIFACTSTAGINGDIRECTORY,_=t.LANGUAGE_DEFAULT,o=t.LANGUAGE_DEFAULT;const y=a.env.VSCODE_NLS_CONFIG;if(y)try{const S=JSON.parse(y);_=S.userLocale,d=S.osLocale,o=S.resolvedLanguage||t.LANGUAGE_DEFAULT,i=(w=S.languagePack)==null?void 0:w.translationsConfigFile}catch{}u=!0}else typeof navigator!="object"||b?console.error("Unable to resolve platform."):(v=navigator.userAgent,n=v.indexOf("Windows")>=0,f=v.indexOf("Macintosh")>=0,s=(v.indexOf("Macintosh")>=0||v.indexOf("iPad")>=0||v.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,g=v.indexOf("Linux")>=0,l=(v==null?void 0:v.indexOf("Mobi"))>=0,r=!0,o=globalThis._VSCODE_NLS_LANGUAGE||t.LANGUAGE_DEFAULT,_=navigator.language.toLowerCase(),d=_);var R;(function(y){y[y.Web=0]="Web",y[y.Mac=1]="Mac",y[y.Linux=2]="Linux",y[y.Windows=3]="Windows"})(R||(t.Platform=R={}));let T=R.Web;var C,E;f?T=R.Mac:n?T=R.Windows:g&&(T=R.Linux),t.isWindows=n,t.isMacintosh=f,t.isLinux=g,t.isLinuxSnap=p,t.isNative=u,t.isElectron=h,t.isWeb=r,t.isWebWorker=r&&typeof c.importScripts=="function",t.webWorkerOrigin=t.isWebWorker?c.origin:void 0,t.isIOS=s,t.isMobile=l,t.isCI=e,t.platform=T,t.userAgent=v,t.language=o,(function(y){y.value=function(){return t.language},y.isDefaultVariant=function(){return t.language.length===2?t.language==="en":t.language.length>=3&&t.language[0]==="e"&&t.language[1]==="n"&&t.language[2]==="-"},y.isDefault=function(){return t.language==="en"}})(C||(t.Language=C={})),t.locale=_,t.platformLocale=d,t.translationsConfigFile=i,t.setTimeout0IsFaster=typeof c.postMessage=="function"&&!c.importScripts,t.setTimeout0=(()=>{if(t.setTimeout0IsFaster){const y=[];c.addEventListener("message",(D=>{if(D.data&&D.data.vscodeScheduleAsyncWork)for(let M=0,I=y.length;M<I;M++){const F=y[M];if(F.id===D.data.vscodeScheduleAsyncWork)return y.splice(M,1),void F.callback()}}));let S=0;return D=>{const M=++S;y.push({id:M,callback:D}),c.postMessage({vscodeScheduleAsyncWork:M},"*")}}return y=>setTimeout(y)})(),(function(y){y[y.Windows=1]="Windows",y[y.Macintosh=2]="Macintosh",y[y.Linux=3]="Linux"})(E||(t.OperatingSystem=E={})),t.OS=f||s?E.Macintosh:n?E.Windows:E.Linux;let A=!0,N=!1;t.isChrome=!!(t.userAgent&&t.userAgent.indexOf("Chrome")>=0),t.isFirefox=!!(t.userAgent&&t.userAgent.indexOf("Firefox")>=0),t.isSafari=!!(!t.isChrome&&t.userAgent&&t.userAgent.indexOf("Safari")>=0),t.isEdge=!!(t.userAgent&&t.userAgent.indexOf("Edg/")>=0),t.isAndroid=!!(t.userAgent&&t.userAgent.indexOf("Android")>=0)},9881:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SmoothScrollingOperation=t.SmoothScrollingUpdate=t.Scrollable=t.ScrollState=t.ScrollbarVisibility=void 0;const i=_(802),v=_(7150);var n;(function(h){h[h.Auto=1]="Auto",h[h.Hidden=2]="Hidden",h[h.Visible=3]="Visible"})(n||(t.ScrollbarVisibility=n={}));class f{constructor(s,e,l,o,d,c,a){this._forceIntegerValues=s,this._scrollStateBrand=void 0,this._forceIntegerValues&&(e|=0,l|=0,o|=0,d|=0,c|=0,a|=0),this.rawScrollLeft=o,this.rawScrollTop=a,e<0&&(e=0),o+e>l&&(o=l-e),o<0&&(o=0),d<0&&(d=0),a+d>c&&(a=c-d),a<0&&(a=0),this.width=e,this.scrollWidth=l,this.scrollLeft=o,this.height=d,this.scrollHeight=c,this.scrollTop=a}equals(s){return this.rawScrollLeft===s.rawScrollLeft&&this.rawScrollTop===s.rawScrollTop&&this.width===s.width&&this.scrollWidth===s.scrollWidth&&this.scrollLeft===s.scrollLeft&&this.height===s.height&&this.scrollHeight===s.scrollHeight&&this.scrollTop===s.scrollTop}withScrollDimensions(s,e){return new f(this._forceIntegerValues,s.width!==void 0?s.width:this.width,s.scrollWidth!==void 0?s.scrollWidth:this.scrollWidth,e?this.rawScrollLeft:this.scrollLeft,s.height!==void 0?s.height:this.height,s.scrollHeight!==void 0?s.scrollHeight:this.scrollHeight,e?this.rawScrollTop:this.scrollTop)}withScrollPosition(s){return new f(this._forceIntegerValues,this.width,this.scrollWidth,s.scrollLeft!==void 0?s.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,s.scrollTop!==void 0?s.scrollTop:this.rawScrollTop)}createScrollEvent(s,e){const l=this.width!==s.width,o=this.scrollWidth!==s.scrollWidth,d=this.scrollLeft!==s.scrollLeft,c=this.height!==s.height,a=this.scrollHeight!==s.scrollHeight,m=this.scrollTop!==s.scrollTop;return{inSmoothScrolling:e,oldWidth:s.width,oldScrollWidth:s.scrollWidth,oldScrollLeft:s.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:s.height,oldScrollHeight:s.scrollHeight,oldScrollTop:s.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:l,scrollWidthChanged:o,scrollLeftChanged:d,heightChanged:c,scrollHeightChanged:a,scrollTopChanged:m}}}t.ScrollState=f;class g extends v.Disposable{constructor(s){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new i.Emitter),this.onScroll=this._onScroll.event,this._smoothScrollDuration=s.smoothScrollDuration,this._scheduleAtNextAnimationFrame=s.scheduleAtNextAnimationFrame,this._state=new f(s.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(s){this._smoothScrollDuration=s}validateScrollPosition(s){return this._state.withScrollPosition(s)}getScrollDimensions(){return this._state}setScrollDimensions(s,e){var o;const l=this._state.withScrollDimensions(s,e);this._setState(l,!!this._smoothScrolling),(o=this._smoothScrolling)==null||o.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(s){const e=this._state.withScrollPosition(s);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(e,!1)}setScrollPositionSmooth(s,e){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(s);if(this._smoothScrolling){s={scrollLeft:s.scrollLeft===void 0?this._smoothScrolling.to.scrollLeft:s.scrollLeft,scrollTop:s.scrollTop===void 0?this._smoothScrolling.to.scrollTop:s.scrollTop};const l=this._state.withScrollPosition(s);if(this._smoothScrolling.to.scrollLeft===l.scrollLeft&&this._smoothScrolling.to.scrollTop===l.scrollTop)return;let o;o=e?new r(this._smoothScrolling.from,l,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,l,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=o}else{const l=this._state.withScrollPosition(s);this._smoothScrolling=r.start(this._state,l,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame((()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())}))}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;const s=this._smoothScrolling.tick(),e=this._state.withScrollPosition(s);return this._setState(e,!0),this._smoothScrolling?s.isDone?(this._smoothScrolling.dispose(),void(this._smoothScrolling=null)):void(this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame((()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())}))):void 0}_setState(s,e){const l=this._state;l.equals(s)||(this._state=s,this._onScroll.fire(this._state.createScrollEvent(l,e)))}}t.Scrollable=g;class p{constructor(s,e,l){this.scrollLeft=s,this.scrollTop=e,this.isDone=l}}function u(h,s){const e=s-h;return function(l){return h+e*(1-(o=1-l,Math.pow(o,3)));var o}}t.SmoothScrollingUpdate=p;class r{constructor(s,e,l,o){this.from=s,this.to=e,this.duration=o,this.startTime=l,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(s,e,l){if(Math.abs(s-e)>2.5*l){let a,m;return s<e?(a=s+.75*l,m=e-.75*l):(a=s-.75*l,m=e+.75*l),o=u(s,a),d=u(m,e),c=.33,function(b){return b<c?o(b/c):d((b-c)/(1-c))}}var o,d,c;return u(s,e)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(s){this.to=s.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(s){const e=(s-this.startTime)/this.duration;if(e<1){const l=this.scrollLeft(e),o=this.scrollTop(e);return new p(l,o,!1)}return new p(this.to.scrollLeft,this.to.scrollTop,!0)}combine(s,e,l){return r.start(s,e,l)}static start(s,e,l){l+=10;const o=Date.now()-10;return new r(s,e,o,l)}}t.SmoothScrollingOperation=r},9725:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StopWatch=void 0;const _=globalThis.performance&&typeof globalThis.performance.now=="function";class i{static create(n){return new i(n)}constructor(n){this._now=_&&n===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}}t.StopWatch=i},1316:(K,t,_)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noBreakWhitespace=t.CodePointIterator=void 0,t.isFalsyOrWhitespace=function(c){return!c||typeof c!="string"||c.trim().length===0},t.format=function(c,...a){return a.length===0?c:c.replace(n,(function(m,b){const R=parseInt(b,10);return isNaN(R)||R<0||R>=a.length?m:a[R]}))},t.format2=function(c,a){return Object.keys(a).length===0?c:c.replace(f,((m,b)=>a[b]??m))},t.htmlAttributeEncodeValue=function(c){return c.replace(/[<>"'&]/g,(a=>{switch(a){case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";case"'":return"&apos;";case"&":return"&amp;"}return a}))},t.escape=function(c){return c.replace(/[<>&]/g,(function(a){switch(a){case"<":return"&lt;";case">":return"&gt;";case"&":return"&amp;";default:return a}}))},t.escapeRegExpCharacters=g,t.count=function(c,a){let m=0,b=c.indexOf(a);for(;b!==-1;)m++,b=c.indexOf(a,b+a.length);return m},t.truncate=function(c,a,m="\u2026"){return c.length<=a?c:`${c.substr(0,a)}${m}`},t.truncateMiddle=function(c,a,m="\u2026"){if(c.length<=a)return c;const b=Math.ceil(a/2)-m.length/2,R=Math.floor(a/2)-m.length/2;return`${c.substr(0,b)}${m}${c.substr(c.length-R)}`},t.trim=function(c,a=" "){return u(p(c,a),a)},t.ltrim=p,t.rtrim=u,t.convertSimple2RegExpPattern=function(c){return c.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,"\\$&").replace(/[\*]/g,".*")},t.stripWildcards=function(c){return c.replace(/\*/g,"")},t.createRegExp=function(c,a,m={}){if(!c)throw new Error("Cannot create regex from empty string");a||(c=g(c)),m.wholeWord&&(/\B/.test(c.charAt(0))||(c="\\b"+c),/\B/.test(c.charAt(c.length-1))||(c+="\\b"));let b="";return m.global&&(b+="g"),m.matchCase||(b+="i"),m.multiline&&(b+="m"),m.unicode&&(b+="u"),new RegExp(c,b)},t.regExpLeadsToEndlessLoop=function(c){return c.source!=="^"&&c.source!=="^$"&&c.source!=="$"&&c.source!=="^\\s*$"&&!(!c.exec("")||c.lastIndex!==0)},t.splitLines=function(c){return c.split(/\r\n|\r|\n/)},t.splitLinesIncludeSeparators=function(c){const a=[],m=c.split(/(\r\n|\r|\n)/);for(let b=0;b<Math.ceil(m.length/2);b++)a.push(m[2*b]+(m[2*b+1]??""));return a},t.firstNonWhitespaceIndex=function(c){for(let a=0,m=c.length;a<m;a++){const b=c.charCodeAt(a);if(b!==i.CharCode.Space&&b!==i.CharCode.Tab)return a}return-1},t.getLeadingWhitespace=function(c,a=0,m=c.length){for(let b=a;b<m;b++){const R=c.charCodeAt(b);if(R!==i.CharCode.Space&&R!==i.CharCode.Tab)return c.substring(a,b)}return c.substring(a,m)},t.lastNonWhitespaceIndex=function(c,a=c.length-1){for(let m=a;m>=0;m--){const b=c.charCodeAt(m);if(b!==i.CharCode.Space&&b!==i.CharCode.Tab)return m}return-1},t.replaceAsync=function(c,a,m){const b=[];let R=0;for(const T of c.matchAll(a)){if(b.push(c.slice(R,T.index)),T.index===void 0)throw new Error("match.index should be defined");R=T.index+T[0].length,b.push(m(T[0],...T.slice(1),T.index,c,T.groups))}return b.push(c.slice(R)),Promise.all(b).then((T=>T.join("")))},t.compare=function(c,a){return c<a?-1:c>a?1:0},t.compareSubstring=r,t.compareIgnoreCase=function(c,a){return h(c,a,0,c.length,0,a.length)},t.compareSubstringIgnoreCase=h,t.isAsciiDigit=function(c){return c>=i.CharCode.Digit0&&c<=i.CharCode.Digit9},t.isLowerAsciiLetter=s,t.isUpperAsciiLetter=function(c){return c>=i.CharCode.A&&c<=i.CharCode.Z},t.equalsIgnoreCase=function(c,a){return c.length===a.length&&h(c,a)===0},t.startsWithIgnoreCase=function(c,a){const m=a.length;return!(a.length>c.length)&&h(c,a,0,m)===0},t.commonPrefixLength=function(c,a){const m=Math.min(c.length,a.length);let b;for(b=0;b<m;b++)if(c.charCodeAt(b)!==a.charCodeAt(b))return b;return m},t.commonSuffixLength=function(c,a){const m=Math.min(c.length,a.length);let b;const R=c.length-1,T=a.length-1;for(b=0;b<m;b++)if(c.charCodeAt(R-b)!==a.charCodeAt(T-b))return b;return m},t.isHighSurrogate=e,t.isLowSurrogate=l,t.computeCodePoint=o,t.getNextCodePoint=d;const i=_(4869),v=_(8960),n=/{(\d+)}/g,f=/{([^}]+)}/g;function g(c){return c.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g,"\\$&")}function p(c,a){if(!c||!a)return c;const m=a.length;if(m===0||c.length===0)return c;let b=0;for(;c.indexOf(a,b)===b;)b+=m;return c.substring(b)}function u(c,a){if(!c||!a)return c;const m=a.length,b=c.length;if(m===0||b===0)return c;let R=b,T=-1;for(;T=c.lastIndexOf(a,R-1),T!==-1&&T+m===R;){if(T===0)return"";R=T}return c.substring(0,R)}function r(c,a,m=0,b=c.length,R=0,T=a.length){for(;m<b&&R<T;m++,R++){const A=c.charCodeAt(m),N=a.charCodeAt(R);if(A<N)return-1;if(A>N)return 1}const C=b-m,E=T-R;return C<E?-1:C>E?1:0}function h(c,a,m=0,b=c.length,R=0,T=a.length){for(;m<b&&R<T;m++,R++){let A=c.charCodeAt(m),N=a.charCodeAt(R);if(A===N)continue;if(A>=128||N>=128)return r(c.toLowerCase(),a.toLowerCase(),m,b,R,T);s(A)&&(A-=32),s(N)&&(N-=32);const P=A-N;if(P!==0)return P}const C=b-m,E=T-R;return C<E?-1:C>E?1:0}function s(c){return c>=i.CharCode.a&&c<=i.CharCode.z}function e(c){return 55296<=c&&c<=56319}function l(c){return 56320<=c&&c<=57343}function o(c,a){return a-56320+(c-55296<<10)+65536}function d(c,a,m){const b=c.charCodeAt(m);if(e(b)&&m+1<a){const R=c.charCodeAt(m+1);if(l(R))return o(b,R)}return b}t.CodePointIterator=class{get offset(){return this._offset}constructor(c,a=0){this._str=c,this._len=c.length,this._offset=a}setOffset(c){this._offset=c}prevCodePoint(){const c=(function(a,m){const b=a.charCodeAt(m-1);if(l(b)&&m>1){const R=a.charCodeAt(m-2);if(e(R))return o(R,b)}return b})(this._str,this._offset);return this._offset-=c>=v.Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN?2:1,c}nextCodePoint(){const c=d(this._str,this._len,this._offset);return this._offset+=c>=v.Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN?2:1,c}eol(){return this._offset>=this._len}},t.noBreakWhitespace="\xA0"},5015:(K,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MicrotaskDelay=void 0,t.MicrotaskDelay=Symbol("MicrotaskDelay")},8960:(K,t)=>{var _;Object.defineProperty(t,"__esModule",{value:!0}),t.Constants=void 0,t.toUint8=function(i){return i<0?0:i>_.MAX_UINT_8?_.MAX_UINT_8:0|i},t.toUint32=function(i){return i<0?0:i>_.MAX_UINT_32?_.MAX_UINT_32:0|i},(function(i){i[i.MAX_SAFE_SMALL_INTEGER=1073741824]="MAX_SAFE_SMALL_INTEGER",i[i.MIN_SAFE_SMALL_INTEGER=-1073741824]="MIN_SAFE_SMALL_INTEGER",i[i.MAX_UINT_8=255]="MAX_UINT_8",i[i.MAX_UINT_16=65535]="MAX_UINT_16",i[i.MAX_UINT_32=4294967295]="MAX_UINT_32",i[i.UNICODE_SUPPLEMENTARY_PLANE_BEGIN=65536]="UNICODE_SUPPLEMENTARY_PLANE_BEGIN"})(_||(t.Constants=_={}))}},De={};function de(K){var t=De[K];if(t!==void 0)return t.exports;var _=De[K]={exports:{}};return Oe[K].call(_.exports,_,_.exports,de),_.exports}var Re={};return(()=>{var K=Re;Object.defineProperty(K,"__esModule",{value:!0}),K.Terminal=void 0;const t=de(7721),_=de(1718),i=de(7150),v=de(3027),n=de(5101),f=de(6097),g=de(4335),p=["cols","rows"];let u=0;class r extends i.Disposable{constructor(s){super(),this._core=this._register(new _.CoreBrowserTerminal(s)),this._addonManager=this._register(new v.AddonManager),this._publicOptions={...this._core.options};const e=o=>this._core.options[o],l=(o,d)=>{this._checkReadonlyOptions(o),this._core.options[o]=d};for(const o in this._core.options){const d={get:e.bind(this,o),set:l.bind(this,o)};Object.defineProperty(this._publicOptions,o,d)}}_checkReadonlyOptions(s){if(p.includes(s))throw new Error(`Option "${s}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new f.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new g.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new n.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const s=this._core.coreService.decPrivateModes;let e="none";switch(this._core.coreMouseService.activeProtocol){case"X10":e="x10";break;case"VT200":e="vt200";break;case"DRAG":e="drag";break;case"ANY":e="any"}return{applicationCursorKeysMode:s.applicationCursorKeys,applicationKeypadMode:s.applicationKeypad,bracketedPasteMode:s.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:e,originMode:s.origin,reverseWraparoundMode:s.reverseWraparound,sendFocusMode:s.sendFocus,synchronizedOutputMode:s.synchronizedOutput,wraparoundMode:s.wraparound}}get options(){return this._publicOptions}set options(s){for(const e in s)this._publicOptions[e]=s[e]}blur(){this._core.blur()}focus(){this._core.focus()}input(s,e=!0){this._core.input(s,e)}resize(s,e){this._verifyIntegers(s,e),this._core.resize(s,e)}open(s){this._core.open(s)}attachCustomKeyEventHandler(s){this._core.attachCustomKeyEventHandler(s)}attachCustomWheelEventHandler(s){this._core.attachCustomWheelEventHandler(s)}registerLinkProvider(s){return this._core.registerLinkProvider(s)}registerCharacterJoiner(s){return this._checkProposedApi(),this._core.registerCharacterJoiner(s)}deregisterCharacterJoiner(s){this._checkProposedApi(),this._core.deregisterCharacterJoiner(s)}registerMarker(s=0){return this._verifyIntegers(s),this._core.registerMarker(s)}registerDecoration(s){return this._checkProposedApi(),this._verifyPositiveIntegers(s.x??0,s.width??0,s.height??0),this._core.registerDecoration(s)}hasSelection(){return this._core.hasSelection()}select(s,e,l){this._verifyIntegers(s,e,l),this._core.select(s,e,l)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(s,e){this._verifyIntegers(s,e),this._core.selectLines(s,e)}dispose(){super.dispose()}scrollLines(s){this._verifyIntegers(s),this._core.scrollLines(s)}scrollPages(s){this._verifyIntegers(s),this._core.scrollPages(s)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(s){this._verifyIntegers(s),this._core.scrollToLine(s)}clear(){this._core.clear()}write(s,e){this._core.write(s,e)}writeln(s,e){this._core.write(s),this._core.write(`\r
+`,e)}paste(s){this._core.paste(s)}refresh(s,e){this._verifyIntegers(s,e),this._core.refresh(s,e)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(s){this._addonManager.loadAddon(this,s)}static get strings(){return{get promptLabel(){return t.promptLabel.get()},set promptLabel(s){t.promptLabel.set(s)},get tooMuchOutput(){return t.tooMuchOutput.get()},set tooMuchOutput(s){t.tooMuchOutput.set(s)}}}_verifyIntegers(...s){for(u of s)if(u===1/0||isNaN(u)||u%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...s){for(u of s)if(u&&(u===1/0||isNaN(u)||u%1!=0||u<0))throw new Error("This API only accepts positive integers")}}K.Terminal=r})(),Re})()));
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.kt
new file mode 100644
index 00000000..4794c791
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.kt
@@ -0,0 +1,119 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.togetherWith
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.AccessTicket
+import com.codync.android.core.CloudComputer
+import androidx.compose.ui.draw.clip
+import com.kyant.shapes.RoundedRectangle
+import com.codync.android.design.*
+import kotlinx.coroutines.delay
+
+private enum class AccessPhase { Asking, Code, Approved, Ended }
+
+/** Asks an account computer for this phone: the code to check on it, until it answers (iOS `AccessRequestView`). */
+@Composable internal fun AccessRequestView(state: AppState, store: AppStore, computer: CloudComputer) {
+ val dismiss = LocalDismissModal.current
+ val ticket = state.access?.takeIf { it.computerId == computer.computerId }
+ val approved = state.computers.any { it.id == computer.computerId }
+ // The request ran and is over without an approval: denied, expired, or it failed.
+ var asked by remember { mutableStateOf("access" in state.busy) }
+ var ended by remember { mutableStateOf<String?>(null) }
+ val asking = "access" in state.busy
+ LaunchedEffect(Unit) { if (!asking && !approved) store.requestAccess(computer) }
+ LaunchedEffect(asking, approved) {
+ if (asking) asked = true
+ else if (asked && !approved) { ended = state.error ?: "${computer.name} didn't approve this request."; store.clearError(); asked = false }
+ }
+ LaunchedEffect(approved) {
+ if (!approved) return@LaunchedEffect
+ Analytics.capture(AnalyticsEvent.ComputerPaired, mapOf("via" to "account", "computer" to Analytics.computerTag(computer.computerId)))
+ delay(1000); dismiss()
+ }
+ val phase = when {
+ approved -> AccessPhase.Approved
+ ticket != null -> AccessPhase.Code
+ ended != null -> AccessPhase.Ended
+ else -> AccessPhase.Asking
+ }
+ // Closing keeps waiting in the background; the computer shows up once approved.
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader("Access")
+ Column(Modifier.fillMaxWidth().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(24.dp)) {
+ ComputerBadge(computer.device, 64.dp)
+ AnimatedContent(phase, transitionSpec = { fadeIn(Motion.fade()) togetherWith fadeOut(Motion.fade()) }, label = "Access") { shown ->
+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(24.dp)) {
+ when (shown) {
+ AccessPhase.Approved -> IconLabel("${computer.name} approved this phone", "checkmark.circle.fill", Palette.added, style = Type.headline)
+ AccessPhase.Code -> {
+ val code = ticket?.code.orEmpty()
+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text("Check the code on ${computer.name}", style = Type.headline, color = Palette.text)
+ SelectionContainer {
+ Text(if (code.length == 6) "${code.take(3)} ${code.takeLast(3)}" else code,
+ Modifier.semantics { contentDescription = "Code ${code.toList().joinToString(" ")}" },
+ style = Type.system(52f, FontWeight.SemiBold).copy(fontFamily = FontFamily.Monospace), color = Palette.text)
+ }
+ Text("Approve only if the computer shows exactly this code. If it doesn't, deny it there: someone may be trying to get in.",
+ style = Type.subheadline, color = Palette.secondary, textAlign = TextAlign.Center)
+ }
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Spinner()
+ Text("Waiting for approval…", style = Type.subheadline, color = Palette.secondary)
+ IconButton("Cancel request", "xmark.circle.fill") { store.cancelAccess(); dismiss() }
+ }
+ }
+ AccessPhase.Ended -> {
+ Text(ended.orEmpty(), style = Type.body, color = Palette.secondary, textAlign = TextAlign.Center)
+ SecondaryButton("Ask again") { ended = null; store.requestAccess(computer) }
+ }
+ AccessPhase.Asking -> Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Spinner()
+ Text(if (computer.online != false) "Asking ${computer.name}…" else "${computer.name} is offline. Turn it on to continue.",
+ style = Type.subheadline, color = Palette.secondary, textAlign = TextAlign.Center)
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/** The pending access request over the tabs: approve on that computer, or cancel. */
+@Composable internal fun AccessBanner(ticket: AccessTicket, name: String, cancel: () -> Unit) {
+ Row(Modifier.padding(horizontal = 16.dp).fillMaxWidth().clip(RoundedRectangle(16.dp)).background(Palette.bubbleAgent)
+ .padding(start = 14.dp, end = 6.dp, top = 8.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Spinner(16.dp)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(1.dp)) {
+ Text("Approve on $name", style = Type.subheadline.medium, color = Palette.text)
+ Text("Code ${ticket.code.take(3)} ${ticket.code.takeLast(3)}", style = Type.footnote.monospacedDigit, color = Palette.secondary)
+ }
+ IconButton("Cancel request", "xmark", action = cancel)
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountSwitcherView.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountSwitcherView.kt
new file mode 100644
index 00000000..6254800d
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountSwitcherView.kt
@@ -0,0 +1,141 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.expandVertically
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.shrinkVertically
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.semantics.clearAndSetSemantics
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.selected
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import coil3.compose.AsyncImage
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+
+/** Who you're signed in as, the other accounts on this phone, and the way to the computers (iOS `AccountSwitcherView`). */
+@Composable internal fun AccountSwitcherView(state: AppState, store: AppStore, showSettings: () -> Unit, pair: () -> Unit) {
+ val account = state.account
+ val current = account.accounts.firstOrNull { it.userId == account.userId }
+ val busy = "session" in state.busy
+ var confirmSignOut by remember { mutableStateOf(false) }
+ var addingAccount by remember { mutableStateOf(false) }
+ LaunchedEffect(account.userId) { addingAccount = false }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader("Account") { if (busy) ThinkingOrb(ThinkingOrbState.Connecting, 20.dp, modifier = Modifier.semantics { contentDescription = "Signing in" }) }
+ CardForm(Modifier.weight(1f)) {
+ Row(Modifier.fillMaxWidth().clip(RoundedRectangle(18.dp)).background(Palette.bubbleAgent).plainButton(action = pair).padding(16.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Symbol("qrcode.viewfinder", size = 24.dp, tint = Palette.text)
+ Text("Scan a computer's code", Modifier.weight(1f), style = Type.body.medium, color = Palette.text)
+ Symbol("chevron.right", size = 13.dp, tint = Palette.tertiary)
+ }
+ // The big picture: your face and address when signed in, both login options when not.
+ Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(if (current != null) 10.dp else 16.dp)) {
+ if (current != null) {
+ AccountAvatar(current.avatar, current.email, 76.dp)
+ Text(current.email, style = Type.subheadline.medium, color = Palette.text, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
+ } else {
+ Box(Modifier.size(76.dp).clip(Capsule()).background(Palette.bubbleAgent).clearAndSetSemantics {}, contentAlignment = Alignment.Center) {
+ Symbol("person.fill", size = 34.dp, tint = Palette.tertiary)
+ }
+ if (account.configured) SignInButtons(state, store)
+ else IconLabel("QR pairing only in this build", "qrcode", Palette.secondary)
+ }
+ }
+ if (current != null && (account.multiple || account.accounts.size > 1)) {
+ Switcher(state, store, busy) { addingAccount = !addingAccount }
+ AnimatedVisibility(addingAccount, enter = fadeIn(Motion.fade()) + expandVertically(Motion.layoutSize),
+ exit = fadeOut(Motion.fade()) + shrinkVertically(Motion.layoutSize)) { SignInButtons(state, store) }
+ }
+ CardSection {
+ row { RowLabel("Computers", "desktopcomputer", chevron = true, modifier = Modifier.plainButton(action = showSettings)) }
+ if (current != null) row {
+ RowLabel("Sign out", "rectangle.portrait.and.arrow.right", Palette.danger,
+ modifier = Modifier.plainButton(enabled = !busy) { confirmSignOut = true })
+ }
+ }
+ account.error?.let { IconLabel(it, "exclamationmark.triangle.fill", Palette.danger) }
+ }
+ }
+ CodyncDialog("Sign out of ${current?.email ?: "this account"}?", confirmSignOut, { confirmSignOut = false },
+ "This phone forgets the account's computers. Your bots stay on them.") {
+ listOf(DialogAction("Sign out", destructive = true, action = store::signOut))
+ }
+}
+
+/** Every account on this phone as a face; tap one to switch, + to add another. */
+@Composable private fun Switcher(state: AppState, store: AppStore, busy: Boolean, add: () -> Unit) {
+ Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 4.dp),
+ horizontalArrangement = Arrangement.spacedBy(14.dp, Alignment.CenterHorizontally), verticalAlignment = Alignment.CenterVertically) {
+ for (item in state.account.accounts) {
+ val current = item.userId == state.account.userId
+ Box(Modifier.clip(Capsule()).border(2.dp, if (current) Palette.accent else Color.Transparent, Capsule())
+ .plainButton(enabled = !busy && !current) { store.switchAccount(item) }
+ .semantics { contentDescription = item.email; selected = current }.padding(3.dp)) {
+ AccountAvatar(item.avatar, item.email, 44.dp)
+ }
+ }
+ if (state.account.multiple) Box(Modifier.size(50.dp).clip(Capsule()).background(Palette.bubbleAgent).plainButton(enabled = !busy, action = add)
+ .semantics { contentDescription = "Add account" }, contentAlignment = Alignment.Center) {
+ Symbol("plus", size = 20.dp, tint = Palette.secondary)
+ }
+ }
+}
+
+/** An icon and a short name, with a chevron when it leads somewhere. */
+@Composable internal fun RowLabel(title: String, systemImage: String, tint: Color = Palette.text, chevron: Boolean = false,
+ modifier: Modifier = Modifier) {
+ Row(modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Box(Modifier.width(26.dp), contentAlignment = Alignment.Center) { Symbol(systemImage, size = 20.dp, tint = tint) }
+ Text(title, Modifier.weight(1f), style = Type.body, color = tint)
+ if (chevron) Symbol("chevron.right", size = 13.dp, tint = Palette.tertiary)
+ }
+}
+
+/** The account's photo; its first letter on a tinted circle until (or unless) the photo loads. */
+@Composable internal fun AccountAvatar(url: String?, email: String?, size: Dp) {
+ Box(Modifier.size(size).clip(Capsule()).background(Palette.bubbleUser).clearAndSetSemantics {}, contentAlignment = Alignment.Center) {
+ val letter = email?.firstOrNull()
+ if (letter != null) Text(letter.uppercase(), style = Type.system(size.value * 0.42f, FontWeight.SemiBold), color = Palette.text)
+ else Symbol("person.fill", size = size * 0.5f, tint = Palette.tertiary)
+ if (url != null) AsyncImage(url, null, imageLoader = LocalNetworkImages.current, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
+ }
+}
+
+/** The account face of the roster's top bar. */
+@Composable internal fun AccountAvatar(state: AppState, size: Dp) {
+ val current = state.account.accounts.firstOrNull { it.userId == state.account.userId }
+ AccountAvatar(current?.avatar, current?.email, size)
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AgentIcons.kt b/apps/android/app/src/main/kotlin/com/codync/android/AgentIcons.kt
new file mode 100644
index 00000000..7f8f45bb
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AgentIcons.kt
@@ -0,0 +1,41 @@
+// Generated by tools/agent_icons.py: the agent logos converted from the desktop app's SVGs.
+package com.codync.android
+
+import androidx.annotation.DrawableRes
+
+/** The logo for an agent's ACP registry id (or Codync's id for agents outside it), or null. */
+@DrawableRes internal fun agentIconRes(registry: String?): Int? = when (registry) {
+ "amp-acp" -> R.drawable.agent_amp_acp
+ "antigravity-acp" -> R.drawable.agent_antigravity_acp
+ "auggie" -> R.drawable.agent_auggie
+ "autohand" -> R.drawable.agent_autohand
+ "claude-acp" -> R.drawable.agent_claude_acp
+ "codebuddy-code" -> R.drawable.agent_codebuddy_code
+ "codex-acp" -> R.drawable.agent_codex_acp
+ "cortex-code" -> R.drawable.agent_cortex_code
+ "crow-cli" -> R.drawable.agent_crow_cli
+ "cursor" -> R.drawable.agent_cursor
+ "deepagents" -> R.drawable.agent_deepagents
+ "devin" -> R.drawable.agent_devin
+ "dimcode" -> R.drawable.agent_dimcode
+ "factory-droid" -> R.drawable.agent_factory_droid
+ "gemini" -> R.drawable.agent_gemini
+ "github-copilot-cli" -> R.drawable.agent_github_copilot_cli
+ "glm-acp-agent" -> R.drawable.agent_glm_acp_agent
+ "goose" -> R.drawable.agent_goose
+ "grok-build" -> R.drawable.agent_grok_build
+ "harn" -> R.drawable.agent_harn
+ "kilo" -> R.drawable.agent_kilo
+ "kimchi" -> R.drawable.agent_kimchi
+ "kimi" -> R.drawable.agent_kimi
+ "minimax-code" -> R.drawable.agent_minimax_code
+ "mistral-vibe" -> R.drawable.agent_mistral_vibe
+ "omp" -> R.drawable.agent_omp
+ "opencode" -> R.drawable.agent_opencode
+ "pi-acp" -> R.drawable.agent_pi_acp
+ "poolside" -> R.drawable.agent_poolside
+ "qoder" -> R.drawable.agent_qoder
+ "qwen-code" -> R.drawable.agent_qwen_code
+ "stakpak" -> R.drawable.agent_stakpak
+ else -> null
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AgentModelPicker.kt b/apps/android/app/src/main/kotlin/com/codync/android/AgentModelPicker.kt
new file mode 100644
index 00000000..628cd15f
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AgentModelPicker.kt
@@ -0,0 +1,83 @@
+package com.codync.android
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.AgentModels
+import com.codync.android.core.Bot
+import com.codync.android.core.LinkState
+import com.codync.android.design.*
+import kotlinx.coroutines.CancellationException
+
+/**
+ * Models come from the selected computer's agent, never a bundled list (iOS `AgentModelPicker`).
+ * The selected model's settings follow it; Fast mode is its own row while the agent offers it.
+ */
+@Composable internal fun AgentModelPicker(state: AppState, load: suspend (String) -> AgentModels, backend: String, selection: String?,
+ options: Map<String, String>, fastMode: Boolean, bot: Bot?, choose: (String?, Map<String, String>) -> Unit, setFast: (Boolean) -> Unit) {
+ val online = state.actualConnection is LinkState.Ready
+ var catalog by remember(backend) { mutableStateOf<AgentModels?>(null) }
+ var loading by remember(backend) { mutableStateOf(false) }
+ var failure by remember(backend) { mutableStateOf<String?>(null) }
+ var retry by remember(backend) { mutableIntStateOf(0) }
+ LaunchedEffect(state.computers.firstOrNull()?.id, backend, online, retry) {
+ failure = null; loading = false
+ if (backend == "custom") return@LaunchedEffect
+ if (!online) { failure = "Connect to this computer to load its models. You can still enter a model ID."; return@LaunchedEffect }
+ loading = true
+ try { catalog = load(backend) }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (error: Exception) { failure = "Couldn't load models: ${error.message ?: "Try again."}" }
+ finally { loading = false }
+ }
+ // The agent's own "Default" entry is the same choice as no model.
+ val agentDefault = catalog?.agentDefault
+ val value = if (selection == agentDefault?.id) "" else selection.orEmpty()
+ val modelOptions = catalog?.models?.firstOrNull { it.id == value }?.options.orEmpty()
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text("Model", style = Type.body, color = Palette.text)
+ Box(Modifier.weight(1f))
+ if (backend != "custom") Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) {
+ if (loading) Spinner(12.dp) else IconButton(if (failure == null) "Refresh model list" else "Retry model list", "arrow.clockwise") { retry++ }
+ }
+ if (backend == "custom" || (!loading && catalog?.models.isNullOrEmpty())) {
+ Box(Modifier.widthIn(max = 180.dp).outline().pill(androidx.compose.ui.graphics.Color.Transparent)) {
+ PlainTextField(value, { choose(it.ifEmpty { null }, emptyMap()) }, prompt = "Default", singleLine = true,
+ style = Type.body.copy(textAlign = TextAlign.End))
+ }
+ } else {
+ val choices = catalog?.options(selection)?.map { it.id.orEmpty() to it.name } ?: listOf("" to "Default")
+ ChoicePicker(value, choices, { if (it != value) choose(it.ifEmpty { null }, emptyMap()) }, label = "Model")
+ }
+ }
+ for (option in modelOptions) Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(option.name, Modifier.weight(1f), style = Type.body, color = Palette.text)
+ val fallback = option.values.firstOrNull { it.id == option.default }?.name
+ ChoicePicker(options[option.id].orEmpty(), listOf("" to (fallback?.let { "Default · $it" } ?: "Default")) + option.values.map { it.id to it.name },
+ { picked -> choose(selection, if (picked.isEmpty()) options - option.id else options + (option.id to picked)) }, label = option.name)
+ }
+ val note = failure
+ if (backend != "custom" && !loading && note != null) Text(note, style = Type.caption, color = Palette.warning)
+ else if (backend != "custom" && !loading && catalog?.models?.isEmpty() == true)
+ Text("This agent doesn't advertise a model list. Leave Default or enter a model ID.", style = Type.caption, color = Palette.secondary)
+ Text("Changing the model starts a new agent session. Chat history is kept.", style = Type.caption, color = Palette.secondary)
+ val showsFast = (backend != "custom" && catalog?.fastMode == true) || fastMode || (bot?.backend == backend && bot.fastModeShown)
+ if (showsFast) SwitchRow("Fast mode", bot?.fastModeRefusal ?: "Faster replies for more usage, on models that offer it.", fastMode, setFast)
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AgentSheet.kt b/apps/android/app/src/main/kotlin/com/codync/android/AgentSheet.kt
new file mode 100644
index 00000000..42949ddd
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AgentSheet.kt
@@ -0,0 +1,254 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.slideInHorizontally
+import androidx.compose.animation.slideOutHorizontally
+import androidx.compose.animation.togetherWith
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.semantics.stateDescription
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.AgentAuth
+import com.codync.android.core.AgentAuthMethod
+import com.codync.android.core.AgentBackend
+import com.codync.android.core.WireJson
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.launch
+import kotlinx.serialization.json.decodeFromJsonElement
+
+/** A step inside the agent's sheet: a terminal for install / Node.js / sign-in, or its keys. */
+private data class SetupRoute(val step: String, val method: AgentAuthMethod? = null)
+
+/** The computer's agents, live: an install or sign-in updates the host's list. */
+internal fun agentBackends(state: AppState): List<AgentBackend> =
+ state.hello?.get("backends")?.let { runCatching { WireJson.decodeFromJsonElement<List<AgentBackend>>(it) }.getOrNull() }.orEmpty()
+
+/**
+ * Getting an agent ready on the computer (iOS `AgentSheet`): install it, add Node.js when it runs
+ * on Node and the computer has none, then sign in. `recheck` (a chat's sign-in request) asks the
+ * agent again however signed in it looked.
+ */
+@Composable internal fun AgentSheet(initial: AgentBackend, state: AppState, store: AppStore, recheck: Boolean = false) {
+ val scope = rememberCoroutineScope()
+ val backend = agentBackends(state).firstOrNull { it.id == initial.id } ?: initial
+ var route by remember { mutableStateOf<SetupRoute?>(null) }
+ var auth by remember { mutableStateOf<AgentAuth?>(null) }
+ var checking by remember { mutableStateOf(false) }
+ var authenticating by remember { mutableStateOf<String?>(null) }
+ var error by remember { mutableStateOf<String?>(null) }
+ fun check() {
+ if (checking) return
+ checking = true
+ scope.launch {
+ try { auth = store.agentAuth(backend.id); error = null }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't check this agent." }
+ finally { checking = false }
+ }
+ }
+ // A known "signed in" needs no agent start; everything else asks the agent (which can't start without its Node.js).
+ LaunchedEffect(Unit) { if ((recheck || backend.signedIn != true) && !backend.needsNode) check() }
+ val back = { route = null; check() }
+ AnimatedContent(route, transitionSpec = {
+ val forward = targetState != null
+ (slideInHorizontally(Motion.layoutOffset) { if (forward) it else -it } + fadeIn(Motion.fade())) togetherWith
+ (slideOutHorizontally(Motion.layoutOffset) { if (forward) -it else it } + fadeOut(Motion.fade()))
+ }, label = "Agent setup") { shown ->
+ when {
+ shown == null -> Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader(backend.name)
+ Overview(backend, auth, checking, authenticating, error, state, { route = it }, ::check) { method ->
+ authenticating = method.id
+ scope.launch {
+ try { auth = store.agentAuthenticate(backend.id, method.id); error = null }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Sign-in didn't finish." }
+ finally { authenticating = null }
+ }
+ }
+ }
+ shown.step == "keys" -> AgentKeysForm(backend, requireNotNull(shown.method), auth?.savedEnv.orEmpty(), state, store, back) { auth = it }
+ else -> SetupTerminal(backend.takeUnless { shown.step == "node" }, shown.step, shown.method, state, store, back)
+ }
+ }
+}
+
+@Composable private fun Overview(backend: AgentBackend, auth: AgentAuth?, checking: Boolean, authenticating: String?, error: String?, state: AppState,
+ go: (SetupRoute) -> Unit, check: () -> Unit, authenticate: (AgentAuthMethod) -> Unit) {
+ val host = state.hostName
+ val signedIn = auth?.signedIn ?: backend.signedIn
+ val curated = backend.curated
+ CardForm {
+ CardSection {
+ row {
+ Row(Modifier.padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ Box(Modifier.size(52.dp).clip(RoundedRectangle(14.dp)).background(Palette.bubbleAgent), contentAlignment = Alignment.Center) {
+ AgentIcon(backend.registry ?: backend.id, 30.dp)
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(backend.name, style = Type.title3.semibold, color = Palette.text)
+ backend.description?.takeIf(String::isNotEmpty)?.let {
+ Text(it, style = Type.subheadline, color = Palette.secondary, maxLines = 3, overflow = TextOverflow.Ellipsis)
+ }
+ }
+ }
+ }
+ }
+ if (curated) CardSection {
+ row {
+ SetupStepRow(1, "Install", if (backend.installed) "Installed on $host." else if (backend.canInstall) "Runs the official installer on $host." else backend.installHint,
+ backend.installed, ("Install" to { go(SetupRoute("install")) }).takeIf { !backend.installed && backend.canInstall })
+ }
+ }
+ if (backend.node != null) CardSection {
+ row {
+ SetupStepRow(if (curated) 2 else 1, "Node.js", if (backend.needsNode) "${backend.name} runs on Node.js. Codync adds its own copy." else "Added on $host.",
+ !backend.needsNode, ("Add" to { go(SetupRoute("node")) }).takeIf { backend.needsNode })
+ }
+ }
+ val agentMethods = auth?.methods.orEmpty().any { it.kind == "agent" || it.kind == null }
+ CardSection(footer = if (signedIn != true && agentMethods) "Browser sign-ins open on $host itself. Away from it? Use Remote screen to finish there." else null) {
+ row {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Box(Modifier.weight(1f)) {
+ SetupStepRow(1 + (if (curated) 1 else 0) + (if (backend.node != null) 1 else 0), "Sign in",
+ statusText(backend, auth, signedIn, checking, host), signedIn == true, null)
+ }
+ if (checking) ThinkingOrb(ThinkingOrbState.Connecting, 16.dp, Palette.secondary) else IconButton("Check again", "arrow.clockwise", action = check)
+ }
+ }
+ val detail = auth?.detail
+ if (signedIn != true && !detail.isNullOrEmpty()) row { SelectionContainer { Text(detail, style = Type.footnote, color = Palette.secondary) } }
+ // Some CLIs drop the current sign-in the moment a new one starts: no options once signed in.
+ if (signedIn != true && !checking) {
+ if (auth?.login == true) row {
+ OptionRow("Sign in", "In a terminal on $host. Links open here.", "terminal", enabled = authenticating == null) { go(SetupRoute("login")) }
+ }
+ for (method in auth?.methods.orEmpty()) row {
+ when (method.kind) {
+ "terminal" -> OptionRow(method.name, method.description ?: "In a terminal on $host.", "terminal", enabled = authenticating == null) {
+ go(SetupRoute("login", method))
+ }
+ "envVar" -> OptionRow(method.name, method.description ?: "Saved on $host only.", "key", enabled = authenticating == null) {
+ go(SetupRoute("keys", method))
+ }
+ "agent", null -> OptionRow(method.name, if (authenticating == method.id) "Finish signing in in the browser on $host…"
+ else method.description ?: "Opens a browser on $host.", "safari", busy = authenticating == method.id, enabled = authenticating == null) { authenticate(method) }
+ else -> OptionRow(method.name, "This sign-in needs a newer app. Sign in on $host for now.", "exclamationmark.circle", enabled = false) {}
+ }
+ }
+ }
+ }
+ error?.let { CardSection { row { SelectionContainer { ErrorRow(it) } } } }
+ }
+}
+
+private fun statusText(backend: AgentBackend, auth: AgentAuth?, signedIn: Boolean?, checking: Boolean, host: String) = when {
+ checking -> if (auth == null) "Checking with ${backend.name}… The first check can download it." else "Checking…"
+ signedIn == true -> "Signed in."
+ backend.needsNode -> "Add Node.js first."
+ signedIn == false -> "Not signed in yet."
+ else -> "Couldn't tell. Skip this if you've already signed in on $host."
+}
+
+@Composable private fun OptionRow(title: String, detail: String, icon: String, busy: Boolean = false, enabled: Boolean = true, action: () -> Unit) {
+ Row(Modifier.fillMaxWidth().plainButton(enabled = enabled, action = action), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Box(Modifier.width(26.dp), contentAlignment = Alignment.Center) { Symbol(icon, size = 20.dp, tint = Palette.secondary) }
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(title, style = Type.body.medium, color = Palette.text)
+ Text(detail, style = Type.subheadline, color = Palette.secondary, maxLines = 3, overflow = TextOverflow.Ellipsis)
+ }
+ if (busy) ThinkingOrb(size = 16.dp, color = Palette.secondary) else Symbol("chevron.right", size = 13.dp, tint = Palette.tertiary)
+ }
+}
+
+/** A numbered setup step: done shows a check; an action sits on the right. */
+@Composable private fun SetupStepRow(number: Int, title: String, detail: String, done: Boolean, action: Pair<String, () -> Unit>?) {
+ Row(Modifier.padding(vertical = 4.dp).semantics(mergeDescendants = true) { stateDescription = if (done) "Done" else "" },
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Box(Modifier.size(26.dp).clip(Capsule()).background(if (done) Palette.accentFill else Palette.bubbleAgent), contentAlignment = Alignment.Center) {
+ if (done) Symbol("checkmark", size = 13.dp, tint = Palette.onAccent)
+ else Text("$number", style = Type.caption.semibold, color = Palette.secondary)
+ }
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(title, style = Type.body.medium, color = Palette.text)
+ Text(detail, style = Type.subheadline, color = Palette.secondary)
+ }
+ action?.let { (label, run) ->
+ Text(label, Modifier.clip(Capsule()).background(Palette.bubbleAgent).plainButton(action = run).padding(horizontal = 14.dp, vertical = 7.dp),
+ style = Type.subheadline.semibold, color = Palette.text)
+ }
+ }
+}
+
+/** Keys an agent reads from its environment, kept on the computer (iOS `AgentKeysForm`). */
+@Composable private fun AgentKeysForm(backend: AgentBackend, method: AgentAuthMethod, saved: List<String>, state: AppState, store: AppStore,
+ back: () -> Unit, done: (AgentAuth) -> Unit) {
+ val scope = rememberCoroutineScope()
+ var values by remember { mutableStateOf(emptyMap<String, String>()) }
+ var saving by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf<String?>(null) }
+ fun save(vars: Map<String, String>) {
+ saving = true; error = null
+ scope.launch {
+ try { done(store.setAgentEnv(backend.id, vars)); back() }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't update these keys." }
+ finally { saving = false }
+ }
+ }
+ val savedHere = method.vars.any { it.name in saved }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ScreenHeader({ BackButton(back) }, { Text(method.name, style = Type.body.semibold, color = Palette.text, maxLines = 1) }) {
+ if (saving) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
+ else IconButton("Save", "checkmark", enabled = method.complete(values, saved)) { save(values.filterValues(String::isNotEmpty)) }
+ }
+ CardForm(Modifier.weight(1f)) {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ CardSection(method.name) {
+ for (v in method.vars) row {
+ NotedInput(values[v.name].orEmpty(), { values = values + (v.name to it) }, if (v.name in saved) "Saved (type to replace)" else v.name,
+ v.label + if (v.optional) " (optional)" else "", secret = v.secret)
+ }
+ }
+ Column(Modifier.padding(horizontal = 4.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ method.description?.let { Text(it, style = Type.caption, color = Palette.tertiary) }
+ Text("Saved on ${state.hostName} only and given to ${backend.name} when it starts.", style = Type.caption, color = Palette.tertiary)
+ method.link?.let { WebLink("Get a key", it, Type.caption) }
+ }
+ }
+ if (savedHere) CardSection {
+ row { LinkButton("Remove saved keys", enabled = !saving, color = Palette.danger) { save(method.vars.associate { it.name to "" }) } }
+ }
+ error?.let { CardSection { row { ErrorRow(it) } } }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/Analytics.kt b/apps/android/app/src/main/kotlin/com/codync/android/Analytics.kt
new file mode 100644
index 00000000..c3e82f62
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/Analytics.kt
@@ -0,0 +1,150 @@
+package com.codync.android
+
+import android.content.Context
+import android.content.SharedPreferences
+import android.os.Build
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import java.security.MessageDigest
+import java.time.Instant
+import java.util.UUID
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonArray
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+
+/** What the phone reports (iOS `AnalyticsEvent`). Bot and message events come from the computer's host instead. */
+internal enum class AnalyticsEvent(val wire: String) {
+ AppOpened("app_opened"), OnboardingCompleted("onboarding_completed"), ComputerPaired("computer_paired"),
+ SignedIn("signed_in"), SignedOut("signed_out"), VoiceCallStarted("voice_call_started"),
+}
+
+/**
+ * Product analytics (iOS `Analytics`, docs/features/analytics.md): batches events to PostHog, on
+ * unless turned off in Settings. Feature use only, never content. Main thread only.
+ */
+internal object Analytics {
+ private const val ENDPOINT = "https://us.i.posthog.com/batch/"
+ private const val API_KEY = "phc_rQHvxdSFKnMquPfMjmiMhXhM4tqJ5qCYsWuVEoFxCCWX"
+ private const val BATCH_SIZE = 20
+ private const val MAX_PENDING = 500
+ private const val FLUSH_DELAY = 30_000L
+
+ /** The signed-in Codync account, read at capture time; null = the install's random ID. */
+ var userId: () -> String? = { null }
+ private var sharing by mutableStateOf(true)
+ /** Settings' switch; absent = on. Observable, so the switch follows it. */
+ val enabled: Boolean get() = sharing
+ private var prefs: SharedPreferences? = null
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+ private val http by lazy { OkHttpClient() }
+ private val pending = mutableListOf<JsonObject>()
+ private var timer: Job? = null
+ private var sending = false
+ private var foreground = false
+
+ fun start(context: Context) {
+ if (prefs != null) return
+ val stored = context.getSharedPreferences("codync-analytics", Context.MODE_PRIVATE)
+ prefs = stored
+ sharing = stored.getBoolean("enabled", true)
+ CrashReports.start(context)
+ }
+
+ /** Turning it off drops everything not yet sent. */
+ fun setEnabled(on: Boolean) {
+ sharing = on
+ prefs?.edit()?.putBoolean("enabled", on)?.apply()
+ if (on) return flush()
+ pending.clear(); timer?.cancel(); timer = null
+ }
+
+ /** `properties` are public names, never content. */
+ fun capture(event: AnalyticsEvent, properties: Map<String, String> = emptyMap()) =
+ record(event.wire, properties.mapValues { JsonPrimitive(it.value) })
+
+ /** One event for the signed-in account (merging the install ID into it once), else the install ID. */
+ fun record(name: String, extra: Map<String, JsonElement>) {
+ val stored = prefs ?: return
+ if (!enabled) return
+ val user = userId()
+ if (user != null) {
+ val identified = stored.getStringSet("identified", emptySet()).orEmpty()
+ if (user !in identified) {
+ enqueue("\$identify", user, mapOf("\$anon_distinct_id" to JsonPrimitive(installId(stored))))
+ stored.edit().putStringSet("identified", identified + user).apply()
+ }
+ enqueue(name, user, extra)
+ } else enqueue(name, installId(stored), extra)
+ }
+
+ /** `app_opened` once per trip to the foreground. */
+ fun becameActive() { if (!foreground) { foreground = true; capture(AnalyticsEvent.AppOpened) } }
+
+ fun enteredBackground() { foreground = false; flush() }
+
+ fun flush() {
+ timer?.cancel(); timer = null
+ if (sending || pending.isEmpty() || !enabled) return
+ val batch = pending.toList()
+ val body = buildJsonObject { put("api_key", API_KEY); put("batch", buildJsonArray { batch.forEach { add(it) } }) }.toString()
+ sending = true
+ scope.launch {
+ val ok = withContext(Dispatchers.IO) { post(body) }
+ sending = false
+ if (ok) pending.removeAll(batch.toSet())
+ if (pending.isNotEmpty()) scheduleFlush()
+ }
+ }
+
+ private fun installId(stored: SharedPreferences): String = stored.getString("install", null)
+ ?: UUID.randomUUID().toString().also { stored.edit().putString("install", it).apply() }
+
+ private fun enqueue(name: String, distinctId: String, extra: Map<String, JsonElement>) {
+ pending += event(name, distinctId, Instant.now().toString(), extra)
+ if (pending.size > MAX_PENDING) repeat(pending.size - MAX_PENDING) { pending.removeAt(0) }
+ if (pending.size >= BATCH_SIZE) flush() else scheduleFlush()
+ }
+
+ private fun scheduleFlush() {
+ if (timer != null) return
+ timer = scope.launch { delay(FLUSH_DELAY); timer = null; flush() }
+ }
+
+ /** Sent (or rejected for good) → true; network errors, 429 and 5xx → false, retried next flush. */
+ private fun post(body: String): Boolean = try {
+ http.newCall(Request.Builder().url(ENDPOINT).post(body.toRequestBody("application/json".toMediaType())).build()).execute()
+ .use { it.code < 500 && it.code != 429 }
+ } catch (_: java.io.IOException) { false }
+
+ /** One event in PostHog's `/batch/` body, with the properties every event carries. */
+ internal fun event(name: String, distinctId: String, timestamp: String, extra: Map<String, JsonElement>): JsonObject = buildJsonObject {
+ put("uuid", UUID.randomUUID().toString()); put("event", name); put("distinct_id", distinctId); put("timestamp", timestamp)
+ put("properties", JsonObject(common + extra + ("\$process_person_profile" to JsonPrimitive(true))))
+ }
+
+ private val common: Map<String, JsonElement> by lazy {
+ mapOf("\$lib" to JsonPrimitive("codync-android"), "app_version" to JsonPrimitive(BuildConfig.VERSION_NAME),
+ // Codync Dev reports as dev, whatever the build type.
+ "env" to JsonPrimitive(if (BuildConfig.APPLICATION_ID.endsWith(".dev")) "dev" else "main"),
+ "\$os" to JsonPrimitive("Android"), "\$os_version" to JsonPrimitive(Build.VERSION.RELEASE.orEmpty()))
+ }
+
+ /** A computer's analytics key, the same hash its host sends: joins `computer_paired` with that computer's events. */
+ fun computerTag(id: String): String =
+ MessageDigest.getInstance("SHA-256").digest("codync-analytics:$id".toByteArray()).take(8).joinToString("") { "%02x".format(it) }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsSheet.kt b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsSheet.kt
new file mode 100644
index 00000000..0fdb9e6d
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsSheet.kt
@@ -0,0 +1,54 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalUriHandler
+import androidx.compose.ui.unit.dp
+import com.codync.android.design.*
+
+private val DETAILS = listOf(
+ Triple("chart.bar", "Features you use", "Opening the app, creating or deleting a bot, sending a message (how many attachments, never the files), running a routine or a voice call, installing a connector. Each comes with the app version, the platform, and the bot's agent and model."),
+ Triple("exclamationmark.triangle", "Crashes and errors", "When Codync crashes or an agent fails to answer: the kind of error and where in Codync's own code it happened. Never the error's message; file paths are cut down to Codync's own files."),
+ Triple("globe", "Approximate location", "Country and city, looked up from your IP address. The IP address itself is never stored."),
+ Triple("person.crop.circle", "Who it belongs to", "Your Codync account when you're signed in, otherwise a random ID made on this device."),
+ Triple("eye.slash", "Never shared", "Your messages, prompts, code, files, file names or paths, bot names, credentials, or anything your agents produce."),
+ Triple("lock.shield", "How it's used", "Only to spot bugs sooner and see which features work and where people get stuck. Never sold, never used for ads or to track you across other apps and websites."),
+ Triple("power", "Your choice", "Each phone and each computer has its own switch. Turning it off stops sending right away and drops anything not sent yet."),
+)
+
+/** Settings' info button beside Share usage analytics (iOS `AnalyticsSheet`): everything it covers, true to the privacy policy. */
+@Composable internal fun AnalyticsSheet() {
+ val uri = LocalUriHandler.current
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader("Usage analytics")
+ CardForm {
+ CardSection {
+ for ((icon, title, detail) in DETAILS) row {
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Box(Modifier.width(22.dp).padding(top = 1.dp), contentAlignment = Alignment.Center) { Symbol(icon, size = 18.dp, tint = Palette.secondary) }
+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(title, style = Type.body, color = Palette.text)
+ Text(detail, style = Type.footnote, color = Palette.secondary)
+ }
+ }
+ }
+ }
+ Row(Modifier.padding(horizontal = 2.dp), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text("See the", style = Type.caption, color = Palette.secondary)
+ LinkButton("Privacy Policy", style = Type.caption.copy(textDecoration = androidx.compose.ui.text.style.TextDecoration.Underline),
+ color = Palette.text) { uri.openUri("https://codync.dev/privacy") }
+ Text("for details.", style = Type.caption, color = Palette.secondary)
+ }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
new file mode 100644
index 00000000..5e61fec7
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
@@ -0,0 +1,51 @@
+package com.codync.android
+
+import com.codync.android.core.*
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.longOrNull
+
+/** Everything the UI renders for the active account and its computer; `AppStore` owns the only writer. */
+data class AppState(
+ val contextId: String = "local",
+ val generation: Int = 0,
+ val account: AccountState = AccountState(),
+ val cloudComputers: List<CloudComputer> = emptyList(),
+ val access: AccessTicket? = null,
+ val notifications: Boolean = true,
+ val tasks: Boolean = true,
+ val setupComplete: Boolean = false,
+ val loading: Boolean = true,
+ val pairing: Boolean = false,
+ val computers: List<Computer> = emptyList(),
+ val bots: List<Bot> = emptyList(),
+ val rosterLoaded: Boolean = false,
+ val mirrorRevision: Long = 0,
+ val entries: List<Entry> = emptyList(),
+ val pending: List<PendingSend> = emptyList(),
+ val drafts: Map<String, ComposerDraft> = emptyMap(),
+ val uploadProgress: Map<String, Int> = emptyMap(),
+ val usage: JsonObject = JsonObject(emptyMap()),
+ val hello: JsonObject? = null,
+ val connection: LinkState = LinkState.Connecting,
+ val actualConnection: LinkState = LinkState.Connecting,
+ val selectedBot: String? = null,
+ val navigationRequest: Int = 0,
+ val navigationUsage: Boolean = false,
+ val thread: String? = null,
+ val trace: Boolean = false,
+ val busy: Set<String> = emptySet(),
+ val historyComplete: Set<String> = emptySet(),
+ val routines: Map<String, RoutineListing> = emptyMap(),
+ val plugins: PluginListing? = null,
+ val voice: VoiceCallViewState? = null,
+ /** The host sent data this app can't read even after fetching everything again. */
+ val unreadable: Boolean = false,
+ val error: String? = null,
+) {
+ /** Connection alone cannot make a cached roster current before event catch-up. */
+ internal val widgetBotsCurrent: Boolean get() {
+ val head = hello?.get("rev")?.jsonPrimitive?.longOrNull ?: return false
+ return !loading && rosterLoaded && actualConnection is LinkState.Ready && mirrorRevision >= head
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
new file mode 100644
index 00000000..25b3914c
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
@@ -0,0 +1,266 @@
+package com.codync.android
+
+import android.app.Application
+import androidx.lifecycle.AndroidViewModel
+import androidx.lifecycle.viewModelScope
+import com.codync.android.core.*
+import java.io.IOException
+import java.util.UUID
+import java.util.concurrent.ConcurrentHashMap
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.json.*
+
+/**
+ * The ViewModel the UI talks to: the active account's state and the one writer of it. This file holds
+ * the account context's lifecycle (load, retire), the mirror refresh and the helpers every feature
+ * uses; the features themselves are `AppStore` extensions in the `AppStore*.kt` files beside it.
+ */
+class AppStore(application: Application) : AndroidViewModel(application) {
+ internal val activityOwnerId: String = UUID.randomUUID().toString()
+ internal var local = LocalStore(application)
+ private var contextJob = SupervisorJob(viewModelScope.coroutineContext[Job])
+ internal var contextScope = CoroutineScope(contextJob + Dispatchers.Main.immediate)
+ internal val transitions = Mutex()
+ internal var cloud: CloudClient? = null
+ private var sessionJob: Job? = null
+ internal var linkJob: Job? = null
+ internal val asked = mutableSetOf<String>()
+ internal var attachments = AttachmentFiles(application, local.directory)
+ internal val downloadLocks = ConcurrentHashMap<String, Mutex>()
+ internal val mutableState = MutableStateFlow(AppState())
+ val state = mutableState.asStateFlow()
+ internal var database: MirrorDatabase? = null
+ internal var draftBook: DraftBook? = null
+ internal var draftWriter: Job? = null
+ internal var savedDrafts: Map<String, ComposerDraft> = emptyMap()
+ internal var connectionJob: Job? = null
+ internal var pairingJob: Job? = null
+ internal var graceJob: Job? = null
+ internal var channel: EncryptedChannel? = null
+ internal var foreground = false
+ internal val foregroundState = MutableStateFlow(false)
+ internal val setupTerminals = mutableMapOf<String, SetupTerminalSession>()
+ internal val appConnections = mutableMapOf<String, AppConnectionSession>()
+ internal var oauthRequestId: String? = null
+ internal var voiceBinding: VoiceBinding? = null
+ internal var voiceGeneration: Int? = null
+ internal val transportRequired: Boolean get() = foreground || state.value.voice != null
+ internal val sends = mutableSetOf<String>()
+ internal val actions = mutableMapOf<String, Job>()
+ internal var pluginsRefreshAgain = false
+ internal var widgetOwner: WidgetOwner? = null
+ /** The host version an undecodable event already made the mirror fetch everything again for. */
+ internal var rewoundFor: String? = null
+
+ init {
+ viewModelScope.launch {
+ transitions.withLock { loadContext(null) }
+ NativeAccounts.observe(viewModelScope) { account ->
+ mutableState.update { it.copy(account = account) }
+ if (account.ready) transitions.withLock {
+ // Read the latest state after a concurrent logout/reset finishes.
+ val current = state.value.account
+ val desired = current.userId ?: "local"
+ if (desired != local.contextId) {
+ retireContext()
+ loadContext(current.userId)
+ } else if (cloud == null && current.userId != null) {
+ configureCloud(current.userId)
+ refreshCloud()
+ }
+ }
+ }
+ }
+ }
+
+ internal suspend fun loadContext(userId: String?) {
+ try {
+ WidgetRefreshWorker.stop(getApplication())
+ local = LocalStore(getApplication(), userId ?: "local")
+ widgetOwner = withContext(Dispatchers.IO) { WidgetStore.activate(getApplication(), local.contextId) }
+ PushDelivery.activate(getApplication(), userId)
+ attachments = AttachmentFiles(getApplication(), local.directory)
+ val computers = withContext(Dispatchers.IO) { local.computers() }
+ val complete = withContext(Dispatchers.IO) { local.setupComplete() }
+ mutableState.update { AppState(contextId = local.referenceId, generation = it.generation + 1,
+ account = it.account, computers = computers, setupComplete = complete || computers.isNotEmpty() || userId != null) }
+ mutableState.update { it.copy(notifications = PushPreferences.enabled(getApplication()), tasks = PushPreferences.tasks(getApplication())) }
+ openMirror()
+ if (userId != null) configureCloud(userId)
+ mutableState.update { it.copy(loading = false) }
+ observeWidgets(requireNotNull(widgetOwner))
+ if (foreground) connect()
+ refreshCloud()
+ } catch (error: CancellationException) { throw error }
+ catch (error: Exception) { showError(error) }
+ }
+
+ private suspend fun configureCloud(userId: String) {
+ val identity = withContext(Dispatchers.IO) { local.identity() }
+ cloud = CloudClient(BuildConfig.CLOUD_URL, identity) { NativeAccounts.token(userId) }
+ }
+
+ /** Join every writer before closing a context's database or replacing its identity. */
+ internal suspend fun retireContext() = withContext(NonCancellable) {
+ mutableState.update { it.copy(loading = true) }
+ withContext(Dispatchers.IO) { WidgetStore.retire(getApplication(), widgetOwner) }
+ widgetOwner = null
+ WidgetRefreshWorker.stop(getApplication())
+ try { CodyncWidgets.update(getApplication()) } catch (_: Exception) { }
+ val call = voiceBinding; voiceBinding = null; voiceGeneration = null
+ val callId = state.value.voice?.id
+ mutableState.update { it.copy(voice = null) }
+ if (callId != null) VoiceService.stop(getApplication(), callId)
+ call?.session?.end(); call?.session?.awaitEnd()
+ val writers = actions.values.toList()
+ writers.forEach { it.cancel() }; writers.forEach { it.join() }
+ PushDelivery.retire(getApplication())
+ val retiringChannel = channel?.takeIf { it.state.value is LinkState.Ready }
+ val feed = TaskFeed(local.directory)
+ if (retiringChannel != null) withTimeoutOrNull(2_000) {
+ try {
+ retiringChannel.call("unregisterDevice")
+ for (watch in withContext(Dispatchers.IO) { feed.all() }) retiringChannel.call("unregisterActivity", body("botId" to watch.botId))
+ } catch (_: Exception) { }
+ }
+ // Editing is disabled during retirement; let its last coalesced write finish.
+ draftWriter?.join()
+ contextJob.cancelAndJoin()
+ setupTerminals.clear()
+ appConnections.clear()
+ oauthRequestId = null
+ AccountImages.retire()
+ channel?.close(); channel = null
+ connectionJob = null; pairingJob = null; graceJob = null
+ actions.clear(); sends.clear(); downloadLocks.clear(); asked.clear(); cloud = null
+ pluginsRefreshAgain = false
+ rewoundFor = null
+ draftWriter = null; draftBook = null; savedDrafts = emptyMap()
+ withContext(Dispatchers.IO) { feed.clear(); database?.close(); database = null }
+ withContext(Dispatchers.IO) { ConnectorOAuthBook(local.directory).clear() }
+ contextJob = SupervisorJob(viewModelScope.coroutineContext[Job])
+ contextScope = CoroutineScope(contextJob + Dispatchers.Main.immediate)
+ }
+
+ internal fun sessionAction(operation: suspend () -> Unit) {
+ if (sessionJob?.isActive == true) return
+ sessionJob = viewModelScope.launch {
+ mutableState.update { it.copy(busy = it.busy + "session", error = null) }
+ try { operation() }
+ catch (error: CancellationException) { throw error }
+ catch (error: Exception) { showError(error) }
+ finally { mutableState.update { it.copy(busy = it.busy - "session") } }
+ }
+ }
+
+ internal suspend fun openMirror() {
+ val computer = state.value.computers.firstOrNull() ?: return
+ val book = DraftBook(local.directory, computer.id)
+ withContext(Dispatchers.IO) {
+ database?.close()
+ database = MirrorDatabase(getApplication(), local.directory, computer.id)
+ database?.recoverInterrupted()
+ val snapshot = requireNotNull(database).snapshot()
+ val restored = book.recover(snapshot)
+ savedDrafts = restored.associateBy { it.lane }
+ mutableState.update { it.copy(drafts = restored.associateBy { draft -> draft.lane }) }
+ attachments.retainPending(snapshot.pending.flatMap { it.files } + restored.flatMap { it.files })
+ }
+ draftBook = book
+ refresh()
+ }
+
+ internal suspend fun refresh() {
+ val mirror = database ?: return
+ val snapshot = withContext(Dispatchers.IO) { mirror.snapshot() }
+ val retainedDraftFiles = state.value.drafts.values.flatMap { it.files }.map { it.path }.toSet()
+ val retired = state.value.pending.filter { old -> snapshot.pending.none { it.nonce == old.nonce } }.flatMap { it.files }.filter { it.path !in retainedDraftFiles }
+ withContext(Dispatchers.IO) { retired.forEach(attachments::discard) }
+ mutableState.update { current -> current.copy(bots = snapshot.bots, entries = snapshot.entries,
+ pending = snapshot.pending, usage = snapshot.usage, mirrorRevision = snapshot.rev,
+ selectedBot = current.selectedBot?.takeIf { id -> snapshot.bots.any { it.id == id } }) }
+ voiceBinding?.let { call ->
+ if (snapshot.bots.none { it.id == call.botId && !it.deleted }) endVoice("Voice chat ended because its bot was removed.")
+ else for (reply in call.replies.observe(snapshot.entries)) call.session.speak(reply)
+ }
+ if (PushPreferences.tasks(getApplication())) {
+ val feed = TaskFeed(local.directory)
+ val watched = withContext(Dispatchers.IO) { feed.all().filter { !it.finished }.map { it.botId }.toSet() }
+ for (bot in snapshot.bots.filter { it.id in watched }) {
+ val watch = withContext(Dispatchers.IO) { feed.local(bot) }
+ if (watch != null) NotificationDisplay.task(getApplication(), local.referenceId, state.value.computers.first().id, watch)
+ }
+ }
+ }
+
+ /** The ready channel, waiting briefly for a reconnect; a timeout is an error the action shows. */
+ internal suspend fun ready(): EncryptedChannel = deadline(20_000, "Can't reach the computer. Check that it's on, then try again.") {
+ while (true) {
+ val active = channel
+ if (active?.state?.value is LinkState.Ready) return@deadline active
+ val link = active?.state?.value
+ if (link is LinkState.ComputerOffline) throw IOException("The computer is offline.")
+ if (link is LinkState.Failed && link.status in listOf(403, 426)) throw HostError(requireNotNull(link.status), link.message)
+ delay(100)
+ }
+ @Suppress("UNREACHABLE_CODE") error("Unreachable")
+ }
+
+ internal fun action(key: String, operation: suspend () -> Unit) {
+ if (state.value.loading || key in state.value.busy) return
+ mutableState.update { it.copy(busy = it.busy + key, error = null) }
+ val job = contextScope.launch(start = CoroutineStart.LAZY) {
+ try { operation() }
+ catch (error: CancellationException) { throw error }
+ catch (error: Exception) { showError(error) }
+ finally { actions.remove(key); mutableState.update { it.copy(busy = it.busy - key) } }
+ }
+ actions[key] = job
+ job.start()
+ }
+
+ internal fun showError(error: Exception) { mutableState.update { it.copy(loading = false, error = error.message ?: "Couldn't complete the action.") } }
+
+ private data class WidgetSource(val computer: Computer?, val bots: List<Bot>, val usage: JsonObject, val fresh: Boolean)
+ @OptIn(FlowPreview::class)
+ private fun observeWidgets(owner: WidgetOwner) {
+ contextScope.launch {
+ state.filter { !it.loading && it.contextId == owner.scope }
+ .map { WidgetSource(it.computers.firstOrNull(), it.bots, it.usage, it.widgetBotsCurrent) }
+ .distinctUntilChanged().debounce(350).collect { source ->
+ try {
+ val usage = UsageReport.decode(source.usage)
+ val accepted = withContext(Dispatchers.IO) { WidgetStore.publish(getApplication(), owner, source.computer, source.bots, usage, source.fresh, false) }
+ if (!accepted) return@collect
+ WidgetRefreshWorker.schedule(getApplication(), source.computer != null)
+ CodyncWidgets.update(getApplication())
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) { mutableState.update { it.copy(error = "Couldn't update widgets. Open State and try again.") } }
+ }
+ }
+ }
+
+ override fun onCleared() {
+ state.value.voice?.id?.let { VoiceService.stop(getApplication(), it) }
+ voiceBinding?.session?.end()
+ channel?.close()
+ val old = database
+ val retiring = contextJob
+ val book = draftBook
+ val drafts = state.value.drafts.values.toList()
+ CoroutineScope(Dispatchers.IO).launch {
+ retiring.cancelAndJoin()
+ try { book?.save(drafts) }
+ catch (_: Exception) { /* An already closing activity cannot report a storage error. */ }
+ finally { old?.close() }
+ }
+ super.onCleared()
+ }
+}
+
+fun body(vararg values: Pair<String, String?>): JsonObject = buildJsonObject {
+ for ((key, value) in values) if (value != null) put(key, value)
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt
new file mode 100644
index 00000000..42d6c0fe
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt
@@ -0,0 +1,125 @@
+package com.codync.android
+
+import android.app.Application
+import android.os.Build
+import java.io.File
+import java.io.IOException
+import kotlinx.coroutines.sync.withLock
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.json.*
+
+// Accounts, account computers and starting over: what the account sheet and Computers & settings ask for.
+
+fun AppStore.signIn(apple: Boolean = false, hosted: Boolean = false) = sessionAction {
+ if (hosted) NativeAccounts.hostedSignIn() else NativeAccounts.signIn(apple)
+}
+fun AppStore.switchAccount(account: SavedAccount) = sessionAction { NativeAccounts.switch(account) }
+fun AppStore.retryAccounts() { NativeAccounts.retry() }
+fun AppStore.signOut() = sessionAction {
+ val old = state.value.account.accounts.firstOrNull { it.userId == state.value.account.userId } ?: return@sessionAction
+ NativeAccounts.signOut(old.sessionId)
+ transitions.withLock {
+ // The SDK updates its session synchronously; its observer may be queued behind us.
+ val userId = com.clerk.api.Clerk.activeSession?.user?.id
+ retireContext()
+ loadContext(userId)
+ val remaining = com.clerk.api.Clerk.auth.sessions.any { it.user?.id == old.userId && it.status == com.clerk.api.session.Session.SessionStatus.ACTIVE }
+ if (!remaining) withContext(Dispatchers.IO) {
+ LocalStore(getApplication(), old.userId).erase()
+ File(getApplication<Application>().cacheDir, "codync-images-${LocalStore.referenceId(old.userId)}").deleteRecursively()
+ }
+ }
+}
+
+fun AppStore.refreshCloud() = action("cloud") {
+ val client = cloud ?: return@action
+ try {
+ client.registerDevice(Build.MODEL.take(100))
+ val computers = client.computers()
+ mutableState.update { it.copy(cloudComputers = computers) }
+ val target = computers.firstOrNull { remote -> state.value.computers.isEmpty() && remote.computerId !in asked }
+ if (target != null) requestAccess(target)
+ } catch (error: CloudError) { if (!error.isTransient) throw error }
+}
+
+fun AppStore.requestAccess(target: CloudComputer) = action("access") {
+ val client = requireNotNull(cloud) { "Sign in to reach your account." }
+ require(state.value.computers.isEmpty() || state.value.computers.first().id == target.computerId) { "Forget the current computer before connecting a different one." }
+ asked.add(target.computerId)
+ val ticket = client.requestAccess(target.computerId, target.signKey)
+ mutableState.update { it.copy(access = ticket) }
+ try {
+ while (currentCoroutineContext().isActive) {
+ if (System.currentTimeMillis() >= ticket.expiresAt) throw CloudError(410, "requestExpired")
+ delay(2_000)
+ val status = try { client.accessStatus(ticket.requestId) }
+ catch (error: CloudError) { if (error.isTransient) continue else throw error }
+ require(status.requestId == ticket.requestId && (status.computerId == null || status.computerId == ticket.computerId)) { "Invalid access response" }
+ when (status.state) {
+ "pending" -> continue
+ "approved" -> {
+ // Pin only the key used in the SAS. The first authenticated hello supplies addresses and box key.
+ val computer = Computer(ticket.computerId, target.name, ticket.signKey, cloud = BuildConfig.CLOUD_URL)
+ computer.validate()
+ withContext(Dispatchers.IO) { local.saveComputers(listOf(computer)); local.completeSetup() }
+ mutableState.update { it.copy(computers = listOf(computer), setupComplete = true) }
+ openMirror(); connect(); return@action
+ }
+ "denied" -> throw IOException("${target.name} declined the request.")
+ else -> throw CloudError(410, "requestExpired")
+ }
+ }
+ } finally { mutableState.update { it.copy(access = null) } }
+}
+
+fun AppStore.cancelAccess() {
+ val ticket = state.value.access
+ val client = cloud
+ val request = actions["access"]
+ action("cancelAccess") {
+ request?.cancelAndJoin()
+ if (ticket != null && client != null) client.cancelAccess(ticket.requestId)
+ }
+}
+
+fun AppStore.forgetComputer() = sessionAction {
+ transitions.withLock {
+ val userId = state.value.account.userId
+ val id = state.value.computers.firstOrNull()?.id
+ retireContext()
+ if (id != null) asked.add(id)
+ withContext(Dispatchers.IO) {
+ local.saveComputers(emptyList())
+ local.directory.listFiles()?.filter { it.name.startsWith("mirror-") || it.name.startsWith("drafts-") }?.forEach { it.delete() }
+ }
+ loadContext(userId)
+ }
+}
+
+fun AppStore.skipSetup() = action("setup") {
+ withContext(Dispatchers.IO) { local.completeSetup() }
+ mutableState.update { it.copy(setupComplete = true) }
+}
+
+fun AppStore.clearError() { mutableState.update { it.copy(error = null) } }
+
+fun AppStore.startOver() = sessionAction {
+ transitions.withLock {
+ retireContext()
+ withContext(NonCancellable) {
+ NativeAccounts.reset()
+ withContext(Dispatchers.IO) {
+ LocalStore.eraseAll(getApplication())
+ WidgetStore.reset(getApplication())
+ PushPreferences.reset(getApplication())
+ val cache = getApplication<Application>().cacheDir
+ File(cache, "shared-attachments").deleteRecursively()
+ cache.listFiles()?.filter { it.name.startsWith("codync-images") }?.forEach { it.deleteRecursively() }
+ }
+ mutableState.update { it.copy(account = AccountState(ready = true), error = null) }
+ loadContext(null)
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
new file mode 100644
index 00000000..3c9bbafb
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
@@ -0,0 +1,123 @@
+package com.codync.android
+
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.json.*
+
+// Bots and groups, their routines, usage, and the host queries the screens make.
+
+fun AppStore.command(method: String, body: JsonObject = JsonObject(emptyMap()), key: String = method, onSuccess: () -> Unit = {}) = action(key) {
+ val active = ready()
+ val response = active.call(method, body)
+ response.jsonObject["bot"]?.let { value ->
+ withContext(Dispatchers.IO) { requireNotNull(database).receive(HostClient.decode(value.jsonObject)) }
+ }
+ response.jsonObject["entry"]?.let { value ->
+ withContext(Dispatchers.IO) { requireNotNull(database).receive(listOf(Entry.decode(value.jsonObject))) }
+ }
+ refresh()
+ onSuccess()
+}
+
+fun AppStore.saveBot(draft: BotDraft, onSaved: () -> Unit) = action("editor") {
+ val active = ready()
+ val result = active.call(if (draft.id == null) "createBot" else "updateBot", draft.body())
+ val bot = HostClient.decode(result.jsonObject.getValue("bot").jsonObject)
+ withContext(Dispatchers.IO) { requireNotNull(database).receive(bot) }
+ refresh()
+ openBot(bot.id)
+ onSaved()
+}
+
+fun AppStore.saveGroup(draft: GroupDraft, onSaved: () -> Unit) = action("editor") {
+ val payload = draft.body(state.value.bots)
+ val active = ready()
+ val result = active.call(if (draft.id == null) "createBot" else "updateBot", payload)
+ val bot = HostClient.decode(result.jsonObject.getValue("bot").jsonObject)
+ withContext(Dispatchers.IO) { requireNotNull(database).receive(bot) }
+ refresh()
+ openBot(bot.id)
+ onSaved()
+}
+
+fun AppStore.deleteBot(bot: Bot, onDeleted: () -> Unit) = action("delete:" + bot.id) {
+ val active = ready()
+ active.call("deleteBot", body("botId" to bot.id))
+ mutableState.update { it.copy(selectedBot = it.selectedBot.takeUnless { id -> id == bot.id },
+ drafts = it.drafts.filterValues { draft -> draft.botId != bot.id }) }
+ persistDrafts()
+ onDeleted()
+}
+
+/** A host call for the screens that keep their own state (memory): waits for the connection first. */
+internal suspend fun AppStore.hostCall(method: String, body: JsonObject, timeoutMillis: Long = 240_000): JsonElement = ready().call(method, body, timeoutMillis)
+internal suspend fun AppStore.hostFiles(): HostFiles = HostFiles(ready())
+
+fun AppStore.loadRoutines(botId: String) = action("routines:$botId") { receiveRoutines(botId) }
+private suspend fun AppStore.receiveRoutines(botId: String) {
+ val active = ready()
+ val response = active.call("routines", body("botId" to botId))
+ val listing = WireJson.decodeFromJsonElement<RoutineListing>(response)
+ mutableState.update { it.copy(routines = it.routines + (botId to listing)) }
+}
+fun AppStore.saveRoutine(botId: String, draft: RoutineDraft, saved: (Routine) -> Unit) = action("routines:$botId") {
+ val active = ready()
+ val response = active.call("saveRoutine", draft.body(botId))
+ val routine = WireJson.decodeFromJsonElement<Routine>(response.jsonObject.getValue("routine"))
+ receiveRoutines(botId)
+ saved(routine)
+}
+fun AppStore.routineAction(botId: String, id: String, method: String, enabled: Boolean? = null, done: () -> Unit = {}) = action("routines:$botId") {
+ require(method in listOf("setRoutineEnabled", "deleteRoutine", "runRoutine"))
+ val active = ready()
+ active.call(method, buildJsonObject { put("botId", botId); put("id", id); enabled?.let { put("enabled", it) } })
+ receiveRoutines(botId)
+ done()
+}
+/** Queries belong to the account runtime as well as their screen; retiring either cancels them. */
+internal suspend fun AppStore.hostQuery(method: String, payload: JsonObject, timeoutMillis: Long = 20_000,
+ expectedGeneration: Int = state.value.generation): JsonElement {
+ val request = contextScope.async {
+ check(state.value.generation == expectedGeneration) { "The active account changed." }
+ val active = ready()
+ check(state.value.generation == expectedGeneration) { "The active account changed." }
+ active.call(method, payload, timeoutMillis = timeoutMillis)
+ }
+ try { return request.await() } finally { request.cancel() }
+}
+suspend fun AppStore.agentModels(backend: String): AgentModels {
+ val response = hostQuery("agentModels", body("backend" to backend), timeoutMillis = 300_000)
+ return WireJson.decodeFromJsonElement(response)
+}
+fun AppStore.refreshUsage(force: Boolean = true) = action("usage") {
+ val active = ready()
+ // The existing host can spend up to a minute reading an installed provider.
+ val result = active.call("usage", buildJsonObject { put("refresh", force) }, timeoutMillis = 75_000)
+ val response = result.jsonObject
+ UsageReport.decode(response)
+ withContext(Dispatchers.IO) { requireNotNull(database).apply(MirrorEvent.Usage(response)) }
+ refresh()
+ widgetOwner?.let { owner ->
+ val current = state.value
+ withContext(Dispatchers.IO) { WidgetStore.publish(getApplication(), owner, current.computers.firstOrNull(),
+ current.bots, UsageReport.decode(current.usage), false, true) }
+ CodyncWidgets.update(getApplication())
+ }
+}
+suspend fun AppStore.listDirs(path: String?): DirListing {
+ val response = hostQuery("listDirs", body("path" to path))
+ return WireJson.decodeFromJsonElement(response)
+}
+suspend fun AppStore.routineSchedule(triggers: List<JsonObject>, zone: String): RoutineSchedulePreview {
+ val response = hostQuery("routineSchedule", buildJsonObject { put("triggers", JsonArray(triggers)); put("timeZone", zone) })
+ return WireJson.decodeFromJsonElement(response)
+}
+suspend fun AppStore.routineSchedule(draft: RoutineScheduleDraft): RoutineSchedulePreview {
+ val response = hostQuery("routineSchedule", buildJsonObject { put("draft", WireJson.encodeToJsonElement(draft)) })
+ return WireJson.decodeFromJsonElement(response)
+}
+suspend fun AppStore.routineWebhook(botId: String, id: String, rotate: Boolean = false): RoutineWebhook {
+ val response = hostQuery("routineWebhook", buildJsonObject { put("botId", botId); put("id", id); put("rotate", rotate) })
+ return WireJson.decodeFromJsonElement(response)
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
new file mode 100644
index 00000000..2a3e6256
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
@@ -0,0 +1,146 @@
+package com.codync.android
+
+import android.app.Application
+import java.io.IOException
+import java.util.UUID
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.json.*
+
+// Conversations: opening a bot or thread, history, sending and its retries.
+
+fun AppStore.openBot(id: String?, thread: String? = null) {
+ mutableState.update { it.copy(selectedBot = id, thread = thread, trace = false) }
+ if (id != null) {
+ acknowledgeVisible()
+ if (thread != null) action("thread:" + thread) {
+ val active = ready()
+ val response = active.call("thread", body("botId" to id, "rootId" to thread))
+ receiveEntries(response)
+ }
+ }
+}
+fun AppStore.showTrace(show: Boolean) { mutableState.update { it.copy(trace = show) } }
+
+internal fun AppStore.acknowledgeVisible() {
+ val current = state.value
+ val id = current.selectedBot ?: return
+ if (!foreground || current.trace || channel?.state?.value !is LinkState.Ready) return
+ action("read:" + id + ":" + current.thread) {
+ val response = body("botId" to id, "threadId" to current.thread)
+ channel?.call("markRead", response)
+ }
+}
+
+fun AppStore.loadHistory() {
+ val id = state.value.selectedBot ?: return
+ action("history") {
+ val mirror = requireNotNull(database)
+ if (withContext(Dispatchers.IO) { mirror.historyComplete(id) }) {
+ mutableState.update { it.copy(historyComplete = it.historyComplete + id) }
+ return@action
+ }
+ val before = state.value.entries.filter { it.botId == id }.minOfOrNull(Entry::seq) ?: Long.MAX_VALUE
+ val active = ready()
+ val response = active.call("history", buildJsonObject { put("botId", id); put("beforeSeq", before); put("limit", 100) })
+ val entries = response.jsonObject.getValue("entries").jsonArray.map { Entry.decode(it.jsonObject) }
+ withContext(Dispatchers.IO) {
+ mirror.receive(entries)
+ if (entries.size < 100) mirror.finishHistory(id)
+ }
+ if (entries.size < 100) mutableState.update { it.copy(historyComplete = it.historyComplete + id) }
+ refresh()
+ }
+}
+
+fun AppStore.send(text: String, files: List<OutgoingFile> = emptyList()) {
+ val id = state.value.selectedBot ?: return
+ if (text.isBlank() && files.isEmpty()) return
+ val send = PendingSend(UUID.randomUUID().toString(), id, state.value.thread, text.trim(), System.currentTimeMillis(), files = files)
+ action("save:" + send.nonce) { savePending(send); deliver(send) }
+}
+
+fun AppStore.retry(send: PendingSend) = action("send:" + send.nonce) { deliver(send.copy(status = SendStatus.Sending, error = null)) }
+fun AppStore.discard(send: PendingSend) = action("discard:" + send.nonce) {
+ require(send.status == SendStatus.Failed) { "Cancel a queued message before discarding it." }
+ withContext(Dispatchers.IO) { requireNotNull(database).discard(send.nonce) }
+ refresh()
+}
+fun AppStore.cancelQueued(send: PendingSend) = action("cancel:" + send.nonce) {
+ val active = requireNotNull(channel) { "Reconnect to the relay to cancel this message." }
+ when (active.cancelQueued(send.nonce)) {
+ "cancelled" -> { withContext(Dispatchers.IO) { requireNotNull(database).discard(send.nonce) }; refresh() }
+ "delivering" -> savePending(send.copy(status = SendStatus.Delivering))
+ else -> throw IOException("Couldn't take the message back. It may have been delivered already.")
+ }
+}
+
+internal suspend fun AppStore.deliver(send: PendingSend) {
+ if (!sends.add(send.nonce)) return
+ try {
+ if (state.value.entries.any { it.botId == send.botId && it.clientNonce == send.nonce }) return
+ savePending(send)
+ val active = channel
+ if (active?.state?.value is LinkState.ComputerOffline && send.files.isEmpty()) {
+ savePending(send.copy(status = SendStatus.Waiting))
+ try { active.enqueue(send); return }
+ catch (error: IOException) {
+ if (error.message != "hostOnline") throw error
+ // Relay presence can lag; use the same nonce after the channel becomes ready.
+ }
+ }
+ val connection = ready()
+ val ids = mutableListOf<String>()
+ var completed = 0L
+ val total = send.files.sumOf { it.size }
+ for (file in send.files) {
+ val id = UUID.randomUUID().toString()
+ HostFiles(connection).upload(send.botId, id, file) { offset ->
+ val percent = if (total == 0L) 100 else ((completed + offset) * 100 / total).toInt()
+ mutableState.update { it.copy(uploadProgress = it.uploadProgress + (send.nonce to percent)) }
+ }
+ completed += file.size
+ ids.add(id)
+ withContext(Dispatchers.IO) { attachments.cache(id, file) }
+ }
+ val result = connection.call("send", buildJsonObject {
+ put("botId", send.botId); put("text", send.text); put("clientNonce", send.nonce)
+ send.threadId?.let { put("threadId", it) }
+ if (ids.isNotEmpty()) put("attachments", JsonArray(ids.map(::JsonPrimitive)))
+ })
+ val entry = Entry.decode(result.jsonObject.getValue("entry").jsonObject)
+ withContext(Dispatchers.IO) { requireNotNull(database).receive(listOf(entry)) }
+ refresh()
+ val bot = state.value.bots.firstOrNull { it.id == send.botId }
+ if (bot != null && PushPreferences.tasks(getApplication()) && getApplication<Application>().getSystemService(android.app.NotificationManager::class.java).areNotificationsEnabled()) {
+ val watch = withContext(Dispatchers.IO) { TaskFeed(local.directory).start(bot) }
+ NotificationDisplay.task(getApplication(), local.referenceId, state.value.computers.first().id, watch)
+ syncPush(); PushDelivery.schedule(getApplication())
+ }
+ } catch (error: CancellationException) {
+ withContext(NonCancellable) { savePending(send.copy(status = SendStatus.Failed, error = "Sending was interrupted. Retry uses the same message ID.")) }
+ throw error
+ } catch (error: Exception) {
+ savePending(send.copy(status = SendStatus.Failed, error = error.message ?: "Couldn't send."))
+ } finally {
+ sends.remove(send.nonce)
+ mutableState.update { it.copy(uploadProgress = it.uploadProgress - send.nonce) }
+ }
+}
+
+internal suspend fun AppStore.savePending(send: PendingSend) {
+ withContext(Dispatchers.IO) { requireNotNull(database).save(send) }
+ refresh()
+}
+fun AppStore.respond(entry: Entry, option: String?) = action("permission:" + entry.id) {
+ val active = ready()
+ active.call("respondPermission", body("entryId" to entry.id, "optionId" to option))
+ delay(2_000)
+}
+
+private suspend fun AppStore.receiveEntries(response: JsonElement) {
+ val entries = response.jsonObject.getValue("entries").jsonArray.map { Entry.decode(it.jsonObject) }
+ withContext(Dispatchers.IO) { requireNotNull(database).receive(entries) }
+ refresh()
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
new file mode 100644
index 00000000..216c20cb
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
@@ -0,0 +1,242 @@
+package com.codync.android
+
+import android.os.Build
+import java.io.IOException
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.json.*
+
+// Pairing, the encrypted link to the computer and the mirror's event stream.
+
+fun AppStore.setRoute(route: ConnectionRoute) = action("route") {
+ val computer = state.value.computers.firstOrNull() ?: return@action
+ val changed = computer.copy(route = route)
+ withContext(Dispatchers.IO) { local.saveComputers(listOf(changed)) }
+ mutableState.update { it.copy(computers = listOf(changed)) }
+ connectionJob?.cancelAndJoin(); connect()
+}
+
+fun AppStore.setForeground(active: Boolean) {
+ foreground = active
+ foregroundState.value = active
+ PushDelivery.foreground = transportRequired
+ if (active && !state.value.loading) {
+ connect()
+ acknowledgeVisible()
+ refreshCloud()
+ }
+ if (!active) {
+ pairingJob?.cancel()
+ if (!transportRequired) {
+ connectionJob?.cancel()
+ graceJob?.cancel()
+ channel?.close()
+ }
+ }
+}
+
+fun AppStore.pair(text: String) {
+ if (pairingJob?.isActive == true) return
+ pairingJob = contextScope.launch {
+ state.first { !it.loading }
+ mutableState.update { it.copy(pairing = true, error = null) }
+ try {
+ val pairing = Pairing.parse(text, BuildConfig.URL_SCHEME)
+ val old = state.value.computers.firstOrNull()
+ require(old == null || old.id == pairing.computer.id) { "Use Start over to pair a different computer." }
+ require(old == null || old.signKey == pairing.computer.signKey) { "This computer's identity changed. Start over before pairing again." }
+ val identity = withContext(Dispatchers.IO) { local.identity() }
+ val computer = HostConnector.pair(pairing, identity, Build.MODEL.take(100))
+ withContext(Dispatchers.IO) { local.saveComputers(listOf(computer)); local.completeSetup() }
+ mutableState.update { it.copy(computers = listOf(computer), setupComplete = true) }
+ if (database == null) openMirror()
+ connect()
+ } catch (error: CancellationException) { throw error }
+ catch (error: Exception) { showError(error) }
+ finally { mutableState.update { it.copy(pairing = false) } }
+ }
+}
+
+fun AppStore.connect() {
+ if (connectionJob?.isActive == true || !transportRequired) return
+ val computer = state.value.computers.firstOrNull() ?: return
+ val previous = connectionJob
+ connectionJob = contextScope.launch {
+ previous?.cancelAndJoin()
+ var backoff = 1_000L
+ while (transportRequired) {
+ var connected: EncryptedChannel? = null
+ try {
+ showConnection(LinkState.Connecting)
+ val identity = withContext(Dispatchers.IO) { local.identity() }
+ val target = state.value.computers.firstOrNull { it.id == computer.id } ?: return@launch
+ val active = HostConnector.connect(target, identity)
+ connected = active
+ channel = active
+ coroutineScope {
+ launch {
+ active.mailbox.collect { event ->
+ val nonce = event["nonce"]?.jsonPrimitive?.content ?: return@collect
+ val send = state.value.pending.firstOrNull { it.nonce == nonce } ?: return@collect
+ val status = if (event["t"]?.jsonPrimitive?.content == "mbox.delivered") SendStatus.Delivering else SendStatus.Failed
+ savePending(send.copy(status = status))
+ }
+ }
+ launch {
+ active.state.collectLatest { link ->
+ showConnection(link)
+ if (link is LinkState.ComputerOffline) {
+ reconcileMailbox(active)
+ }
+ if (link is LinkState.Ready) {
+ val updated = HostClient.hello(active, target)
+ val hello = active.call("hello").jsonObject
+ withContext(Dispatchers.IO) {
+ local.saveComputers(listOf(updated))
+ requireNotNull(database).setStamp(requireNotNull(hello["hostId"]?.jsonPrimitive?.content),
+ BuildConfig.VERSION_NAME + "/" + hello["version"]?.jsonPrimitive?.content)
+ }
+ mutableState.update { it.copy(computers = listOf(updated)) }
+ noteHello(hello)
+ // The event catch-up is ordered by revision; bot revisions can
+ // follow hundreds of historical entries. Load the current roster
+ // without moving the event cursor before consuming that stream.
+ if (state.value.bots.isEmpty()) {
+ val roster = HostClient.bots(active)
+ if (BuildConfig.DEBUG) android.util.Log.d("CodyncSync", "Initial roster: ${roster.size} bots")
+ withContext(Dispatchers.IO) { requireNotNull(database).receive(roster) }
+ }
+ mutableState.update { it.copy(rosterLoaded = true) }
+ refresh()
+ backoff = 1_000
+ reconcileMailbox(active)
+ acknowledgeVisible()
+ syncPush()
+ while (isActive) {
+ if (state.value.mismatch != null) { awaitUpdate(active); continue }
+ val cursor = withContext(Dispatchers.IO) { requireNotNull(database).revision() }
+ try {
+ consumeEvents(active, cursor)
+ } catch (_: Resync) { /* The cursor remains the last committed event. */ }
+ }
+ }
+ }
+ }
+ val end = active.state.first { it is LinkState.Failed } as LinkState.Failed
+ val status = end.status
+ if (status != null) throw HostError(status, end.message)
+ throw IOException(end.message)
+ }
+ } catch (error: CancellationException) { throw error }
+ catch (error: Exception) {
+ if (BuildConfig.DEBUG) android.util.Log.d("CodyncSync", "Sync failed: ${error.javaClass.simpleName}")
+ showConnection(LinkState.Failed(error.message ?: "Can't reach the computer.", (error as? HostError)?.status))
+ if (error is SecurityException || error is HostError && error.status in listOf(403, 426)) return@launch
+ } finally {
+ connected?.close()
+ if (channel === connected) channel = null
+ }
+ delay(backoff)
+ backoff = minOf(backoff * 2, 20_000)
+ }
+ }
+}
+
+/** Drain available catch-up in bounded transactions, without delaying a lone live event. */
+private suspend fun AppStore.consumeEvents(active: EncryptedChannel, cursor: Long): Unit = coroutineScope {
+ val source = active.events(cursor).produceIn(this)
+ try {
+ while (isActive) {
+ val batch = mutableListOf<MirrorEvent>()
+ var next: JsonObject? = source.receiveCatching().getOrThrow()
+ var resync = false
+ while (next != null && batch.size < 64) {
+ when (val event = decode(next)) {
+ null -> {}
+ MirrorEvent.Resync -> { resync = true; break }
+ else -> batch.add(event)
+ }
+ next = if (batch.size < 64) source.tryReceive().getOrNull() else null
+ }
+ withContext(Dispatchers.IO) { requireNotNull(database).apply(batch) }
+ refresh()
+ if (batch.any { it is MirrorEvent.EntryChanged && it.entry.isChat }) acknowledgeVisible()
+ if (resync) throw Resync()
+ }
+ } finally { source.cancel() }
+ throw IOException("The event subscription ended.")
+}
+
+/** What an event this app can't decode leads to, as on iOS: never skip data unread while fetching everything again can help. */
+internal enum class Undecodable { Rewind, AwaitUpdate, Skip }
+
+internal fun undecodable(alreadyRewound: Boolean, hostNewer: Boolean): Undecodable = when {
+ !alreadyRewound -> Undecodable.Rewind
+ // A newer host this app can't follow: stop syncing until one side updates.
+ hostNewer -> Undecodable.AwaitUpdate
+ else -> Undecodable.Skip
+}
+
+/** An event, or null when it can't be read and is passed over; a rewind or a wait restarts the stream. */
+private suspend fun AppStore.decode(event: JsonObject): MirrorEvent? {
+ try { return MirrorEvent.decode(event) }
+ catch (error: Exception) {
+ if (BuildConfig.DEBUG) android.util.Log.d("CodyncSync", "Undecodable event: ${error.javaClass.simpleName}")
+ val version = state.value.hello?.text("version").orEmpty()
+ when (undecodable(rewoundFor == version, AppVersion.isBelow(BuildConfig.VERSION_NAME, version))) {
+ Undecodable.Rewind -> {
+ rewoundFor = version
+ withContext(Dispatchers.IO) { requireNotNull(database).rewind() }
+ throw Resync()
+ }
+ Undecodable.AwaitUpdate -> { mutableState.update { it.copy(unreadable = true) }; throw Resync() }
+ Undecodable.Skip -> { mutableState.update { it.copy(unreadable = true) }; return null }
+ }
+ }
+}
+
+/** Reached, but nothing to sync until one side updates: ask again every 30 s (a host update restarts the link anyway). */
+private suspend fun AppStore.awaitUpdate(active: EncryptedChannel) {
+ delay(30_000)
+ noteHello(active.call("hello").jsonObject)
+}
+
+/** A different host version may read fine: forget that its data was unreadable (iOS `noteHostVersion`). */
+private fun AppStore.noteHello(hello: JsonObject) = mutableState.update {
+ it.copy(hello = hello, unreadable = it.unreadable && it.hello?.text("version") == hello.text("version"))
+}
+
+private fun AppStore.showConnection(link: LinkState) {
+ mutableState.update { it.copy(actualConnection = link) }
+ val immediate = link is LinkState.Ready || link is LinkState.Failed && link.status in listOf(403, 426)
+ if (immediate) {
+ graceJob?.cancel()
+ mutableState.update { it.copy(connection = link) }
+ } else if (graceJob?.isActive != true) {
+ val grace = if (state.value.connection is LinkState.Ready) 5_000L else 1_000L
+ graceJob = contextScope.launch {
+ delay(grace)
+ mutableState.update { it.copy(connection = it.actualConnection) }
+ }
+ }
+}
+
+private suspend fun AppStore.reconcileMailbox(active: EncryptedChannel) {
+ if (active.route != HostRoute.Relay || state.value.pending.none { it.status in listOf(SendStatus.Waiting, SendStatus.Delivering) }) return
+ try {
+ val response = active.queued()
+ val held = response.getValue("items").jsonArray.associate { it.jsonObject.getValue("nonce").jsonPrimitive.content to it.jsonObject.getValue("state").jsonPrimitive.content }
+ for (send in state.value.pending.filter { it.status in listOf(SendStatus.Waiting, SendStatus.Delivering) }) {
+ savePending(send.copy(status = when (held[send.nonce]) {
+ "queued" -> SendStatus.Waiting
+ "delivering" -> SendStatus.Delivering
+ else -> SendStatus.Failed
+ }))
+ }
+ } catch (error: CancellationException) { throw error }
+ catch (_: IOException) { /* Reconcile when the relay connection recovers. */ }
+}
+
+/** The host asked for the stream to start over from the mirror's cursor (or the mirror rewound). */
+private class Resync : IOException()
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnectorSignIn.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnectorSignIn.kt
new file mode 100644
index 00000000..208e980c
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnectorSignIn.kt
@@ -0,0 +1,87 @@
+package com.codync.android
+
+import android.app.Application
+import android.net.Uri
+import java.io.IOException
+import androidx.lifecycle.viewModelScope
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.json.*
+
+// Connector sign-in in the browser, and its return to the app.
+
+fun AppStore.connectorSignIn(id: String, requestId: String? = null) = action("oauth") {
+ val generation = state.value.generation
+ oauthRequestId = requestId
+ val response = hostQuery("connectorSignIn", body("id" to id), 60_000)
+ val plan = WireJson.decodeFromJsonElement<ConnectorSignIn>(response)
+ val computer = requireNotNull(state.value.computers.firstOrNull())
+ externalHttps(plan.url)
+ if (plan.callback == "app") {
+ val pending = PendingConnectorOAuth.create(plan, id, computer.id, System.currentTimeMillis()).copy(requestId = requestId)
+ withContext(Dispatchers.IO) { ConnectorOAuthBook(local.directory).save(pending) }
+ } else {
+ require(plan.callback == "host") { "This sign-in callback needs a newer app." }
+ withContext(Dispatchers.IO) { ConnectorOAuthBook(local.directory).clear() }
+ }
+ val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, Uri.parse(plan.url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
+ try { getApplication<Application>().startActivity(intent) }
+ catch (error: Exception) { withContext(Dispatchers.IO) { ConnectorOAuthBook(local.directory).clear() }; throw IOException("Couldn't open the sign-in browser.", error) }
+ if (plan.callback == "host") {
+ val complete = withTimeoutOrNull(600_000) {
+ while (true) {
+ delay(2_000)
+ combine(foregroundState, state) { visible, current -> visible && current.generation == generation && current.actualConnection is LinkState.Ready }.first { it }
+ val listing = hostQuery("connectors", JsonObject(emptyMap()), 60_000, generation)
+ val connectors = WireJson.decodeFromJsonElement<List<InstalledConnector>>(listing.jsonObject.getValue("items"))
+ if (connectors.any { it.id == id && it.auth == "signedIn" }) {
+ requestId?.let { finishConnectionRequest(it, connectorId = id, expectedGeneration = generation) }
+ refreshPlugins()
+ return@withTimeoutOrNull true
+ }
+ }
+ @Suppress("UNREACHABLE_CODE") false
+ }
+ if (complete == null) throw IOException("Sign-in wasn't confirmed. Check the computer and installed connections before trying again.")
+ }
+}
+fun AppStore.cancelConnectorSignIn() = action("cancelOAuth") { cancelOAuthPending(null) }
+fun AppStore.cancelConnectionRequestSignIn(entryId: String) = action("cancelOAuth") { cancelOAuthPending(entryId) }
+internal suspend fun AppStore.cancelOAuthPending(requestId: String?) {
+ val pending = withContext(Dispatchers.IO) { ConnectorOAuthBook(local.directory).read() }
+ if (requestId != null && pending?.requestId != requestId && oauthRequestId != requestId) return
+ val old = actions["oauth"]
+ old?.cancelAndJoin()
+ withContext(Dispatchers.IO) { ConnectorOAuthBook(local.directory).clear() }
+ oauthRequestId = null
+ refreshPlugins()
+}
+fun AppStore.finishConnectorSignIn(uri: Uri) {
+ linkJob?.cancel()
+ linkJob = viewModelScope.launch {
+ var expectedGeneration: Int? = null
+ try {
+ val back = OAuthReturn.parse(uri.toString(), BuildConfig.URL_SCHEME)
+ val activated = deadline(35_000, "This account didn't finish opening.") { state.first { !it.loading && it.account.ready &&
+ it.contextId == LocalStore.referenceId(it.account.userId ?: "local") } }
+ val generation = activated.generation
+ expectedGeneration = generation
+ val directory = local.directory
+ val pending = withContext(Dispatchers.IO) { ConnectorOAuthBook(directory).read() }
+ ?: throw IOException("No connector sign-in is pending for this account. Start sign-in again.")
+ pending.validate(back, activated.computers.firstOrNull()?.id.orEmpty(), System.currentTimeMillis())
+ val response = hostQuery("connectorSignInFinish", body("state" to back.state, "code" to back.code, "error" to back.error), 60_000, generation)
+ val connector = WireJson.decodeFromJsonElement<InstalledConnector>(response.jsonObject.getValue("connector"))
+ pending.requestId?.let { finishConnectionRequest(it, connectorId = connector.id, expectedGeneration = generation) }
+ withContext(Dispatchers.IO) { ConnectorOAuthBook(directory).clear() }
+ if (state.value.generation == generation) { oauthRequestId = null; refreshPlugins(); mutableState.update { it.copy(error = null) } }
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) {
+ mutableState.update {
+ if (expectedGeneration != null && it.generation != expectedGeneration) it
+ else it.copy(error = "Connector sign-in didn't complete. Reconnect and start sign-in again; the connector remains installed.")
+ }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt
new file mode 100644
index 00000000..9126494b
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt
@@ -0,0 +1,113 @@
+package com.codync.android
+
+import android.net.Uri
+import java.io.File
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.json.*
+
+// Composer drafts (saved as you type) and the files that go with them.
+
+fun AppStore.editDraft(botId: String, thread: String?, text: String) {
+ if (state.value.loading) return
+ val lane = ComposerDraft.lane(botId, thread)
+ val current = state.value.drafts[lane]
+ if (current?.text == text || current == null && text.isEmpty()) return
+ try { updateDraft((current ?: ComposerDraft(botId, thread)).copy(text = text)) }
+ catch (error: Exception) { showError(error) }
+}
+
+fun AppStore.addDraftFiles(botId: String, thread: String?, files: List<OutgoingFile>) {
+ check(!state.value.loading) { "Wait for the account to finish opening before adding files." }
+ val current = state.value.drafts[ComposerDraft.lane(botId, thread)] ?: ComposerDraft(botId, thread)
+ updateDraft(current.copy(files = current.files + files))
+}
+
+fun AppStore.removeDraftFile(botId: String, thread: String?, file: OutgoingFile) = action("draft-file:" + file.path) {
+ val current = state.value.drafts[ComposerDraft.lane(botId, thread)] ?: return@action
+ updateDraft(current.copy(files = current.files - file))
+ draftWriter?.join()
+ check(savedDrafts.values.none { draft -> draft.files.any { it.path == file.path } }) { "Couldn't save the attachment removal. Retry before leaving this chat." }
+ if (state.value.pending.none { send -> send.files.any { it.path == file.path } }) withContext(Dispatchers.IO) { attachments.discard(file) }
+}
+
+private fun AppStore.updateDraft(draft: ComposerDraft) {
+ val book = draftBook ?: return
+ val drafts = if (draft.text.isEmpty() && draft.files.isEmpty()) state.value.drafts - draft.lane else state.value.drafts + (draft.lane to draft)
+ book.validate(drafts.values, checkPaths = false)
+ mutableState.update { it.copy(drafts = drafts) }
+ persistDrafts()
+}
+
+internal fun AppStore.persistDrafts() {
+ if (draftWriter?.isActive == true) return
+ val book = draftBook ?: return
+ draftWriter = contextScope.launch {
+ try {
+ while (isActive) {
+ val saving = state.value.drafts.values.toList()
+ withContext(Dispatchers.IO) { book.save(saving) }
+ savedDrafts = saving.associateBy { it.lane }
+ if (state.value.drafts.values.toList() == saving) break
+ }
+ } catch (error: CancellationException) { throw error }
+ catch (_: Exception) { mutableState.update { it.copy(error = "Couldn't save this draft. Keep the app open and retry.") } }
+ finally { draftWriter = null }
+ }
+}
+
+fun AppStore.sendDraft(botId: String, thread: String?, text: String, onQueued: () -> Unit) {
+ editDraft(botId, thread, text)
+ val lane = ComposerDraft.lane(botId, thread)
+ val draft = state.value.drafts[lane] ?: return
+ if (draft.text != text) return
+ if (draft.text.isBlank() && draft.files.isEmpty()) return
+ action("draft-send:" + lane) {
+ // Persist its nonce before the pending commit. Recovery removes a draft
+ // already represented by a pending or confirmed send with this nonce.
+ persistDrafts()
+ draftWriter?.join()
+ check(savedDrafts[lane] == draft) { "Couldn't save this draft. Retry to send it." }
+ val send = PendingSend(draft.nonce, botId, thread, draft.text.trim(), System.currentTimeMillis(), files = draft.files)
+ savePending(send)
+ mutableState.update { it.copy(drafts = it.drafts - lane) }
+ persistDrafts()
+ onQueued()
+ action("send:" + send.nonce) { deliver(send) }
+ }
+}
+
+fun AppStore.importFiles(uris: List<Uri>, onImported: (List<OutgoingFile>) -> Unit) = action("attachments") {
+ val imported = mutableListOf<OutgoingFile>()
+ try {
+ for (uri in uris) {
+ require(uri.scheme == "content") { "Choose a file using Photos or Files." }
+ imported.add(attachments.import(uri))
+ }
+ onImported(imported.toList())
+ } catch (error: Throwable) {
+ withContext(NonCancellable + Dispatchers.IO) { imported.forEach(attachments::discard) }
+ throw error
+ }
+}
+fun AppStore.removeFile(file: OutgoingFile) = action("remove:" + file.path) { withContext(Dispatchers.IO) { attachments.discard(file) } }
+
+suspend fun AppStore.attachment(botId: String, file: Attachment): File {
+ val request = contextScope.async { downloadLocks.getOrPut(file.id) { Mutex() }.withLock {
+ val destination = withContext(Dispatchers.IO) { attachments.cached(file.id) }
+ if (!destination.exists() || destination.length() != file.size) {
+ val active = ready()
+ HostFiles(active).download(botId, file, destination)
+ withContext(Dispatchers.IO) { attachments.trim() }
+ }
+ destination
+ } }
+ try { return request.await() } finally { request.cancel() }
+}
+fun AppStore.shareAttachment(botId: String, file: Attachment) = action("share:" + file.id) {
+ val source = attachment(botId, file)
+ attachments.share(file, source)
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreExtensions.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreExtensions.kt
new file mode 100644
index 00000000..632da90c
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreExtensions.kt
@@ -0,0 +1,202 @@
+package com.codync.android
+
+import java.io.IOException
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.json.*
+
+// Extensions on the computer: agent setup, connectors, skills, credentials and Composio apps.
+
+suspend fun AppStore.agentAuth(backend: String): AgentAuth {
+ val response = hostQuery("agentAuth", body("backend" to backend), 300_000)
+ refreshBackends()
+ return WireJson.decodeFromJsonElement(response)
+}
+suspend fun AppStore.agentAuthenticate(backend: String, method: String): AgentAuth {
+ val response = hostQuery("agentAuthenticate", body("backend" to backend, "method" to method), 660_000)
+ refreshBackends()
+ return WireJson.decodeFromJsonElement(response)
+}
+suspend fun AppStore.setAgentEnv(backend: String, values: Map<String, String>): AgentAuth {
+ val response = hostQuery("setAgentEnv", buildJsonObject { put("backend", backend); put("vars", WireJson.encodeToJsonElement(values)) }, 300_000)
+ refreshBackends()
+ return WireJson.decodeFromJsonElement(response)
+}
+internal fun AppStore.setupTerminal(owner: String, backend: String, step: String, method: String?): SetupTerminalSession {
+ require(step in listOf("install", "login", "node"))
+ return setupTerminals.getOrPut(owner) {
+ val generation = state.value.generation
+ val transport = object : SetupTerminalTransport {
+ var last: EncryptedChannel? = null
+ suspend fun connection(): EncryptedChannel {
+ check(state.value.generation == generation) { "The active account changed." }
+ val active = ready()
+ last = active
+ return active
+ }
+ override suspend fun setup(cols: Int, rows: Int): String {
+ val active = connection()
+ val response = active.call("agentSetup", buildJsonObject { put("backend", backend); put("step", step);
+ method?.let { put("method", it) }; put("cols", cols); put("rows", rows) }, 300_000)
+ return response.jsonObject.getValue("term").jsonPrimitive.content
+ }
+ override suspend fun awaitActive() { foregroundState.first { it } }
+ override fun output(term: String): Flow<TerminalEvent> = flow {
+ val active = connection()
+ emitAll(active.subscribe("term", body("term" to term)).map(TerminalEvent::decode))
+ }
+ override suspend fun input(term: String, bytes: ByteArray) {
+ val active = connection()
+ active.call("termInput", body("term" to term, "data" to java.util.Base64.getEncoder().encodeToString(bytes)), 10_000)
+ }
+ override suspend fun resize(term: String, cols: Int, rows: Int) {
+ val active = connection()
+ active.call("termResize", buildJsonObject { put("term", term); put("cols", cols); put("rows", rows) }, 10_000)
+ }
+ override suspend fun close(term: String) { last?.takeIf { it.state.value is LinkState.Ready }?.call("termClose", body("term" to term), 2_000) }
+ }
+ SetupTerminalSession(contextScope, transport)
+ }
+}
+internal fun AppStore.closeSetupTerminal(owner: String) { setupTerminals.remove(owner)?.close(); refreshBackends() }
+fun AppStore.refreshPlugins() {
+ if ("plugins" in state.value.busy) { pluginsRefreshAgain = true; return }
+ action("plugins") {
+ do {
+ pluginsRefreshAgain = false
+ val connectors = hostQuery("connectors", JsonObject(emptyMap()))
+ val skills = hostQuery("skills", JsonObject(emptyMap()))
+ val listing = PluginListing(WireJson.decodeFromJsonElement(connectors.jsonObject.getValue("items")),
+ WireJson.decodeFromJsonElement(skills.jsonObject.getValue("items")))
+ mutableState.update { it.copy(plugins = listing) }
+ } while (pluginsRefreshAgain)
+ }
+}
+suspend fun AppStore.marketConnectors(search: String, cursor: String?): MarketConnectors {
+ val response = hostQuery("marketConnectors", body("search" to search, "cursor" to cursor.orEmpty()), 60_000)
+ return WireJson.decodeFromJsonElement(response)
+}
+suspend fun AppStore.marketSkills(): List<MarketSkill> {
+ val response = hostQuery("marketSkills", JsonObject(emptyMap()), 60_000)
+ return WireJson.decodeFromJsonElement(response.jsonObject.getValue("items"))
+}
+suspend fun AppStore.connectorInfo(name: String): MarketConnector {
+ val response = hostQuery("connectorInfo", body("registryName" to name), 60_000)
+ return WireJson.decodeFromJsonElement(response)
+}
+suspend fun AppStore.installedConnectors(): List<InstalledConnector> {
+ val response = hostQuery("connectors", JsonObject(emptyMap()), 60_000)
+ return WireJson.decodeFromJsonElement(response.jsonObject.getValue("items"))
+}
+suspend fun AppStore.verifyConnector(id: String) {
+ hostQuery("connectorVerify", body("id" to id), 120_000)
+ refreshPlugins()
+}
+suspend fun AppStore.importConnectors(config: String): List<InstalledConnector> {
+ val response = hostQuery("importConnectors", body("config" to config), 60_000)
+ refreshPlugins()
+ return WireJson.decodeFromJsonElement(response.jsonObject.getValue("items"))
+}
+suspend fun AppStore.credentialStatus(): CredentialStatus {
+ val response = hostQuery("credentialStatus", JsonObject(emptyMap()), 60_000)
+ return WireJson.decodeFromJsonElement(response)
+}
+suspend fun AppStore.savedLogins(): List<SavedLogin> {
+ val response = hostQuery("credentialLogins", JsonObject(emptyMap()), 60_000)
+ return WireJson.decodeFromJsonElement(response.jsonObject.getValue("items"))
+}
+suspend fun AppStore.saveLogin(site: String, username: String, password: String): SavedLogin {
+ val response = hostQuery("credentialSaveLogin", body("site" to site, "username" to username, "password" to password), 60_000)
+ return WireJson.decodeFromJsonElement(response.jsonObject.getValue("login"))
+}
+suspend fun AppStore.removeLogin(id: String) { hostQuery("credentialRemoveLogin", body("id" to id), 60_000) }
+suspend fun AppStore.onePasswordToken(token: String): CredentialStatus {
+ val response = hostQuery("credentialSetOnePassword", body("token" to token), 60_000)
+ return WireJson.decodeFromJsonElement(response)
+}
+suspend fun AppStore.updateConnectorCredentials(connector: InstalledConnector, values: Map<String, String>) {
+ val fields = credentialReplacements(connector, values)
+ require(fields.isNotEmpty()) { "Enter a value to replace." }
+ hostQuery("credentialUpdateConnector", buildJsonObject { put("id", connector.id); put("fields", WireJson.encodeToJsonElement(fields)) }, 120_000)
+ refreshPlugins()
+}
+suspend fun AppStore.composioStatus(): ComposioStatus {
+ val response = hostQuery("composioStatus", JsonObject(emptyMap()), 60_000)
+ return WireJson.decodeFromJsonElement(response)
+}
+suspend fun AppStore.composioKey(key: String): ComposioStatus {
+ val response = hostQuery("setComposioKey", body("key" to key), 60_000)
+ refreshPlugins()
+ return WireJson.decodeFromJsonElement(response)
+}
+suspend fun AppStore.composioApps(search: String, cursor: String?): ComposioApps {
+ val response = hostQuery("composioToolkits", body("search" to search, "cursor" to cursor.orEmpty()), 60_000)
+ return WireJson.decodeFromJsonElement(response)
+}
+internal fun AppStore.appConnection(owner: String, slug: String, resumeId: String? = null): AppConnectionSession = appConnections.getOrPut(owner) {
+ val generation = state.value.generation
+ val transport = object : AppConnectionTransport {
+ override suspend fun awaitActive() {
+ combine(foregroundState, state) { visible, current ->
+ visible && current.generation == generation && current.actualConnection is LinkState.Ready
+ }.first { it }
+ }
+ override suspend fun start(): ComposioConnect {
+ val response = hostQuery("composioConnect", body("toolkit" to slug), 60_000, generation)
+ return WireJson.decodeFromJsonElement(response)
+ }
+ override suspend fun state(id: String): ComposioConnectionState {
+ val response = hostQuery("composioConnection", body("id" to id), 30_000, generation)
+ return WireJson.decodeFromJsonElement(response)
+ }
+ override suspend fun submit(mode: String, fields: Map<String, String>): ComposioConnectionState {
+ val response = hostQuery("composioConnectFields", buildJsonObject { put("toolkit", slug); put("mode", mode); put("fields", WireJson.encodeToJsonElement(fields)) }, 60_000, generation)
+ return WireJson.decodeFromJsonElement(response)
+ }
+ }
+ AppConnectionSession(contextScope, transport, resumeId)
+}
+internal fun AppStore.closeAppConnection(owner: String) { appConnections.remove(owner)?.close(); refreshPlugins() }
+fun AppStore.completeConnectionRequest(entryId: String, connectorId: String? = null, value: String? = null,
+ username: String? = null, cancel: Boolean = false) = action("connection:$entryId") {
+ try {
+ finishConnectionRequest(entryId, connectorId, value, username, cancel)
+ if (cancel) cancelOAuthPending(entryId)
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) { throw IOException(if (cancel) "Cancellation wasn't confirmed. Reconnect and check this request."
+ else "Connection wasn't confirmed. Check its setup and refresh before trying again.") }
+}
+suspend fun AppStore.finishConnectionRequest(entryId: String, connectorId: String? = null, value: String? = null,
+ username: String? = null, cancel: Boolean = false, expectedGeneration: Int = state.value.generation) {
+ // Own the API reply and its mirror write together; retirement joins both.
+ val request = contextScope.async {
+ check(state.value.generation == expectedGeneration) { "The active account changed." }
+ val active = ready()
+ check(state.value.generation == expectedGeneration) { "The active account changed." }
+ val payload = buildJsonObject { put("entryId", entryId); put("cancel", cancel)
+ connectorId?.let { put("connectorId", it) }; value?.let { put("value", it) }; username?.let { put("username", it) } }
+ val response = active.call("connectorRequestFinish", payload, 120_000)
+ val entry = Entry.decode(response.jsonObject.getValue("entry").jsonObject)
+ withContext(Dispatchers.IO) { requireNotNull(database).receive(listOf(entry)) }
+ refresh()
+ }
+ try { request.await() } finally { request.cancel() }
+}
+fun AppStore.refreshBackends() = action("backends") {
+ val response = hostQuery("refreshBackends", JsonObject(emptyMap()), 60_000)
+ mutableState.update { it.copy(hello = JsonObject(it.hello.orEmpty() + ("backends" to response.jsonObject.getValue("backends")))) }
+}
+suspend fun AppStore.installConnector(item: MarketConnector, option: InstallOption, inputs: Map<String, String>): InstalledConnector {
+ require(option in item.options && option.complete(inputs)) { "Complete the required connector fields." }
+ val response = hostQuery("installConnector", buildJsonObject { put("registryName", item.name); put("option", option.id); put("inputs", WireJson.encodeToJsonElement(inputs)) }, 45_000)
+ val connector = WireJson.decodeFromJsonElement<InstalledConnector>(response.jsonObject.getValue("connector"))
+ refreshPlugins()
+ return connector
+}
+fun AppStore.pluginAction(method: String, payload: JsonObject, done: () -> Unit = {}) = action("plugin") {
+ require(method in listOf("installConnector", "importConnectors", "removeConnector", "installSkill", "removeSkill", "connectorSignOut", "credentialUpdateConnector"))
+ hostQuery(method, payload, 120_000)
+ refreshPlugins()
+ done()
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt
new file mode 100644
index 00000000..3618b53f
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt
@@ -0,0 +1,86 @@
+package com.codync.android
+
+import android.net.Uri
+import androidx.lifecycle.viewModelScope
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.json.*
+
+// Push registration, notification settings and the links notifications and widgets open.
+
+fun AppStore.syncPush() = action("push") {
+ val active = channel?.takeIf { it.state.value is LinkState.Ready } ?: return@action
+ val computer = state.value.computers.firstOrNull() ?: return@action
+ try { PushDelivery.sync(getApplication(), local, computer, active) }
+ catch (error: CancellationException) { throw error }
+ catch (_: Exception) { PushDelivery.schedule(getApplication()) }
+}
+fun AppStore.notifications(enabled: Boolean) = action("notificationSettings") {
+ PushPreferences.enabled(getApplication(), enabled)
+ mutableState.update { it.copy(notifications = enabled) }
+ if (!enabled) NotificationDisplay.cancel(getApplication(), 1)
+ syncPush(); PushDelivery.schedule(getApplication())
+}
+fun AppStore.taskNotifications(enabled: Boolean) = action("taskSettings") {
+ PushPreferences.tasks(getApplication(), enabled)
+ mutableState.update { it.copy(tasks = enabled) }
+ if (!enabled) NotificationDisplay.cancel(getApplication(), 2)
+ syncPush(); PushDelivery.schedule(getApplication())
+}
+fun AppStore.openLink(uri: Uri) {
+ linkJob?.cancel()
+ linkJob = viewModelScope.launch {
+ val completed = withTimeoutOrNull(30_000) {
+ val activated = state.first { current -> !current.loading &&
+ (current.account.ready || !current.account.configured || current.account.error != null) &&
+ current.contextId == LocalStore.referenceId(current.account.userId ?: "local") }
+ val usage = uri.host == "usage"
+ val destination = try {
+ if (usage) { val target = UsageDestination.parse(uri.toString(), BuildConfig.URL_SCHEME); BotDestination(target.scope, target.computerId, "") }
+ else BotDestination.parse(uri.toString(), BuildConfig.URL_SCHEME)
+ }
+ catch (_: Exception) { mutableState.update { it.copy(error = "This notification has an invalid destination.") }; return@withTimeoutOrNull true }
+ if (destination.scope != activated.contextId) {
+ mutableState.update { it.copy(error = "Switch to the account used by this notification to open its bot.") }
+ return@withTimeoutOrNull true
+ }
+ if (destination.computerId != activated.computers.firstOrNull()?.id) {
+ mutableState.update { it.copy(error = "This notification's computer is no longer paired here.") }
+ return@withTimeoutOrNull true
+ }
+ val generation = activated.generation
+ if (usage) {
+ if (state.value.generation == generation) {
+ openBot(null)
+ mutableState.update { it.copy(error = null, navigationRequest = it.navigationRequest + 1, navigationUsage = true) }
+ }
+ return@withTimeoutOrNull true
+ }
+ if (activated.bots.none { it.id == destination.botId }) {
+ // A cold cache or a newly created bot needs an authoritative current roster.
+ // The query belongs to the activated runtime; account retirement joins it.
+ val request = contextScope.async {
+ val active = ready()
+ val bots = HostClient.bots(active)
+ withContext(Dispatchers.IO) { requireNotNull(database).receive(bots) }
+ refresh()
+ }
+ try { request.await() }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) {
+ if (state.value.generation == generation) mutableState.update { it.copy(error = "Reconnect to this computer and try opening the notification again.") }
+ return@withTimeoutOrNull true
+ } finally { request.cancel() }
+ }
+ if (state.value.generation != generation || state.value.contextId != destination.scope) return@withTimeoutOrNull true
+ if (state.value.bots.any { it.id == destination.botId && !it.deleted }) {
+ mutableState.update { it.copy(error = null, navigationRequest = it.navigationRequest + 1, navigationUsage = false) }
+ openBot(destination.botId)
+ }
+ else mutableState.update { it.copy(error = "This notification's bot is no longer available on the computer.") }
+ true
+ }
+ if (completed == null) mutableState.update { it.copy(error = "Couldn't open this notification yet. Reconnect and try again.") }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt
new file mode 100644
index 00000000..6d8d653b
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt
@@ -0,0 +1,69 @@
+package com.codync.android
+
+import java.util.UUID
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.json.*
+
+// A voice call with one bot: what you say is sent, its replies are read aloud.
+
+/** The call in progress and what it needs: its session, start time and which replies it has read. */
+internal data class VoiceBinding(val id: String, val botId: String, val generation: Int,
+ val startedAt: Long, val session: VoiceSession, val replies: VoiceReplyGate)
+fun AppStore.startVoice(botId: String, expectedGeneration: Int = state.value.generation) {
+ if (state.value.generation != expectedGeneration || state.value.loading || state.value.voice != null) return
+ if (!foreground || state.value.actualConnection !is LinkState.Ready || state.value.bots.none { it.id == botId && !it.deleted && it.kind != "group" }) {
+ mutableState.update { it.copy(error = "Open the connected bot's conversation to start voice chat.") }; return
+ }
+ val id = UUID.randomUUID().toString()
+ voiceGeneration = expectedGeneration
+ mutableState.update { it.copy(voice = VoiceCallViewState(id, botId, VoiceState(settings = VoicePreferences.load(getApplication())))) }
+ try { VoiceService.start(getApplication(), this, id, botId); PushDelivery.foreground = true }
+ catch (_: Exception) { finishVoice(id, "Couldn't start voice chat. Allow microphone access and wait for any previous call to finish.") }
+}
+internal fun AppStore.attachVoice(id: String, botId: String, audio: VoiceAudio): VoiceSession? {
+ val call = state.value.voice ?: return null
+ if (call.id != id || call.botId != botId || voiceGeneration != state.value.generation || state.value.loading || voiceBinding != null) return null
+ val generation = state.value.generation
+ val entries = state.value.entries
+ val head = maxOf(state.value.hello?.get("rev")?.jsonPrimitive?.longOrNull ?: 0, entries.maxOfOrNull(Entry::rev) ?: 0)
+ val session = VoiceSession(contextScope, audio, call.state.settings) { text ->
+ if (state.value.generation == generation && state.value.voice?.id == id && !state.value.loading) {
+ val send = PendingSend(UUID.randomUUID().toString(), botId, null, text, System.currentTimeMillis())
+ action("save:" + send.nonce) { savePending(send); deliver(send) }
+ }
+ }
+ voiceBinding = VoiceBinding(id, botId, generation, android.os.SystemClock.elapsedRealtime(), session, VoiceReplyGate(botId, head, entries))
+ contextScope.launch { session.state.takeWhile { it.phase != VoicePhase.Ended }.collect { status ->
+ mutableState.update { current -> if (current.voice?.id == id) current.copy(voice = current.voice.copy(state = status)) else current }
+ } }
+ connect()
+ return session
+}
+fun AppStore.endVoice(error: String? = null) {
+ val id = state.value.voice?.id ?: return
+ finishVoice(id, error); VoiceService.stop(getApplication(), id)
+}
+internal fun AppStore.finishVoice(id: String, error: String? = null) {
+ if (state.value.voice?.id != id) return
+ val call = voiceBinding?.takeIf { it.id == id }; voiceBinding = null; voiceGeneration = null
+ call?.session?.end()
+ mutableState.update { it.copy(voice = null, error = error ?: it.error) }
+ PushDelivery.foreground = foreground
+ contextScope.launch {
+ try {
+ call?.session?.awaitEnd()
+ if (call != null && state.value.generation == call.generation && channel?.state?.value is LinkState.Ready) {
+ val seconds = ((android.os.SystemClock.elapsedRealtime() - call.startedAt) / 1_000).coerceAtLeast(0)
+ withTimeoutOrNull(3_000) { hostQuery("logCall", buildJsonObject { put("botId", call.botId); put("seconds", seconds) }, 3_000, call.generation) }
+ }
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) { /* Duration is best effort; an uncertain log is never retried. */ }
+ finally { if (!transportRequired) { connectionJob?.cancel(); graceJob?.cancel(); channel?.close() } }
+ }
+}
+fun AppStore.muteVoice() { voiceBinding?.session?.let { it.mute(!it.state.value.muted) } }
+fun AppStore.interruptVoice() { voiceBinding?.session?.interrupt() }
+fun AppStore.resumeVoice() { voiceBinding?.session?.focus(true) }
+fun AppStore.voiceSettings(settings: VoiceSettings) { VoicePreferences.save(getApplication(), settings); voiceBinding?.session?.settings(settings) }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AttachmentFiles.kt b/apps/android/app/src/main/kotlin/com/codync/android/AttachmentFiles.kt
new file mode 100644
index 00000000..95f94396
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AttachmentFiles.kt
@@ -0,0 +1,118 @@
+package com.codync.android
+
+import android.content.Context
+import android.content.Intent
+import android.graphics.Bitmap
+import android.graphics.ImageDecoder
+import android.net.Uri
+import android.provider.OpenableColumns
+import androidx.core.content.FileProvider
+import com.codync.android.core.*
+import java.io.File
+import java.util.UUID
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ensureActive
+import kotlinx.coroutines.withContext
+import kotlin.coroutines.coroutineContext
+
+/** Copies provider streams into this account's private storage before it owns a send. */
+class AttachmentFiles(private val context: Context, private val directory: File) {
+ private val outgoing = File(directory, "outgoing").apply { mkdirs() }
+ private val downloads = File(directory, "attachments").apply { mkdirs() }
+
+ suspend fun import(uri: Uri): OutgoingFile = withContext(Dispatchers.IO) {
+ check(outgoing.mkdirs() || outgoing.isDirectory)
+ var name = "file"
+ context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { cursor ->
+ if (cursor.moveToFirst()) {
+ name = cursor.getString(0) ?: name
+ if (!cursor.isNull(1)) require(cursor.getLong(1) <= MAX_FILE_BYTES) { "Files must be 100 MiB or smaller." }
+ }
+ }
+ name = cleanName(name)
+ val used = outgoing.listFiles().orEmpty().sumOf { it.length() }
+ require(outgoing.listFiles().orEmpty().size < 200 && used < 512L * 1024 * 1024) {
+ "Attachment storage is full. Send or remove older files first."
+ }
+ val destination = File(outgoing, UUID.randomUUID().toString())
+ try {
+ val input = requireNotNull(context.contentResolver.openInputStream(uri)) { "Couldn't open the selected file." }
+ input.use { source -> destination.outputStream().use { target ->
+ val buffer = ByteArray(64 * 1024)
+ var total = 0L
+ while (true) {
+ coroutineContext.ensureActive()
+ val count = source.read(buffer)
+ if (count < 0) break
+ total += count
+ require(total <= MAX_FILE_BYTES) { "Files must be 100 MiB or smaller." }
+ require(used + total <= 512L * 1024 * 1024) { "Attachment storage is full. Send or remove older files first." }
+ target.write(buffer, 0, count)
+ }
+ target.fd.sync()
+ } }
+ if (name.substringAfterLast('.', "").lowercase() in listOf("heic", "heif", "bmp")) {
+ val bitmap = thumbnail(destination, 4096)
+ val converted = File(outgoing, UUID.randomUUID().toString())
+ try {
+ converted.outputStream().use { target -> check(bitmap.compress(Bitmap.CompressFormat.JPEG, 85, target)); target.fd.sync() }
+ destination.delete()
+ return@withContext OutgoingFile(converted.path, name.substringBeforeLast('.') + ".jpg", converted.length())
+ } catch (error: Exception) { converted.delete(); throw error }
+ }
+ OutgoingFile(destination.path, name, destination.length())
+ } catch (error: Throwable) { destination.delete(); throw error }
+ }
+
+ fun discard(file: OutgoingFile) {
+ val path = File(file.path)
+ if (path.parentFile?.canonicalFile == outgoing.canonicalFile) path.delete()
+ }
+ fun retainPending(files: List<OutgoingFile>) {
+ val paths = files.map { File(it.path).canonicalPath }.toSet()
+ outgoing.listFiles().orEmpty().filter { it.canonicalPath !in paths }.forEach { it.delete() }
+ }
+ fun cached(id: String): File {
+ check(downloads.mkdirs() || downloads.isDirectory)
+ val uuid = UUID.fromString(id).toString()
+ require(uuid == id.lowercase()) { "Invalid attachment ID." }
+ return File(downloads, uuid)
+ }
+ fun cache(id: String, source: OutgoingFile) {
+ File(source.path).copyTo(cached(id), overwrite = true)
+ trim()
+ }
+ fun trim() {
+ val files = downloads.listFiles().orEmpty().filter { it.isFile && !it.name.endsWith(".partial") }.sortedBy { it.lastModified() }
+ var bytes = files.sumOf { it.length() }
+ for (file in files) if (bytes > 512L * 1024 * 1024) { bytes -= file.length(); file.delete() }
+ }
+ suspend fun share(file: Attachment, source: File) {
+ val chooser = withContext(Dispatchers.IO) {
+ val root = File(context.cacheDir, "shared-attachments").apply { mkdirs() }
+ root.listFiles().orEmpty().filter { System.currentTimeMillis() - it.lastModified() > 24 * 60 * 60 * 1000 }.forEach { it.deleteRecursively() }
+ val folder = File(root, UUID.randomUUID().toString()).apply { mkdirs() }
+ val shared = source.copyTo(File(folder, cleanName(file.name)))
+ val uri = FileProvider.getUriForFile(context, context.packageName + ".files", shared)
+ val type = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(shared.extension.lowercase()) ?: "application/octet-stream"
+ val intent = Intent(Intent.ACTION_SEND).setType(type).putExtra(Intent.EXTRA_STREAM, uri)
+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ Intent.createChooser(intent, "Share " + file.name).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+ context.startActivity(chooser)
+ }
+
+ companion object {
+ fun cleanName(value: String): String {
+ val name = value.substringAfterLast('/').substringAfterLast('\\').trim().trimStart('.').filter { !it.isISOControl() }
+ val usable = name.ifBlank { "file" }
+ require(usable.toByteArray(Charsets.UTF_8).size <= 200) { "The file name is too long." }
+ return usable
+ }
+ fun thumbnail(file: File, maxPixels: Int): Bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(file)) { decoder, info, _ ->
+ decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
+ val longest = maxOf(info.size.width, info.size.height)
+ decoder.setTargetSampleSize(maxOf(1, (longest + maxPixels - 1) / maxPixels))
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AttachmentRow.kt b/apps/android/app/src/main/kotlin/com/codync/android/AttachmentRow.kt
new file mode 100644
index 00000000..ea02a112
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AttachmentRow.kt
@@ -0,0 +1,40 @@
+package com.codync.android
+
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.*
+import androidx.compose.material3.*
+import androidx.compose.runtime.*
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.ImageBitmap
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.*
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+
+@Composable fun AttachmentRow(botId: String, file: Attachment, state: AppState, store: AppStore) {
+ var full by remember(file.id) { mutableStateOf(false) }
+ var attempt by remember(file.id) { mutableIntStateOf(0) }
+ var image by remember(file.id) { mutableStateOf<ImageBitmap?>(null) }
+ var error by remember(file.id) { mutableStateOf<String?>(null) }
+ LaunchedEffect(file.id, full, attempt, state.actualConnection) {
+ if (file.isImage) try {
+ error = null
+ val source = store.attachment(botId, file)
+ image = withContext(Dispatchers.IO) { AttachmentFiles.thumbnail(source, if (full) 4096 else 720).asImageBitmap() }
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't load this image." }
+ }
+ Column {
+ Text(file.name + " · " + formatBytes(file.size))
+ image?.let { bitmap -> Image(bitmap, contentDescription = file.name,
+ modifier = Modifier.fillMaxWidth().heightIn(max = if (full) 800.dp else 260.dp).clickable { full = !full }) }
+ if (file.isImage && image == null && error == null) Text("Loading image…", style = MaterialTheme.typography.bodySmall)
+ error?.let { Text(it, style = MaterialTheme.typography.bodySmall); TextButton(onClick = { attempt++ }) { Text("Retry") } }
+ TextButton(enabled = "share:" + file.id !in state.busy, onClick = { store.shareAttachment(botId, file) }) {
+ Text(if ("share:" + file.id in state.busy) "Downloading…" else "Download / share")
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt
new file mode 100644
index 00000000..51c91694
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt
@@ -0,0 +1,29 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.*
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.semantics.clearAndSetSemantics
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Bot
+import com.codync.android.design.*
+
+@Composable internal fun BotAvatar(bot: Bot, bots: List<Bot>, size: Dp = 44.dp) {
+ Box(Modifier.size(size).clearAndSetSemantics { }) {
+ if (bot.kind == "group") GroupAvatar(bot.members.mapNotNull { id -> bots.firstOrNull { it.id == id } }
+ .map { AvatarFace(it.avatarShape, it.avatarColor, it.status) }, size)
+ else CharacterAvatar(bot.avatarShape, bot.avatarColor, size, bot.status)
+ if (bot.status == "needsInput") Box(Modifier.size(size * .36f).align(Alignment.BottomEnd)
+ .background(Color(0xFFF0A030), CircleShape), contentAlignment = Alignment.Center) {
+ Text("!", color = Color.White, style = MaterialTheme.typography.labelSmall)
+ } else if (bot.unread > 0) Box(Modifier.size(size * .28f).align(Alignment.BottomEnd)
+ .background(MaterialTheme.colorScheme.primary, CircleShape))
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotConversation.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotConversation.kt
new file mode 100644
index 00000000..ceee8d9f
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotConversation.kt
@@ -0,0 +1,135 @@
+package com.codync.android
+
+import android.content.ClipData
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.platform.ClipEntry
+import androidx.compose.ui.platform.LocalClipboard
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Bot
+import com.codync.android.core.BotConversationRow
+import com.codync.android.core.BotExchange
+import com.codync.android.core.BotExchangeGroup
+import com.codync.android.core.Entry
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.launch
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.put
+
+private fun AppState.authorName(id: String): String = bots.firstOrNull { it.id == id }?.name ?: "A deleted bot"
+
+/** The compact line a bot-to-bot exchange leaves in the chat; tapping it opens the conversation (iOS `BotMessageRow`). */
+@Composable internal fun BotMessageRow(group: BotExchangeGroup, state: AppState, open: () -> Unit) {
+ val peer = state.bots.firstOrNull { it.id == group.peerId }
+ val name = state.authorName(group.peerId)
+ val ink = if (group.failed) Palette.danger else Palette.secondary
+ Row(Modifier.fillMaxWidth().padding(top = 2.dp).plainButton(action = open)
+ .semantics(mergeDescendants = true) { contentDescription = "${group.title} $name${if (group.failed) ", failed" else ""}" }
+ .padding(vertical = 10.dp), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally)) {
+ if (group.failed) Symbol("exclamationmark.triangle.fill", size = 13.dp, tint = Palette.danger)
+ Text(group.title, style = Type.footnote, color = ink)
+ if (peer != null) BotAvatar(peer, state.bots, 18.dp)
+ Text(name, style = Type.footnote.semibold, color = if (group.failed) Palette.danger else Palette.text)
+ Symbol("chevron.right", size = 10.dp, tint = Palette.tertiary)
+ }
+}
+
+/** Read-only history between a bot and one peer, newest at the bottom (iOS `BotConversationView`). */
+@Composable internal fun BotConversationView(bot: Bot, peerId: String, state: AppState, store: AppStore) {
+ var fetched by remember(peerId) { mutableStateOf<List<Entry>?>(null) }
+ var error by remember(peerId) { mutableStateOf<String?>(null) }
+ LaunchedEffect(bot.id, peerId) {
+ try {
+ val result = store.hostCall("botConversation", buildJsonObject { put("botId", bot.id); put("peerId", peerId) }, 20_000)
+ fetched = result.jsonObject["entries"]?.jsonArray?.map { Entry.decode(it.jsonObject) }.orEmpty()
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { fetched = emptyList(); error = failure.message ?: "Couldn't load the conversation." }
+ }
+ val rows = BotConversationRow.build(BotExchange.conversation(fetched.orEmpty(), state.entries.filter { it.botId == bot.id }, peerId))
+ val list = rememberLazyListState()
+ LaunchedEffect(rows.size) { if (rows.isNotEmpty()) list.scrollToItem(rows.lastIndex) }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader({ PairTitle(bot.id, peerId, state) })
+ LazyColumn(Modifier.fillMaxSize(), state = list, contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 12.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ if (error != null || rows.isEmpty() && fetched != null) item("empty") {
+ Text(error ?: "No messages yet.", Modifier.fillMaxWidth().padding(top = 24.dp), style = Type.footnote,
+ color = if (error != null) Palette.danger else Palette.tertiary, textAlign = TextAlign.Center)
+ }
+ items(rows, key = { it.id }) { row ->
+ when (row) {
+ is BotConversationRow.Separator -> TimeSeparator(row.at)
+ is BotConversationRow.Message -> Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ if (row.showsAuthor) Box(Modifier.padding(top = 8.dp)) { AuthorLabel(row.author, state) }
+ ConversationBubble(row.text)
+ }
+ is BotConversationRow.Status -> when (val outcome = row.outcome) {
+ BotExchange.Outcome.Pending -> Text("Waiting for ${state.authorName(row.awaiting)}…", Modifier.padding(start = 12.dp),
+ style = Type.footnote, color = Palette.secondary)
+ is BotExchange.Outcome.Failed -> SelectionContainer {
+ Text(outcome.detail.ifEmpty { "Didn't complete." }, Modifier.padding(start = 12.dp), style = Type.footnote, color = Palette.danger)
+ }
+ BotExchange.Outcome.Done -> {}
+ }
+ }
+ }
+ }
+ }
+}
+
+/** "[avatar] A ⇄ [avatar] B": the two bots of a conversation, the chat's own bot first. */
+@Composable private fun PairTitle(botId: String, peerId: String, state: AppState) {
+ Row(Modifier.semantics(mergeDescendants = true) { contentDescription = "${state.authorName(botId)} and ${state.authorName(peerId)}" },
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ for ((index, id) in listOf(botId, peerId).withIndex()) {
+ if (index > 0) Symbol("arrow.left.arrow.right", size = 13.dp, tint = Palette.tertiary)
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ state.bots.firstOrNull { it.id == id }?.let { BotAvatar(it, state.bots, 22.dp) }
+ Text(state.authorName(id), style = Type.body.semibold, color = Palette.text, maxLines = 1)
+ }
+ }
+ }
+}
+
+/** A message of the conversation: the agent bubble, copyable. */
+@Composable private fun ConversationBubble(text: String) {
+ val clipboard = LocalClipboard.current
+ val scope = rememberCoroutineScope()
+ Box(Modifier.fillMaxWidth().padding(end = 40.dp), contentAlignment = Alignment.CenterStart) {
+ Box(Modifier.clip(RoundedRectangle(22.dp)).background(Palette.bubbleAgent).contextActions {
+ listOf(MenuItem("Copy", icon = "square.on.square") {
+ scope.launch { clipboard.setClipEntry(ClipEntry(ClipData.newPlainText("Message", text))) }
+ })
+ }.padding(horizontal = 16.dp, vertical = 10.dp)) { MarkdownText(text) }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotEditor.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotEditor.kt
new file mode 100644
index 00000000..ec5243ca
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotEditor.kt
@@ -0,0 +1,172 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.BotDraft
+import com.codync.android.core.LinkState
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.jsonPrimitive
+
+/** Create or edit a bot in a sheet, as iOS `BotEditorView`: the settings form plus Close and Save. */
+@Composable fun BotEditor(state: AppState, initial: BotDraft, store: AppStore) {
+ var draft by remember(initial.id) { mutableStateOf(initial) }
+ var folders by remember { mutableStateOf(false) }
+ val online = state.actualConnection is LinkState.Ready
+ val saving = "editor" in state.busy
+ val dismiss = LocalDismissModal.current
+ val isNew = draft.id == null
+ // A new bot starts on an installed agent we know, with every connector and skill on.
+ LaunchedEffect(state.hello, state.plugins) { if (isNew) draft = fillDefaults(draft, state) }
+ LaunchedEffect(online) { if (online) store.refreshPlugins() }
+ Column(Modifier.fillMaxSize()) {
+ ModalHeader(if (isNew) "New bot" else "Settings") {
+ if (saving) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
+ else IconButton(if (isNew) "Create" else "Save", "checkmark", enabled = draft.isValid && online) {
+ store.saveBot(draft) { dismiss() }
+ }
+ }
+ BotSettingsForm(state, store, draft, { draft = it }) { folders = true }
+ }
+ CodyncSheet(folders, { folders = false }) {
+ FolderPicker(draft.cwd.ifEmpty { state.hello?.get("home")?.jsonPrimitive?.contentOrNull }, online, store::listDirs) {
+ draft = draft.copy(cwd = it); folders = false
+ }
+ }
+}
+
+/** Picks an installed agent we know; connectors and skills start on once the computer has listed them. */
+private fun fillDefaults(draft: BotDraft, state: AppState): BotDraft {
+ val backends = backends(state)
+ var next = draft
+ if (backends.none { it.text("id") == draft.backend && it.available }) backends.firstOrNull { it.available && it.curated }?.text("id")
+ ?.let { next = next.copy(backend = it) }
+ val plugins = state.plugins
+ if (plugins != null && next.connectors == null && plugins.connectors.isNotEmpty()) next = next.copy(connectors = plugins.connectors.map { it.id })
+ if (plugins != null && next.skills.isEmpty() && plugins.skills.isNotEmpty() && draft.skills.isEmpty()) next = next.copy(skills = plugins.skills.map { it.id })
+ return next
+}
+
+private fun backends(state: AppState): List<JsonObject> = (state.hello?.get("backends") as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }
+private val JsonObject.available get() = this["available"]?.jsonPrimitive?.booleanOrNull == true
+private val JsonObject.curated get() = this["curated"]?.jsonPrimitive?.booleanOrNull != false
+
+/** Bot settings: a big avatar, then sections in the Settings style (`CardSection`). */
+@Composable private fun BotSettingsForm(state: AppState, store: AppStore, draft: BotDraft, change: (BotDraft) -> Unit, chooseFolder: () -> Unit) {
+ val online = state.actualConnection is LinkState.Ready
+ val screen = state.hello?.get("screen")?.takeUnless { it == JsonNull } as? JsonObject
+ Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(30.dp)) {
+ Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) {
+ Box(Modifier.clip(RoundedRectangle(24.dp)).background(Palette.bubbleAgent).padding(18.dp)) {
+ CharacterAvatar(draft.avatarShape, draft.avatarColor, 96.dp)
+ }
+ AvatarPicker(draft.avatarShape, draft.avatarColor, { change(draft.copy(avatarShape = it)) }, { change(draft.copy(avatarColor = it)) })
+ }
+ CardSection("Profile") {
+ // A new bot is named from its first conversations; rename it any time after.
+ if (draft.id != null) row { Field("Name") { FieldBox(draft.name, { change(draft.copy(name = it)) }, "Name") } }
+ row {
+ Field("Standing instructions", "Rules that always apply. Put task-specific requests in the chat instead.") {
+ FieldBox(draft.description, { change(draft.copy(description = it)) }, "e.g. Reviews PRs. Never pushes without asking.", 3, 8)
+ }
+ }
+ }
+ CardSection("Agent") {
+ row {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ ValueRow("Computer", state.computers.firstOrNull()?.name ?: "Your computer")
+ if (!online) Text(if (draft.id == null) "Connect this computer to create the bot." else "Reconnect to this computer to save settings.",
+ style = Type.caption, color = Palette.warning)
+ }
+ }
+ row {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ val agents = backends(state).map { info ->
+ val id = info.text("id").orEmpty()
+ id to ((info.text("name") ?: id) + if (!info.available) " (not installed)" else "")
+ } + ("custom" to "Custom command")
+ ValueRow("Agent") {
+ ChoicePicker(draft.backend, agents, { if (it != draft.backend) change(draft.copy(backend = it, model = null, modelOptions = emptyMap())) },
+ label = "Agent")
+ }
+ backends(state).firstOrNull { it.text("id") == draft.backend && !it.available }?.text("installHint")?.takeIf(String::isNotBlank)?.let {
+ Text(it, style = Type.caption, color = Palette.warning)
+ }
+ if (draft.backend == "custom") FieldBox(draft.command.orEmpty(), { change(draft.copy(command = it.ifEmpty { null })) },
+ "ACP command, e.g. my-agent --acp", style = Type.callout.monospaced, capitalize = false)
+ }
+ }
+ row {
+ val bot = state.bots.firstOrNull { it.id == draft.id }
+ AgentModelPicker(state, store::agentModels, draft.backend, draft.model, draft.modelOptions, draft.fastMode ?: false, bot,
+ { model, options -> change(draft.copy(model = model, modelOptions = options)) }, { change(draft.copy(fastMode = it)) })
+ }
+ row {
+ ValueRow("Workspace", detail = if (draft.cwd.isEmpty()) "This bot has its own space for files. It can work in other folders when you ask."
+ else "This project is the default starting folder. The bot can work elsewhere when you ask.") {
+ DropdownMenu({ listOf(
+ MenuItem("Personal workspace", selected = draft.cwd.isEmpty()) { change(draft.copy(cwd = "")) },
+ MenuItem("Choose project folder…", selected = draft.cwd.isNotEmpty(), action = chooseFolder),
+ ) }, label = "Workspace") {
+ Row(Modifier.outline().pill(androidx.compose.ui.graphics.Color.Transparent), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(if (draft.cwd.isEmpty()) "Personal" else draft.cwd.trimEnd('/').substringAfterLast('/').ifEmpty { "/" },
+ style = Type.body, color = Palette.text, maxLines = 1)
+ Symbol("chevron.down", size = 13.dp, tint = Palette.secondary)
+ }
+ }
+ }
+ }
+ row {
+ ValueRow("Permissions", detail = if (draft.permission == "auto")
+ "Tool requests are approved automatically. Your agent's own settings (like Claude Code's permission rules) still apply."
+ else "You'll get an approval card and a notification whenever the agent asks.") {
+ ChoicePicker(draft.permission, listOf("ask" to "Ask me", "auto" to "Approve automatically"), { change(draft.copy(permission = it)) },
+ label = "Permissions")
+ }
+ }
+ }
+ CardSection("Activity") {
+ row { SwitchRow("Notifications", "Get notified when this bot finishes or needs you", draft.notify != false, { change(draft.copy(notify = it)) }) }
+ if (screen != null) row {
+ SwitchRow("Use the computer", if (screen["enabled"]?.jsonPrimitive?.booleanOrNull == true)
+ "Let this bot see the screen and use the mouse and keyboard. You can watch and take over from your phone."
+ else "Let this bot see the screen and use the mouse and keyboard. On that computer, open Codync → Settings → Computer access to set up permissions first.",
+ draft.computer, { change(draft.copy(computer = it)) })
+ }
+ }
+ val plugins = state.plugins
+ PluginToggles("Connectors", "No connectors yet. Add GitHub, Linear, Notion and more from Extensions.",
+ plugins?.connectors.orEmpty().map { Triple(it.id, it.name, if (it.needsSignIn) "Sign-in needed" else it.command ?: it.url.orEmpty()) },
+ draft.connectors ?: plugins?.connectors.orEmpty().map { it.id }, { change(draft.copy(connectors = it)) })
+ PluginToggles("Skills", "No skills yet. Get some from Extensions, or write your own.",
+ plugins?.skills.orEmpty().map { Triple(it.id, it.name, it.description) }, draft.skills, { change(draft.copy(skills = it)) })
+ draft.id?.let { MemoryCard(it, store) }
+ state.error?.let { Text(it, style = Type.footnote, color = Palette.danger) }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt
new file mode 100644
index 00000000..22cd6225
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt
@@ -0,0 +1,295 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.asPaddingValues
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBars
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.zIndex
+import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.semantics.stateDescription
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import coil3.compose.AsyncImage
+import com.codync.android.core.Bot
+import com.codync.android.core.LinkState
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import kotlinx.serialization.json.putJsonArray
+
+/** The roster, as iOS `BotListView` draws it: every bot is a person you can message. */
+@Composable internal fun BotListView(state: AppState, store: AppStore, account: () -> Unit, manage: () -> Unit,
+ newBot: () -> Unit, newGroup: () -> Unit, edit: (Bot) -> Unit, bottomInset: androidx.compose.ui.unit.Dp) {
+ var confirmDelete by remember { mutableStateOf<Bot?>(null) }
+ val roster = roster(state.bots)
+ val reorder = remember { RosterReorder() }
+ reorder.roster = roster.map(Bot::id)
+ val online = state.actualConnection is LinkState.Ready
+ val top = WindowInsets.statusBars.asPaddingValues().calculateTopPadding()
+ GlassStage(Modifier.fillMaxSize().background(Palette.background), chrome = {
+ // iOS 26 scroll edge: content fades as it slides under the bar.
+ Box(Modifier.fillMaxWidth().height(top + 64.dp).background(Brush.verticalGradient(
+ 0f to Palette.background, 0.55f to Palette.background.copy(alpha = 0.85f), 1f to Color.Transparent)))
+ Row(Modifier.fillMaxWidth().statusBarsPadding().padding(top = 6.dp).padding(horizontal = 16.dp).height(44.dp),
+ verticalAlignment = Alignment.CenterVertically) {
+ AccountSwitcherButton(state, account)
+ Box(Modifier.weight(1f), contentAlignment = Alignment.Center) { ComputerFilterHeader(state, store, manage) }
+ NewMenuButton(enabled = state.computers.isNotEmpty(), groupEnabled = online, newBot, newGroup)
+ }
+ }) {
+ LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = top + 56.dp, bottom = bottomInset)) {
+ // A computer waiting for an update has its card instead; its bots may not be readable yet.
+ state.mismatch?.let { mismatch -> item("update") { UpdateNeededCard(state, mismatch, Modifier.padding(vertical = 8.dp)) } }
+ if (roster.isEmpty() && state.mismatch == null) item {
+ EmptyRoster(canCreate = state.computers.isNotEmpty(), hasComputer = state.computers.isNotEmpty(), create = newBot, showComputers = manage)
+ }
+ items(reorder.shown(roster), key = Bot::id) { bot ->
+ val lifted = reorder.dragged == bot.id
+ Box(Modifier.onSizeChanged { reorder.heights[bot.id] = it.height }
+ .then(if (lifted) Modifier.zIndex(1f).graphicsLayer { translationY = reorder.offset; scaleX = 1.02f; scaleY = 1.02f }
+ else Modifier.animateItem())) {
+ BotRowItem(bot, state, store, reorder.handle(bot.id) { store.reorder(it) }, edit = { edit(bot) }, delete = { confirmDelete = bot })
+ }
+ }
+ }
+ }
+ val deleting = confirmDelete
+ CodyncDialog("Delete ${deleting?.name ?: "bot"}?", deleting != null, { confirmDelete = null },
+ message = if (deleting?.kind == "group") "Its bots and their own chats stay." else "Files it changed on your computer stay as they are.") {
+ listOf(DialogAction(if (deleting?.kind == "group") "Delete group chat" else "Delete bot and its conversation", destructive = true) {
+ deleting?.let { store.deleteBot(it) {} }
+ })
+ }
+}
+
+/**
+ * Drag-to-reorder for the roster (iOS `List.onMove`): long-press a row, then move it. The order
+ * shown follows the finger until the host's synced order catches up.
+ */
+private class RosterReorder {
+ var roster: List<String> = emptyList()
+ var order by mutableStateOf<List<String>?>(null)
+ var dragged by mutableStateOf<String?>(null)
+ var offset by mutableFloatStateOf(0f)
+ val heights = mutableMapOf<String, Int>()
+ private val handles = mutableMapOf<String, ContextDrag>()
+
+ fun shown(bots: List<Bot>): List<Bot> {
+ val ids = order ?: return bots
+ // Dropped and synced: the host's order is the one to show again.
+ if (dragged == null && ids == roster) { order = null; return bots }
+ return ids.mapNotNull { id -> bots.firstOrNull { it.id == id } } + bots.filter { it.id !in ids }
+ }
+
+ fun handle(id: String, save: (List<String>) -> Unit): ContextDrag = handles.getOrPut(id) {
+ ContextDrag(start = { order = order ?: roster; dragged = id; offset = 0f }, move = { step -> offset += step; swap(id) }, end = {
+ val dropped = order
+ dragged = null; offset = 0f
+ if (dropped != null && dropped != roster) save(dropped) else order = null
+ })
+ }
+
+ /** Past half the neighbor's height, the row takes the neighbor's place. */
+ private fun swap(id: String) {
+ val list = order ?: return
+ val at = list.indexOf(id)
+ val next = if (offset > 0) at + 1 else at - 1
+ val height = list.getOrNull(next)?.let(heights::get) ?: return
+ if (kotlin.math.abs(offset) < height / 2f) return
+ order = list.toMutableList().apply { add(next, removeAt(at)) }
+ offset -= if (offset > 0) height else -height
+ }
+}
+
+/** Roster order: pinned first, then where the user dragged them, then most recent activity. */
+internal fun roster(bots: List<Bot>): List<Bot> = bots.filter { !it.deleted && !it.hidden }
+ .sortedWith(compareByDescending<Bot> { it.pinned }.thenBy { it.position }.thenByDescending { it.lastAt })
+
+@Composable private fun BotRowItem(bot: Bot, state: AppState, store: AppStore, drag: ContextDrag, edit: () -> Unit, delete: () -> Unit) {
+ Box(Modifier.fillMaxWidth().contextActions(onClick = { store.openBot(bot.id) }, reorder = drag, preview = {
+ Box(Modifier.padding(horizontal = 8.dp)) { BotRow(bot, state) }
+ }) {
+ listOf(
+ MenuItem(if (bot.pinned) "Unpin" else "Pin", icon = if (bot.pinned) "pin.slash" else "pin") {
+ store.command("updateBot", buildJsonObject { put("id", bot.id); put("pinned", !bot.pinned) }, "roster:" + bot.id)
+ },
+ if (bot.kind == "group") MenuItem("Edit group", icon = "person.2", action = edit)
+ else MenuItem("Edit profile", icon = "pencil", action = edit),
+ MenuItem("Mark as read", icon = "checkmark.message") {
+ store.command("markRead", buildJsonObject { put("botId", bot.id); put("all", true) }, "roster:" + bot.id)
+ },
+ MenuItem("Hide from list", icon = "eye.slash") {
+ store.command("updateBot", buildJsonObject { put("id", bot.id); put("hidden", true) }, "roster:" + bot.id)
+ },
+ MenuItem("Delete", icon = "trash", destructive = true, divider = true, action = delete),
+ )
+ }.semantics { contentDescription = bot.name }) {
+ BotRow(bot, state)
+ }
+}
+
+/** One bot: avatar with its status dot, name and day, then the live activity or last message. */
+@Composable internal fun BotRow(bot: Bot, state: AppState) {
+ Row(Modifier.fillMaxWidth().padding(vertical = 10.dp), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ BotAvatar(bot, state.bots, 46.dp)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ if (bot.pinned) Symbol("pin.fill", size = 13.dp, tint = Palette.tertiary)
+ Text(bot.name, Modifier.weight(1f, fill = false), style = Type.body.semibold, color = Palette.text, maxLines = 1,
+ overflow = TextOverflow.Ellipsis)
+ }
+ Spacer(Modifier.width(8.dp))
+ if (bot.lastAt > 0) Text(RelativeTime.day(bot.lastAt), style = Type.subheadline,
+ color = if (bot.unread > 0) Palette.text else Palette.tertiary, maxLines = 1)
+ }
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Box(Modifier.weight(1f)) { Preview(bot, state) }
+ if (bot.unread > 0) Box(Modifier.height(18.dp).widthIn(min = 18.dp).clip(Capsule()).background(Palette.accentFill)
+ .padding(horizontal = 6.dp).semantics { contentDescription = "${bot.unread} unread" }, contentAlignment = Alignment.Center) {
+ Text("${bot.unread}", style = Type.caption2.bold, color = Palette.onAccent)
+ }
+ }
+ }
+ }
+}
+
+/** Live activity while working, otherwise the last message (Grok Bot row behavior). */
+@Composable private fun Preview(bot: Bot, state: AppState) {
+ when {
+ bot.status == "needsInput" -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ ThinkingOrb(ThinkingOrbState.Listening, 16.dp, Palette.warning)
+ Text(bot.activity.ifEmpty { "Needs your approval" }, style = Type.subheadline, color = Palette.warning, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ bot.status == "working" -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ ThinkingOrb(size = 13.dp, color = Palette.secondary)
+ Text(bot.activity.ifEmpty { "Working…" }, style = Type.subheadline, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ bot.status == "error" -> Text(messagePreview(bot.lastMessage ?: "Something went wrong"), style = Type.subheadline, color = Palette.danger,
+ maxLines = 1, overflow = TextOverflow.Ellipsis)
+ else -> Text(messagePreview(bot.lastMessage ?: if (bot.kind == "group") "${bot.members.size} bots"
+ else "${backendName(state, bot.backend)} · ${if (bot.managedWorkspace) "Personal workspace" else bot.cwd.trimEnd('/').substringAfterLast('/')}"),
+ style = Type.subheadline, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+}
+
+/** The first non-empty line, without Markdown markers (CodyncKit `MessagePreview`). */
+internal fun messagePreview(text: String): String {
+ val first = text.lines().map(String::trim).firstOrNull(String::isNotEmpty).orEmpty()
+ return first.dropWhile { it in "#>-* " }.replace("**", "").replace("`", "")
+}
+
+@Composable private fun EmptyRoster(canCreate: Boolean, hasComputer: Boolean, create: () -> Unit, showComputers: () -> Unit) {
+ Column(Modifier.fillMaxWidth().padding(vertical = 40.dp), horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(14.dp)) {
+ CharacterAvatar("cloud", "green", 72.dp)
+ Text("No bots yet", style = Type.title3.semibold, color = Palette.text)
+ Text(if (hasComputer) "Create a bot for each kind of work — a reviewer, a fixer, a docs writer — and point it at a project."
+ else "Ask one of your account's computers for access, or pair one with its code.",
+ style = Type.subheadline, color = Palette.secondary, textAlign = TextAlign.Center)
+ if (canCreate) PrimaryButton("Create your first bot", action = create)
+ else if (!hasComputer) PrimaryButton("Computers", action = showComputers)
+ }
+}
+
+/** The account capsule: who's signed in, opening the account sheet. */
+@Composable internal fun AccountSwitcherButton(state: AppState, open: () -> Unit) {
+ val (source, pressed) = rememberPress()
+ val email = state.account.accounts.firstOrNull { it.userId == state.account.userId }?.email
+ Row(Modifier.height(44.dp).glass(Capsule(), pressed = pressed)
+ .clickable(source, null, role = Role.Button, onClick = open)
+ .semantics { contentDescription = "Switch account"; stateDescription = email ?: "Local pairing" }
+ .padding(start = 7.dp, end = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ AccountAvatar(state, 30.dp)
+ Symbol("chevron.down", size = 21.dp, tint = Palette.secondary)
+ }
+}
+
+/** The quiet connection summary, with reconnect and the computers on demand. */
+@Composable private fun ComputerFilterHeader(state: AppState, store: AppStore, manage: () -> Unit) {
+ val summary = connectionSummary(state)
+ DropdownMenu({
+ listOf(
+ MenuItem("All computers", icon = "checkmark"),
+ *state.computers.map { MenuItem("${it.name} · ${connectionLabel(state)}", icon = "checkmark") }.toTypedArray(),
+ MenuItem("Reconnect", icon = "arrow.clockwise", divider = true, enabled = state.computers.isNotEmpty()) { store.connect() },
+ MenuItem("Manage computers", icon = "desktopcomputer", action = manage),
+ )
+ }, label = "Computers, $summary. Filter conversations") {
+ Row(Modifier.padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(summary, style = Type.system(12f).medium, color = Palette.secondary, maxLines = 1)
+ Symbol("chevron.down", size = 15.dp, tint = Palette.secondary)
+ }
+ }
+}
+
+/** "2 connected", "Connecting…", "Offline": what the roster says about its computers. */
+internal fun connectionSummary(state: AppState): String = when {
+ state.computers.isEmpty() -> "No computers"
+ state.connection is LinkState.Ready -> "${state.computers.size} connected"
+ state.connection is LinkState.Connecting -> "Connecting…"
+ else -> "Offline"
+}
+
+internal fun connectionLabel(state: AppState): String = when (state.connection) {
+ is LinkState.Ready -> "Connected"
+ is LinkState.Connecting -> "Connecting…"
+ else -> "Offline"
+}
+
+@Composable private fun NewMenuButton(enabled: Boolean, groupEnabled: Boolean, newBot: () -> Unit, newGroup: () -> Unit) {
+ DropdownMenu({
+ listOf(MenuItem("New bot", icon = "plus", action = newBot),
+ MenuItem("New group chat", icon = "person.2", enabled = groupEnabled, action = newGroup))
+ }, Modifier.size(44.dp).glass(Capsule()), enabled = enabled, label = "New") {
+ Symbol("plus", size = 30.dp, tint = Palette.text.copy(alpha = if (enabled) 1f else 0.35f))
+ }
+}
+
+internal fun backendName(state: AppState, id: String): String =
+ state.hello?.get("backends")?.let { it as? kotlinx.serialization.json.JsonArray }
+ ?.firstOrNull { (it as? kotlinx.serialization.json.JsonObject)?.get("id") == JsonPrimitive(id) }
+ ?.let { ((it as kotlinx.serialization.json.JsonObject)["name"] as? JsonPrimitive)?.content }
+ ?: when (id) { "claude" -> "Claude Code"; "codex" -> "Codex"; "opencode" -> "OpenCode"; "grok" -> "Grok Build"; "gemini" -> "Gemini CLI"; else -> "Custom agent" }
+
+/** Saves a dragged roster order (the host syncs it to every device). */
+internal fun AppStore.reorder(ids: List<String>) =
+ command("reorderBots", buildJsonObject { putJsonArray("ids") { ids.forEach { add(JsonPrimitive(it)) } } }, "reorder")
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
new file mode 100644
index 00000000..3754f40a
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt
@@ -0,0 +1,374 @@
+package com.codync.android
+
+import android.content.ClipData
+import android.content.ClipboardManager
+import androidx.compose.animation.animateContentSize
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableLongStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.rotate
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.*
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.coroutines.delay
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.decodeFromJsonElement
+import kotlinx.serialization.json.intOrNull
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.longOrNull
+
+/** One row of a conversation, as iOS `ChatItem` builds them. */
+internal sealed interface ChatItem {
+ val id: String
+ data class Separator(override val id: String, val at: Long) : ChatItem
+ data class Message(override val id: String, val entry: Entry, val groupStart: Boolean) : ChatItem
+ data class Pending(override val id: String, val send: PendingSend, val groupStart: Boolean) : ChatItem
+ /** Consecutive bot-to-bot exchanges with one peer, as one line. */
+ data class Exchanges(override val id: String, val group: BotExchangeGroup) : ChatItem
+}
+
+/** Chat-visible entries plus time separators (gaps over an hour) and author grouping. */
+internal fun chatItems(entries: List<Entry>, pending: List<PendingSend>): List<ChatItem> {
+ val out = mutableListOf<ChatItem>()
+ var last: Long? = null
+ var author: String? = null
+ // Exchanges with the same peer in a row collapse into one line; anything shown in between ends the run.
+ val units = mutableListOf<Pair<Long, Any>>()
+ var run = mutableListOf<BotExchange>()
+ fun flush() { if (run.isNotEmpty()) { units += run.first().createdAt to BotExchangeGroup(run); run = mutableListOf() } }
+ for (entry in entries) {
+ val exchange = BotExchange.of(entry)
+ if (exchange == null) { flush(); units += entry.createdAt to entry; continue }
+ if (run.isNotEmpty() && run.last().peerId != exchange.peerId) flush()
+ run += exchange
+ }
+ flush()
+ val slots = units + pending.filter { send -> entries.none { it.clientNonce == send.nonce } }.map { it.createdAt to it }
+ for ((at, slot) in slots.sortedBy { it.first }) {
+ val id = when (slot) { is Entry -> slot.clientNonce?.takeIf { slot.kind == "user" && it.isNotEmpty() }?.let { "user-$it" } ?: slot.id
+ is BotExchangeGroup -> "x-" + slot.id
+ else -> "user-" + (slot as PendingSend).nonce }
+ if (last == null || at - last > 3_600_000) { out += ChatItem.Separator("sep-$id", at); author = null }
+ last = at
+ when (slot) {
+ is Entry -> {
+ val who = when (slot.kind) { "user" -> "user"; "agent" -> "agent:" + slot.data.text("author").orEmpty(); else -> slot.kind }
+ out += ChatItem.Message(id, slot, who != author)
+ author = if (who == "user" || slot.kind == "agent") who else null
+ }
+ is PendingSend -> { out += ChatItem.Pending(id, slot, author != "user"); author = "user" }
+ is BotExchangeGroup -> { out += ChatItem.Exchanges(id, slot); author = null }
+ }
+ }
+ return out
+}
+
+/** A chat's time separator: Today 3:27 AM. */
+@Composable internal fun TimeSeparator(at: Long) {
+ Text(RelativeTime.separator(at), Modifier.fillMaxWidth().padding(top = 18.dp, bottom = 6.dp), style = Type.footnote,
+ color = Palette.tertiary, textAlign = TextAlign.Center)
+}
+
+/** One chat-visible entry, with what can be done to it. `reply` opens its thread (main chat only). */
+@Composable internal fun ChatRow(entry: Entry, groupStart: Boolean, chat: Bot?, state: AppState, store: AppStore,
+ openTrace: () -> Unit, reply: (() -> Unit)?, connect: ConnectionRequestActions) {
+ val group = chat?.kind == "group"
+ when (entry.kind) {
+ "user" -> Column(Modifier.fillMaxWidth().padding(top = if (groupStart) 12.dp else 4.dp).animateContentSize(Motion.layoutSize),
+ horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ UserBubble(entry, state, store, reply)
+ ReactionsRow(entry, store)
+ ThreadChip(entry, state, reply)
+ }
+ "agent" -> Column(Modifier.fillMaxWidth().padding(top = if (groupStart) 12.dp else 4.dp).animateContentSize(Motion.layoutSize),
+ verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ if (group && groupStart) AuthorLabel(entry.data.text("author"), state)
+ AgentBubble(entry, state, store, openTrace, reply)
+ Column(Modifier.padding(start = if (group) 34.dp else 0.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ ReactionsRow(entry, store)
+ ThreadChip(entry, state, reply)
+ }
+ }
+ "permission" -> Column(Modifier.padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ if (group) AuthorLabel(entry.data.text("author"), state)
+ PermissionCard(entry, state.computers.firstOrNull()?.name.orEmpty(), answering = "permission:" + entry.id in state.busy) {
+ store.respond(entry, it)
+ }
+ }
+ else -> if (entry.data["connectionRequest"] is JsonObject) Box(Modifier.padding(top = 12.dp)) {
+ ConnectionRequestCard(entry, state, store, connect.openApp, connect.install)
+ } else Box(Modifier.padding(top = 10.dp)) { NoticeRow(entry) }
+ }
+}
+
+/** What a connection request in the chat opens. */
+internal class ConnectionRequestActions(val openApp: (String, ComposioApp) -> Unit, val install: (String, MarketConnector) -> Unit)
+
+/** Who wrote a message in a group: their avatar and name in their color. */
+@Composable internal fun AuthorLabel(botId: String?, state: AppState) {
+ val bot = state.bots.firstOrNull { it.id == botId }
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (bot != null) CharacterAvatar(bot.avatarShape, bot.avatarColor, 26.dp)
+ Text(bot?.name ?: "A deleted bot", style = Type.subheadline.medium, color = bot?.let { AvatarPalette.tint(it.avatarColor) } ?: Palette.secondary)
+ }
+}
+
+/** The menu a message opens on long press: copy, reply in its thread, what the agent did. */
+private fun messageMenu(context: android.content.Context, entry: Entry, reply: (() -> Unit)?, trace: (() -> Unit)?) = buildList {
+ add(MenuItem("Copy", icon = "square.on.square") {
+ context.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("Message", entry.text))
+ })
+ if (reply != null) add(MenuItem("Reply in thread", icon = "arrowshape.turn.up.left", action = reply))
+ if (trace != null) add(MenuItem("Show what it did", icon = "list.bullet", action = trace))
+}
+
+internal val quickReactions = listOf("👍", "❤️", "😂", "🎉", "👀", "🙏")
+
+private fun reactionPick(entry: Entry, store: AppStore) = ReactionPick(quickReactions, entry.reactions) { emoji ->
+ store.command("react", body("entryId" to entry.id, "emoji" to emoji), "react:" + entry.id)
+}
+
+internal val Entry.reactions: List<String> get() = (data["reactions"] as? JsonArray)?.map { it.jsonPrimitive.content }.orEmpty()
+
+@Composable private fun UserBubble(entry: Entry, state: AppState, store: AppStore, reply: (() -> Unit)?) {
+ val context = LocalContext.current
+ val attachments = entry.data["attachments"]?.jsonArray?.map { WireJson.decodeFromJsonElement<Attachment>(it) }.orEmpty()
+ Column(Modifier.fillMaxWidth().padding(start = 56.dp), horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (file in attachments) AttachmentRow(entry.botId, file, state, store)
+ if (entry.text.isNotEmpty()) Box(Modifier.clip(RoundedRectangle(18.dp)).background(Palette.bubbleUser)
+ .contextActions(reactions = reactionPick(entry, store), preview = { UserText(entry.text) }) {
+ messageMenu(context, entry, reply, null)
+ }) { UserText(entry.text) }
+ SendStatusLine(entry.status, state.bots.firstOrNull { it.id == entry.botId }?.status == "working")
+ }
+}
+
+@Composable private fun UserText(text: String) {
+ Text(text, Modifier.background(Palette.bubbleUser).padding(horizontal = 16.dp, vertical = 10.dp), style = Type.body, color = Palette.text)
+}
+
+@Composable private fun SendStatusLine(status: String?, botWorking: Boolean) {
+ val text = when (status) {
+ "sending" -> "Sending…"
+ "queued" -> if (botWorking) "Queued until this response finishes" else "Queued"
+ "cancelled" -> "Not sent — stopped"
+ "delivering" -> "Delivered to the computer"
+ else -> null
+ }
+ if (text != null) Text(text, style = Type.caption2, color = Palette.tertiary)
+}
+
+/** A message this phone is still delivering: the same bubble, with how far it got. */
+@Composable internal fun PendingBubble(send: PendingSend, groupStart: Boolean, state: AppState, store: AppStore) {
+ Column(Modifier.fillMaxWidth().padding(top = if (groupStart) 12.dp else 4.dp).padding(start = 56.dp),
+ horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (file in send.files) Text(file.name + " · " + formatBytes(file.size), Modifier.clip(RoundedRectangle(14.dp))
+ .background(Palette.surface).padding(horizontal = 12.dp, vertical = 8.dp), style = Type.footnote, color = Palette.text)
+ if (send.text.isNotEmpty()) Box(Modifier.clip(RoundedRectangle(18.dp))) { UserText(send.text) }
+ when (send.status) {
+ SendStatus.Sending -> Text(state.uploadProgress[send.nonce]?.let { "Uploading files · $it%" } ?: "Sending…",
+ style = Type.caption2, color = Palette.tertiary)
+ SendStatus.Delivering -> Text("Delivered to the computer", style = Type.caption2, color = Palette.tertiary)
+ SendStatus.Waiting -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text("Waiting for the computer to come online", style = Type.caption2, color = Palette.tertiary)
+ Box(Modifier.clickable(role = Role.Button) { store.cancelQueued(send) }.semantics { contentDescription = "Don't send" }) {
+ Symbol("xmark.circle", size = 14.dp, tint = Palette.tertiary)
+ }
+ }
+ SendStatus.Failed -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text(send.error ?: "Failed to send", style = Type.caption2.bold, color = Palette.danger)
+ Box(Modifier.clickable(role = Role.Button) { store.retry(send) }.semantics { contentDescription = "Resend" }) {
+ Symbol("arrow.clockwise", size = 14.dp, tint = Palette.text)
+ }
+ Box(Modifier.clickable(role = Role.Button) { store.discard(send) }.semantics { contentDescription = "Delete" }) {
+ Symbol("trash", size = 14.dp, tint = Palette.text)
+ }
+ }
+ }
+ }
+}
+
+@Composable private fun AgentBubble(entry: Entry, state: AppState, store: AppStore, openTrace: () -> Unit, reply: (() -> Unit)?) {
+ val context = LocalContext.current
+ val attachments = entry.data["attachments"]?.jsonArray?.map { WireJson.decodeFromJsonElement<Attachment>(it) }.orEmpty()
+ Column(Modifier.fillMaxWidth().padding(end = 40.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (file in attachments) AttachmentRow(entry.botId, file, state, store)
+ if (entry.text.isNotEmpty()) Box(Modifier.clip(RoundedRectangle(18.dp)).background(Palette.bubbleAgent)
+ .contextActions(reactions = reactionPick(entry, store), preview = { AgentText(entry.text) }) {
+ messageMenu(context, entry, reply, openTrace)
+ }) { AgentText(entry.text) }
+ }
+}
+
+@Composable private fun AgentText(text: String) {
+ Box(Modifier.background(Palette.bubbleAgent).padding(horizontal = 16.dp, vertical = 10.dp)) { MarkdownText(text, selectable = false) }
+}
+
+/** Under a message with a thread (Slack's): how many replied, how recently. */
+@Composable private fun ThreadChip(entry: Entry, state: AppState, open: (() -> Unit)?) {
+ val summary = entry.data["thread"] as? JsonObject ?: return
+ val count = summary["count"]?.jsonPrimitive?.intOrNull ?: 0
+ if (count == 0 || open == null) return
+ val unread = summary["unread"]?.jsonPrimitive?.intOrNull ?: 0
+ val lastAt = summary["lastAt"]?.jsonPrimitive?.longOrNull ?: 0
+ val authors = (summary["authors"] as? JsonArray)?.mapNotNull { id -> state.bots.firstOrNull { it.id == id.jsonPrimitive.content } }.orEmpty()
+ val (source, pressed) = rememberPress()
+ Row(Modifier.pressScale(pressed).clip(Capsule()).background(Palette.surface)
+ .clickable(source, null, role = Role.Button, onClick = open)
+ .semantics { contentDescription = "View thread, $count ${if (count == 1) "reply" else "replies"}" + if (unread > 0) ", $unread new" else "" }
+ .padding(horizontal = 10.dp, vertical = 5.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Row(horizontalArrangement = Arrangement.spacedBy((-6).dp)) {
+ for (bot in authors.take(3)) CharacterAvatar(bot.avatarShape, bot.avatarColor, 18.dp)
+ }
+ Text(if (count == 1) "1 reply" else "$count replies", style = Type.footnote.semibold, color = Palette.accent)
+ if (unread > 0) Text("$unread new", style = Type.footnote.semibold, color = Palette.text)
+ else if (lastAt > 0) Text(RelativeTime.day(lastAt), style = Type.footnote, color = Palette.tertiary)
+ Symbol("chevron.right", size = 12.dp, tint = Palette.tertiary)
+ }
+}
+
+/** The user's reactions under a message; tapping one takes it back. */
+@Composable private fun ReactionsRow(entry: Entry, store: AppStore) {
+ val reactions = entry.reactions
+ if (reactions.isEmpty()) return
+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (emoji in reactions) {
+ val (source, pressed) = rememberPress()
+ Text(emoji, Modifier.pressScale(pressed).clip(Capsule()).background(Palette.surface)
+ .clickable(source, null, role = Role.Button) { store.command("react", body("entryId" to entry.id, "emoji" to emoji), "react:" + entry.id) }
+ .semantics { contentDescription = "Remove reaction $emoji" }
+ .padding(horizontal = 8.dp, vertical = 3.dp), style = Type.system(15f))
+ }
+ }
+}
+
+@Composable private fun NoticeRow(entry: Entry) {
+ val text = entry.text
+ val seconds = entry.data["callSeconds"]?.jsonPrimitive?.longOrNull
+ when {
+ seconds != null -> Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {
+ Symbol("waveform", size = 15.dp, tint = Palette.secondary)
+ Spacer(Modifier.width(6.dp))
+ Text("$text · %02d:%02d".format(seconds / 60, seconds % 60), style = Type.footnote.monospacedDigit, color = Palette.secondary)
+ }
+ entry.data.text("style") == "divider" -> Row(Modifier.fillMaxWidth().padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Box(Modifier.weight(1f).height(1.dp).background(Palette.border))
+ Text(text, Modifier.widthIn(max = 260.dp), style = Type.caption2, color = Palette.tertiary, textAlign = TextAlign.Center)
+ Box(Modifier.weight(1f).height(1.dp).background(Palette.border))
+ }
+ entry.data.text("style") == "error" -> Row(Modifier.fillMaxWidth().clip(RoundedRectangle(12.dp))
+ .background(Palette.danger.copy(alpha = 0.12f)).padding(12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol("exclamationmark.triangle.fill", size = 16.dp, tint = Palette.danger)
+ SelectionContainer { Text(text, style = Type.footnote, color = Palette.text) }
+ }
+ else -> Text(text, Modifier.fillMaxWidth(), style = Type.footnote, color = Palette.secondary, textAlign = TextAlign.Center)
+ }
+}
+
+/**
+ * The bot's live activity line: a turning orb, what it's doing and for how long. Tapping it
+ * unfolds what the bot is thinking right now.
+ */
+@Composable internal fun WorkingIndicator(bot: Bot, thinking: String?) {
+ var expanded by remember { mutableStateOf(false) }
+ val needs = bot.status == "needsInput"
+ val turn by animateFloatAsState(if (expanded) 180f else 0f, Motion.layout(), label = "Thinking")
+ Row(Modifier.fillMaxWidth().padding(top = 6.dp, end = 40.dp)) {
+ Column(Modifier.clip(RoundedRectangle(18.dp)).background(Palette.bubbleAgent)
+ .clickable(enabled = thinking != null, role = Role.Button) { expanded = !expanded }
+ .animateContentSize(Motion.layoutSize).padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ ThinkingOrb(if (needs) ThinkingOrbState.Listening else ThinkingOrbState.Working, 16.dp, if (needs) Palette.warning else Palette.secondary)
+ Text(bot.activity.ifEmpty { "Working…" }, Modifier.weight(1f, fill = false), style = Type.subheadline,
+ color = if (needs) Palette.warning else Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ bot.startedAt?.let { Elapsed(it) }
+ if (thinking != null) Symbol("chevron.down", Modifier.rotate(turn), size = 12.dp, tint = Palette.tertiary)
+ }
+ if (expanded && thinking != null) Box(Modifier.heightIn(max = 180.dp).verticalScroll(rememberScrollState(Int.MAX_VALUE))) {
+ SelectionContainer { Text(thinking, style = Type.footnote, color = Palette.secondary) }
+ }
+ }
+ }
+}
+
+/** `Text(date, style: .timer)`: the time since `startedAt`, every second. */
+@Composable private fun Elapsed(startedAt: Long) {
+ var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
+ LaunchedEffect(startedAt) { while (true) { now = System.currentTimeMillis(); delay(1000) } }
+ val seconds = maxOf(0, (now - startedAt) / 1000)
+ Text(if (seconds >= 3600) "%d:%02d:%02d".format(seconds / 3600, seconds / 60 % 60, seconds % 60) else "%d:%02d".format(seconds / 60, seconds % 60),
+ style = Type.footnote.monospacedDigit, color = Palette.tertiary)
+}
+
+/** The latest thinking of the turn running in a chat (`thread` null) or thread. */
+internal fun currentThinking(entries: List<Entry>, botId: String, thread: String?): String? {
+ for (e in entries.asReversed()) {
+ if (e.botId != botId || e.threadId != thread) continue
+ if (e.kind == "user" || (e.kind == "agent" && e.data["final"]?.jsonPrimitive?.booleanOrNull == true)) return null
+ if (e.kind == "thought" && e.text.isNotEmpty()) return e.text
+ }
+ return null
+}
+
+/** The start of an empty chat: who the bot is and how it works. */
+@Composable internal fun IntroCard(bot: Bot, state: AppState) {
+ val members = bot.members.mapNotNull { id -> state.bots.firstOrNull { it.id == id } }
+ Column(Modifier.fillMaxWidth().padding(horizontal = 24.dp).padding(top = 40.dp), horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ BotAvatar(bot, state.bots, 72.dp)
+ Text(bot.name, style = Type.title2.semibold, color = Palette.text)
+ val lines = if (bot.kind == "group") listOfNotNull(
+ members.joinToString(" · ") { it.name }.takeIf { bot.name != members.joinToString(", ") { it.name } },
+ bot.description.ifEmpty { null }) else listOfNotNull(
+ if (bot.managedWorkspace) "${backendName(state, bot.backend)} · Personal workspace" else "${backendName(state, bot.backend)} in ${bot.cwd}",
+ bot.description.ifEmpty { null })
+ for (line in lines) Text(line, style = Type.subheadline, color = Palette.secondary, textAlign = TextAlign.Center)
+ Text(if (bot.kind == "group") "Everyone answers in turn. @mention a bot to ask just that one."
+ else "Tell it what you need. You'll get a notification when it's done or needs you.",
+ Modifier.padding(top = 4.dp), style = Type.subheadline, color = Palette.secondary, textAlign = TextAlign.Center)
+ }
+}
+
+internal fun JsonObject.text(key: String): String? = this[key]?.jsonPrimitive?.contentOrNull
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt
new file mode 100644
index 00000000..1979a156
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt
@@ -0,0 +1,296 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.slideInVertically
+import androidx.compose.animation.slideOutVertically
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.asPaddingValues
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.ime
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.navigationBars
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBars
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.interaction.DragInteraction
+import androidx.compose.foundation.lazy.LazyListState
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.key
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.snapshotFlow
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
+import androidx.compose.ui.input.nestedscroll.NestedScrollSource
+import androidx.compose.ui.input.nestedscroll.nestedScroll
+import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.*
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+
+/**
+ * One endless conversation with a bot or a group, as iOS `ThreadView`: only deliberate messages
+ * show; tool calls and thinking live in "Full conversation". A thread opens over it as a sheet.
+ */
+@Composable fun ChatScreen(state: AppState, store: AppStore, edit: (Bot) -> Unit) {
+ val bot = state.bots.firstOrNull { it.id == state.selectedBot } ?: return
+ key(state.contextId, state.generation, bot.id) { ThreadView(bot, state, store, edit) }
+}
+
+@Composable private fun ThreadView(bot: Bot, state: AppState, store: AppStore, edit: (Bot) -> Unit) {
+ val context = LocalContext.current
+ var confirmNewSession by remember { mutableStateOf(false) }
+ var confirmDelete by remember { mutableStateOf(false) }
+ var routines by remember { mutableStateOf(false) }
+ // The bot whose conversation with this one is open.
+ var peer by remember(bot.id) { mutableStateOf<String?>(null) }
+ var micDenied by remember { mutableStateOf(false) }
+ var setupEntry by rememberSaveable { mutableStateOf<String?>(null) }
+ var app by remember { mutableStateOf<ComposioApp?>(null) }
+ var connector by remember { mutableStateOf<MarketConnector?>(null) }
+ val connect = ConnectionRequestActions({ id, item -> setupEntry = id; app = item }, { id, item -> setupEntry = id; connector = item })
+ val startCall = rememberStartVoice(bot.id, state, store) { micDenied = true }
+ val top = WindowInsets.statusBars.asPaddingValues().calculateTopPadding()
+ var composerHeight by remember { mutableIntStateOf(0) }
+ val density = LocalDensity.current
+ // The main chat ignores an open thread: it stays put underneath.
+ val chatState = state.copy(thread = null, trace = false)
+ GlassStage(Modifier.fillMaxSize().background(Palette.background), chrome = {
+ Box(Modifier.fillMaxWidth().height(top + 64.dp).background(Brush.verticalGradient(
+ 0f to Palette.background, 0.55f to Palette.background.copy(alpha = 0.85f), 1f to Color.Transparent)))
+ ThreadHeader(bot, state, store, edit, { store.showTrace(true) }, { routines = true }, { confirmNewSession = true }, { confirmDelete = true })
+ // The call floats over the chat under the header, as on iOS; the chat stays readable and usable.
+ AnimatedVisibility(state.voice != null, Modifier.padding(top = top + 54.dp),
+ enter = fadeIn(Motion.fade()) + slideInVertically(Motion.layoutOffset) { -it }, exit = fadeOut(Motion.fade()) + slideOutVertically(Motion.layoutOffset) { -it }) {
+ state.voice?.let { CallBar(it, state, store) }
+ }
+ // Measured with the keyboard and navigation bar under it, so the last message clears them too.
+ Column(Modifier.align(Alignment.BottomCenter).fillMaxWidth().onSizeChanged { composerHeight = it.height }
+ .imePadding().navigationBarsPadding()) {
+ // Nothing sent now could be read on the other side.
+ val mismatch = state.mismatch
+ if (mismatch != null) UpdateNeededCard(state, mismatch, Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp))
+ else MessageComposer(bot, null, chatState, store, onCall = if (state.voice == null && state.actualConnection is LinkState.Ready) startCall else null)
+ }
+ }) {
+ Transcript(bot, chatState, store, connect, PaddingValues(start = 16.dp, end = 16.dp, top = top + 60.dp,
+ bottom = with(density) { composerHeight.toDp() } + 8.dp)) { peer = it }
+ }
+ CodyncDialog("Start a new session?", confirmNewSession, { confirmNewSession = false },
+ message = "The conversation stays here, but the agent starts with a fresh context.") {
+ listOf(DialogAction("New session") { store.command("newSession", body("botId" to bot.id)) })
+ }
+ CodyncDialog("Delete ${bot.name}?", confirmDelete, { confirmDelete = false },
+ message = if (bot.kind == "group") "Its bots and their own chats stay." else "Files it changed on your computer stay as they are.") {
+ listOf(DialogAction(if (bot.kind == "group") "Delete group chat" else "Delete bot and its conversation", destructive = true) {
+ store.deleteBot(bot) { store.openBot(null) }
+ })
+ }
+ CodyncDialog("Microphone access is off", micDenied, { micDenied = false },
+ message = "Allow the microphone in Android settings to talk to your bot.") {
+ listOf(DialogAction("Open settings") { openAppSettings(context) })
+ }
+ // A thread over the chat, and "Full conversation" over either.
+ CodyncSheet(state.thread, { store.openBot(bot.id) }) { root -> RepliesView(bot, root, state, store, connect) }
+ CodyncSheet(state.trace, { store.showTrace(false) }) { TraceView(bot, state.thread, state) }
+ CodyncSheet(routines, { routines = false }) { RoutinesScreen(bot, state, store) }
+ CodyncSheet(peer, { peer = null }) { BotConversationView(bot, it, state, store) }
+ CodyncSheet(app, { app = null; setupEntry = null }) { ComposioConnectSheet(it, state, store, setupEntry) { store.refreshPlugins() } }
+ CodyncSheet(connector, { connector = null; setupEntry = null }) { InstallConnectorSheet(it, state, store, setupEntry) }
+}
+
+/** The glass back button, the title (its menu holds the bot's actions) and the connection under it. */
+@Composable private fun ThreadHeader(bot: Bot, state: AppState, store: AppStore, edit: (Bot) -> Unit, trace: () -> Unit,
+ routines: () -> Unit, newSession: () -> Unit, delete: () -> Unit) {
+ Box(Modifier.fillMaxWidth().statusBarsPadding().padding(top = 6.dp).padding(horizontal = 16.dp).height(44.dp)) {
+ val (source, pressed) = rememberPress()
+ Box(Modifier.align(Alignment.CenterStart).size(44.dp).glass(Capsule(), pressed = pressed)
+ .then(Modifier.plainButton { store.openBot(null) }).semantics { contentDescription = "Back" }, contentAlignment = Alignment.Center) {
+ Symbol("chevron.left", size = 32.dp, tint = Palette.text)
+ }
+ val host = state.computers.firstOrNull()?.name.orEmpty()
+ DropdownMenu({ buildList {
+ add(MenuItem("$host · ${connectionLabel(state)}", enabled = false))
+ add(MenuItem("Reconnect", icon = "arrow.clockwise") { store.connect() })
+ add(MenuItem("Details", icon = "info.circle", divider = true) { edit(bot) })
+ add(MenuItem("Full conversation", icon = "list.bullet.rectangle", action = trace))
+ val pin = MenuItem(if (bot.pinned) "Unpin" else "Pin", icon = "pin") {
+ store.command("updateBot", kotlinx.serialization.json.buildJsonObject {
+ put("id", kotlinx.serialization.json.JsonPrimitive(bot.id)); put("pinned", kotlinx.serialization.json.JsonPrimitive(!bot.pinned))
+ }, "roster:" + bot.id)
+ }
+ if (bot.kind == "group") {
+ add(MenuItem("Edit group", icon = "person.2") { edit(bot) }); add(pin)
+ add(MenuItem("Delete group", icon = "trash", destructive = true, divider = true, action = delete))
+ } else {
+ add(MenuItem("Edit profile", icon = "pencil") { edit(bot) }); add(pin)
+ add(MenuItem("Routines", icon = "clock.arrow.circlepath", action = routines))
+ add(MenuItem("New session", icon = "arrow.counterclockwise", action = newSession))
+ add(MenuItem("Delete bot", icon = "trash", destructive = true, divider = true, action = delete))
+ }
+ } }, Modifier.align(Alignment.Center), label = "${bot.name} actions") {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) {
+ BotAvatar(bot, state.bots, 22.dp)
+ Text(bot.name, style = Type.system(13f).semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ ConnectionSubtitle(state)
+ }
+ }
+ }
+}
+
+/** The link to the computer: route icon (or a spinner) and a word. */
+@Composable private fun ConnectionSubtitle(state: AppState) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Box(Modifier.width(12.dp), contentAlignment = Alignment.Center) {
+ when (val link = state.connection) {
+ LinkState.Connecting -> Spinner(8.dp)
+ is LinkState.Ready -> Symbol(if (link.route == HostRoute.Relay) "cloud" else "wifi", size = 11.dp, tint = Palette.secondary)
+ else -> Symbol("wifi.slash", size = 11.dp, tint = Palette.secondary)
+ }
+ }
+ Text(connectionLabel(state), style = Type.system(10f).medium, color = Palette.secondary, maxLines = 1)
+ }
+}
+
+/** The messages: all this phone has, earlier ones from the computer near the top, following the newest. */
+@Composable private fun Transcript(bot: Bot, state: AppState, store: AppStore, connect: ConnectionRequestActions, padding: PaddingValues,
+ openPeer: (String) -> Unit) {
+ val entries = state.entries.filter { it.botId == bot.id && it.threadId == null && it.isChat }
+ val pending = state.pending.filter { it.botId == bot.id && it.threadId == null }
+ val items = chatItems(entries, pending)
+ val working = bot.status in listOf("working", "needsInput") && bot.workingThread == null && state.connection is LinkState.Ready
+ val list = rememberLazyListState()
+ val more = bot.id !in state.historyComplete
+ Follow(list, items.lastOrNull()?.id, entries.lastOrNull()?.rev, working, padding.calculateBottomPadding())
+ LazyColumn(Modifier.fillMaxSize(), state = list, contentPadding = padding) {
+ if (more) item("earlier") {
+ Box(Modifier.fillMaxWidth().padding(vertical = 14.dp), contentAlignment = Alignment.Center) { Spinner(14.dp) }
+ // A chat shorter than the screen never scrolls, so showing the row is the trigger.
+ LaunchedEffect(Unit) { if ("history" !in state.busy) store.loadHistory() }
+ }
+ if (items.isEmpty() && !more) item("intro") { IntroCard(bot, state) }
+ items(items, key = { it.id }) { item ->
+ when (item) {
+ is ChatItem.Separator -> TimeSeparator(item.at)
+ is ChatItem.Message -> ChatRow(item.entry, item.groupStart, bot, state, store, openTrace = { store.showTrace(true) },
+ reply = { store.openBot(bot.id, item.entry.id) }, connect = connect)
+ is ChatItem.Pending -> PendingBubble(item.send, item.groupStart, state, store)
+ is ChatItem.Exchanges -> BotMessageRow(item.group, state) { openPeer(item.group.peerId) }
+ }
+ }
+ if (working) item("working") { WorkingIndicator(bot, currentThinking(state.entries, bot.id, null)) }
+ }
+}
+
+/** Stays on the newest message until the reader scrolls away; scrolling back down follows again. */
+@Composable private fun Follow(list: LazyListState, last: String?, rev: Long?, working: Boolean, bottom: Dp = 0.dp) {
+ var following by remember { mutableStateOf(true) }
+ LaunchedEffect(list) {
+ // Only the reader's own scroll decides: new content arriving (even while Codync is in the background) keeps the follow.
+ var touched = false
+ launch { list.interactionSource.interactions.collect { if (it is DragInteraction.Start) touched = true } }
+ snapshotFlow { list.isScrollInProgress }.collect { scrolling ->
+ if (!scrolling && touched) { touched = false; following = !list.canScrollForward }
+ }
+ }
+ LaunchedEffect(Unit) {
+ val count = snapshotFlow { list.layoutInfo.totalItemsCount }.first { it > 0 }
+ list.scrollToItem(count - 1, Int.MAX_VALUE)
+ }
+ // A new message, or the box growing (keyboard, more lines): stay on the newest.
+ LaunchedEffect(last, rev, working, bottom) {
+ val count = list.layoutInfo.totalItemsCount
+ if (!following || count == 0) return@LaunchedEffect
+ list.animateScrollToItem(count - 1)
+ list.scrollToItem(count - 1, Int.MAX_VALUE)
+ }
+}
+
+/** A thread: the message it started on, its replies, and a box to continue there. */
+@Composable private fun RepliesView(bot: Bot, rootId: String, state: AppState, store: AppStore, connect: ConnectionRequestActions) {
+ val root = state.entries.firstOrNull { it.botId == bot.id && it.id == rootId }
+ val replies = state.entries.filter { it.botId == bot.id && it.threadId == rootId && it.isChat }
+ val pending = state.pending.filter { it.botId == bot.id && it.threadId == rootId }
+ val working = bot.status in listOf("working", "needsInput") && bot.workingThread == rootId && state.connection is LinkState.Ready
+ var composerHeight by remember { mutableIntStateOf(0) }
+ val density = LocalDensity.current
+ val dismiss = LocalDismissModal.current
+ Box(Modifier.fillMaxSize()) {
+ Column(Modifier.fillMaxSize()) {
+ Row(Modifier.fillMaxWidth().height(56.dp).padding(start = 20.dp, end = 12.dp), verticalAlignment = Alignment.CenterVertically) {
+ Column(Modifier.weight(1f)) {
+ Text("Thread", style = Type.body.semibold, color = Palette.text)
+ Text(bot.name, style = Type.caption, color = Palette.tertiary, maxLines = 1)
+ }
+ IconButton("Close thread", "xmark", action = dismiss)
+ }
+ Box(Modifier.fillMaxWidth().height(0.5.dp).background(Palette.border))
+ val list = rememberLazyListState()
+ val items = chatItems(replies, pending)
+ Follow(list, items.lastOrNull()?.id, replies.lastOrNull()?.rev, working)
+ LazyColumn(Modifier.weight(1f), state = list, contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp,
+ bottom = with(density) { composerHeight.toDp() } + 8.dp)) {
+ if (root != null) {
+ item("root") { ChatRow(root, true, bot, state, store, openTrace = { store.showTrace(true) }, reply = null, connect = connect) }
+ item("count") {
+ val count = (root.data["thread"] as? kotlinx.serialization.json.JsonObject)?.get("count")
+ ?.let { (it as? kotlinx.serialization.json.JsonPrimitive)?.content?.toIntOrNull() } ?: 0
+ Row(Modifier.padding(vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text(if (count == 0) "No replies yet" else if (count == 1) "1 reply" else "$count replies", style = Type.caption, color = Palette.tertiary)
+ Box(Modifier.weight(1f).height(1.dp).background(Palette.border))
+ }
+ }
+ }
+ items(items.filter { it !is ChatItem.Separator }, key = { it.id }) { item ->
+ when (item) {
+ is ChatItem.Message -> ChatRow(item.entry, item.groupStart, bot, state, store, openTrace = { store.showTrace(true) }, reply = null, connect = connect)
+ is ChatItem.Pending -> PendingBubble(item.send, item.groupStart, state, store)
+ is ChatItem.Separator, is ChatItem.Exchanges -> {}
+ }
+ }
+ if (working) item("working") { WorkingIndicator(bot, currentThinking(state.entries, bot.id, rootId)) }
+ }
+ }
+ Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().onSizeChanged { composerHeight = it.height }) {
+ MessageComposer(bot, rootId, state, store, onCall = null)
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
new file mode 100644
index 00000000..8ed4c325
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
@@ -0,0 +1,135 @@
+package com.codync.android
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.slideInHorizontally
+import androidx.compose.animation.slideOutHorizontally
+import androidx.compose.animation.togetherWith
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.safeDrawingPadding
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.key
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import com.codync.android.core.BotDraft
+import com.codync.android.core.CloudComputer
+import com.codync.android.core.GroupDraft
+import com.codync.android.design.*
+
+private enum class Root { Loading, Welcome, Pairing, Tabs }
+
+/** The app's root, as iOS `RootView`: the welcome and pairing until set up, then the tabs, with every sheet on top. */
+@Composable fun CodyncApp(state: AppState, store: AppStore) {
+ var welcomed by rememberSaveable { mutableStateOf(false) }
+ var showAccount by rememberSaveable { mutableStateOf(false) }
+ var accountSettings by rememberSaveable { mutableStateOf(false) }
+ var showComputers by rememberSaveable { mutableStateOf(false) }
+ var showPairing by rememberSaveable { mutableStateOf(false) }
+ var showUsage by rememberSaveable { mutableStateOf(false) }
+ var showMarketplace by rememberSaveable { mutableStateOf(false) }
+ var access by remember { mutableStateOf<CloudComputer?>(null) }
+ var editor by remember { mutableStateOf<BotDraft?>(null) }
+ var groupEditor by remember { mutableStateOf<GroupDraft?>(null) }
+ var handledNavigation by rememberSaveable { mutableIntStateOf(state.navigationRequest) }
+ var handledGeneration by rememberSaveable { mutableIntStateOf(state.generation) }
+ fun closeAll() {
+ showAccount = false; accountSettings = false; showComputers = false; showPairing = false; showMarketplace = false
+ access = null; editor = null; groupEditor = null
+ }
+ // A new account or a fresh start drops whatever was open for the old one.
+ LaunchedEffect(state.generation) { if (handledGeneration != state.generation) { closeAll(); showUsage = false; handledGeneration = state.generation } }
+ // A notification, widget or link: close everything, then maybe show usage.
+ LaunchedEffect(state.navigationRequest) {
+ if (handledNavigation != state.navigationRequest) { closeAll(); showUsage = state.navigationUsage; handledNavigation = state.navigationRequest }
+ }
+ val signedIn = state.account.userId != null
+ AnalyticsMilestones(state)
+ val onboarding = !state.setupComplete && state.computers.isEmpty() && state.cloudComputers.isEmpty()
+ // Signing in to an account that has computers completes setup, as pairing or skipping does.
+ LaunchedEffect(state.cloudComputers.isNotEmpty(), state.loading) {
+ if (!state.loading && !state.setupComplete && state.cloudComputers.isNotEmpty()) store.skipSetup()
+ }
+ val root = when {
+ state.loading -> Root.Loading
+ onboarding && !welcomed && !signedIn -> Root.Welcome
+ onboarding -> Root.Pairing
+ else -> Root.Tabs
+ }
+ BackHandler(root == Root.Pairing && !signedIn) { welcomed = false }
+ val openMarketplace = { showAccount = false; accountSettings = false; showComputers = false; showMarketplace = true }
+ Box(Modifier.fillMaxSize().background(Palette.background)) {
+ AnimatedContent(root, transitionSpec = {
+ if (initialState == Root.Welcome && targetState == Root.Pairing)
+ (slideInHorizontally(Motion.layoutOffset) { it } + fadeIn(Motion.fade())) togetherWith (slideOutHorizontally(Motion.layoutOffset) { -it } + fadeOut(Motion.fade()))
+ else if (initialState == Root.Pairing && targetState == Root.Welcome)
+ (slideInHorizontally(Motion.layoutOffset) { -it } + fadeIn(Motion.fade())) togetherWith (slideOutHorizontally(Motion.layoutOffset) { it } + fadeOut(Motion.fade()))
+ else fadeIn(Motion.fade()) togetherWith fadeOut(Motion.fade())
+ }, label = "Root") { shown ->
+ when (shown) {
+ Root.Loading -> Box(Modifier.fillMaxSize())
+ Root.Welcome -> WelcomeView(state, store) { welcomed = true }
+ Root.Pairing -> Box(Modifier.fillMaxSize().safeDrawingPadding()) {
+ PairingView(state, store, onSkip = store::skipSetup) {
+ if (signedIn) AccountSwitcherButton(state) { showAccount = true } else BackButton { welcomed = false }
+ }
+ }
+ Root.Tabs -> MainTabs(state, store, account = { showAccount = true }, manage = { showComputers = true }, usage = { showUsage = true },
+ newBot = { editor = BotDraft() }, newGroup = { groupEditor = GroupDraft() },
+ edit = { bot -> if (bot.kind == "group") groupEditor = GroupDraft.from(bot) else editor = BotDraft.from(bot) }) {
+ ChatScreen(state, store) { bot -> if (bot.kind == "group") groupEditor = GroupDraft.from(bot) else editor = BotDraft.from(bot) }
+ }
+ }
+ }
+ }
+ // The account sheet holds its own push (Computers & settings), as the iOS sheet's NavigationStack.
+ CodyncSheet(showAccount && (state.setupComplete || signedIn) && !state.loading, { showAccount = false; accountSettings = false }) {
+ NavStack(listOfNotNull("account", "settings".takeIf { accountSettings }), key = { it }, pop = { accountSettings = false }) { page ->
+ if (page == "account") AccountSwitcherView(state, store, { accountSettings = true }) { showPairing = true }
+ else SettingsView(state, store, { accountSettings = false }, { showPairing = true }, { access = it }, openMarketplace)
+ }
+ }
+ CodyncSheet(showComputers && !state.loading, { showComputers = false }) {
+ SettingsView(state, store, null, { showPairing = true }, { access = it }, openMarketplace)
+ }
+ CodyncSheet(access, { access = null }) { AccessRequestView(state, store, it) }
+ CodyncSheet(showPairing && !state.loading, { showPairing = false }) { PairingView(state, store, inModal = true) }
+ CodyncSheet(showUsage && !state.loading, { showUsage = false }) { UsageScreen(state) { store.refreshUsage(it) } }
+ CodyncSheet(showMarketplace && root == Root.Tabs, { showMarketplace = false }) { MarketplaceView(state, store) }
+ CodyncSheet(groupEditor.takeIf { !state.loading }, { groupEditor = null }) { draft ->
+ key(state.contextId, state.generation, draft.id) { GroupEditor(state, draft, store) }
+ }
+ CodyncSheet(editor.takeIf { !state.loading }, { editor = null }) { draft ->
+ key(state.contextId, state.generation, draft.id) { BotEditor(state, draft, store) }
+ }
+ // One place for errors the screen showing them doesn't handle itself (pairing, access, the editors do).
+ val inline = root == Root.Pairing || showPairing || access != null || editor != null || groupEditor != null
+ CodyncDialog("Something went wrong", state.error != null && !inline, store::clearError, state.error, cancel = "OK") { emptyList() }
+}
+
+/** The app-level analytics events (iOS reports the same): setup finished, signed in, signed out. */
+@Composable private fun AnalyticsMilestones(state: AppState) {
+ var setup by remember { mutableStateOf<Boolean?>(null) }
+ var user by remember { mutableStateOf<String?>(null) }
+ var known by remember { mutableStateOf(false) }
+ LaunchedEffect(state.loading, state.setupComplete) {
+ if (state.loading) return@LaunchedEffect
+ if (setup == false && state.setupComplete) Analytics.capture(AnalyticsEvent.OnboardingCompleted)
+ setup = state.setupComplete
+ }
+ LaunchedEffect(state.account.ready, state.account.userId) {
+ if (!state.account.ready) return@LaunchedEffect
+ val now = state.account.userId
+ if (known && now != user) Analytics.capture(if (now != null) AnalyticsEvent.SignedIn else AnalyticsEvent.SignedOut)
+ user = now; known = true
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt
new file mode 100644
index 00000000..f02f8531
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt
@@ -0,0 +1,368 @@
+package com.codync.android
+
+import android.appwidget.AppWidgetManager
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Paint
+import android.graphics.RectF
+import android.net.Uri
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.DpSize
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.glance.ColorFilter
+import androidx.glance.GlanceId
+import androidx.glance.GlanceModifier
+import androidx.glance.Image
+import androidx.glance.ImageProvider
+import androidx.glance.LocalContext
+import androidx.glance.LocalSize
+import androidx.glance.action.clickable
+import androidx.glance.appwidget.GlanceAppWidget
+import androidx.glance.appwidget.GlanceAppWidgetManager
+import androidx.glance.appwidget.GlanceAppWidgetReceiver
+import androidx.glance.appwidget.SizeMode
+import androidx.glance.appwidget.action.actionStartActivity
+import androidx.glance.appwidget.appWidgetBackground
+import androidx.glance.appwidget.cornerRadius
+import androidx.glance.appwidget.provideContent
+import androidx.glance.appwidget.updateAll
+import androidx.glance.background
+import androidx.glance.color.ColorProvider
+import androidx.glance.layout.Alignment
+import androidx.glance.layout.Box
+import androidx.glance.layout.Column
+import androidx.glance.layout.ContentScale
+import androidx.glance.layout.Row
+import androidx.glance.layout.Spacer
+import androidx.glance.layout.fillMaxHeight
+import androidx.glance.layout.fillMaxSize
+import androidx.glance.layout.fillMaxWidth
+import androidx.glance.layout.height
+import androidx.glance.layout.padding
+import androidx.glance.layout.size
+import androidx.glance.layout.width
+import androidx.glance.text.FontWeight
+import androidx.glance.text.Text
+import androidx.glance.text.TextAlign
+import androidx.glance.text.TextStyle
+import androidx.glance.unit.ColorProvider as Ink
+import com.codync.android.core.UsageProvider
+import com.codync.android.core.UsageWindow
+import com.codync.android.core.WidgetBot
+import com.codync.android.core.WidgetFeed
+import com.codync.android.core.WidgetKind
+import com.codync.android.core.teamSlots
+import com.codync.android.design.characterAvatarBitmap
+import kotlin.math.roundToInt
+
+// The Home Screen widgets, drawn like the iOS widgets (CodyncKit `WidgetCards.swift`) and the
+// State tab's previews: Provider usage, Bots and Team.
+
+class ProviderWidget : CodyncWidget(WidgetKind.Provider)
+class BotsWidget : CodyncWidget(WidgetKind.Bots)
+class TeamWidget : CodyncWidget(WidgetKind.Team)
+
+abstract class CodyncWidget(private val kind: WidgetKind) : GlanceAppWidget() {
+ override val sizeMode = SizeMode.Responsive(setOf(SMALL, MEDIUM, LARGE))
+ override val previewSizeMode = sizeMode
+ override suspend fun provideGlance(context: Context, id: GlanceId) {
+ val widget = GlanceAppWidgetManager(context).getAppWidgetId(id)
+ provideContent {
+ val revision by WidgetStore.changes.collectAsState()
+ val feed = remember(revision) { WidgetStore.feed(context) }
+ val provider = remember(revision) { WidgetStore.provider(context, widget) }
+ val team = remember(revision) { WidgetStore.team(context, widget) }
+ WidgetCard(feed, kind, provider, team, sample = false)
+ }
+ }
+ override suspend fun providePreview(context: Context, widgetCategory: Int) {
+ provideContent { WidgetCard(sampleFeed(), kind, "claude", emptyList(), sample = true) }
+ }
+
+ private companion object {
+ val SMALL = DpSize(110.dp, 110.dp)
+ val MEDIUM = DpSize(250.dp, 110.dp)
+ val LARGE = DpSize(250.dp, 250.dp)
+ }
+}
+
+private val ink = ColorProvider(day = Color(0xFF141414), night = Color(0xFFF2F2F2))
+private val secondary = ColorProvider(day = Color(0xFF6B6B6B), night = Color(0xFF9A9A9A))
+private val attention = ColorProvider(day = Color(0xFF936000), night = Color(0xFFECAF52))
+private val danger = ColorProvider(day = Color(0xFFC23A2B), night = Color(0xFFF0A7A7))
+private val tile = ColorProvider(day = Color(0xFFF0F0F0), night = Color(0xFF1C1C1C))
+private val divider = ColorProvider(day = Color(0xFFE6E6E6), night = Color(0xFF262626))
+private val ground = ColorProvider(day = Color(0xFFFFFFFF), night = Color(0xFF141414))
+
+private fun style(size: Float, color: Ink, weight: FontWeight = FontWeight.Normal) = TextStyle(color, size.sp, weight)
+
+@Composable private fun WidgetCard(feed: WidgetFeed, kind: WidgetKind, providerId: String, team: List<String?>, sample: Boolean) {
+ val context = LocalContext.current
+ val size = LocalSize.current
+ val layout = if (size.height >= 230.dp) ProviderLayout.Large else if (size.width >= 230.dp) ProviderLayout.Medium else ProviderLayout.Small
+ val open = widgetIntent(context, feed, usage = kind == WidgetKind.Provider)
+ Box(GlanceModifier.fillMaxSize().appWidgetBackground().background(ground).cornerRadius(22.dp)
+ .then(if (sample) GlanceModifier else GlanceModifier.clickable(actionStartActivity(open))).padding(14.dp)) {
+ when {
+ feed.computerId == null && !sample -> Empty("Codync", "Connect a computer in Codync.")
+ kind == WidgetKind.Provider -> {
+ val provider = feed.usage.providers.firstOrNull { it.id == providerId }
+ if (provider == null) Empty(providerName(providerId), "No usage yet. Open Codync to refresh.")
+ else ProviderCard(context, provider, layout)
+ }
+ kind == WidgetKind.Team -> TeamCard(context, feed, team, sample)
+ else -> BotsCard(context, feed, layout, sample)
+ }
+ }
+}
+
+private fun providerName(id: String) = when (id) { "claude" -> "Claude"; "codex" -> "Codex"; else -> id }
+
+@Composable private fun Empty(title: String, message: String) {
+ Column(GlanceModifier.fillMaxSize()) {
+ Text(title, style = style(13f, ink, FontWeight.Medium), maxLines = 1)
+ Spacer(GlanceModifier.defaultWeight())
+ Text(message, style = style(12f, secondary), maxLines = 3)
+ }
+}
+
+/** Claude keeps its orange; Codex gets its blue in gauges; everyone else is ink. */
+private fun gaugeTint(context: Context, id: String): Int = when (id) {
+ "claude" -> 0xFFD97757.toInt()
+ "codex" -> if (dark(context)) 0xFF70ACDC.toInt() else 0xFF326FAD.toInt()
+ else -> ink.getColor(context).toArgb()
+}
+
+private fun dark(context: Context) = context.resources.configuration.uiMode and android.content.res.Configuration.UI_MODE_NIGHT_MASK ==
+ android.content.res.Configuration.UI_MODE_NIGHT_YES
+
+@Composable private fun ProviderCard(context: Context, provider: UsageProvider, layout: ProviderLayout) {
+ val tint = gaugeTint(context, provider.id)
+ val top = provider.tightest
+ Column(GlanceModifier.fillMaxSize()) {
+ Row(GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
+ val logo = agentIconRes(provider.registry)
+ if (WidgetStore.originalIcons(context) && logo != null) Image(ImageProvider(logo), provider.name, GlanceModifier.size(22.dp),
+ colorFilter = ColorFilter.tint(if (provider.id == "claude") ColorProvider(day = Color(0xFFD97757), night = Color(0xFFD97757)) else ink))
+ else Face(context, if (provider.id == "codex") "hex" else "blob", "gray", 22.dp,
+ highlight = if (provider.id == "claude") 0xFFD97757.toInt() else null)
+ Spacer(GlanceModifier.width(7.dp))
+ Text(provider.name, GlanceModifier.defaultWeight(), style = style(13f, ink, FontWeight.Medium), maxLines = 1)
+ if (layout != ProviderLayout.Small) Text("Usage", style = style(10f, secondary, FontWeight.Medium))
+ }
+ if (layout == ProviderLayout.Small && top != null) {
+ Spacer(GlanceModifier.defaultWeight())
+ Text(top.title, style = style(11f, secondary), maxLines = 1)
+ Row(verticalAlignment = Alignment.Bottom) {
+ val color = if ((top.percent ?: 0.0) >= 90) danger else ink
+ Text("${(top.percent ?: 0.0).roundToInt()}", style = style(32f, color, FontWeight.Medium))
+ Text("%", GlanceModifier.padding(bottom = 4.dp), style = style(17f, color, FontWeight.Medium))
+ }
+ Ticks(context, top.percent ?: 0.0, tint, 13.dp)
+ Spacer(GlanceModifier.height(6.dp))
+ Text(top.resetsShort() ?: "Usage reported by your computer", style = style(9f, secondary), maxLines = 1)
+ } else {
+ Spacer(GlanceModifier.height(8.dp))
+ if (layout == ProviderLayout.Large && top != null) {
+ Row(GlanceModifier.padding(vertical = 4.dp), verticalAlignment = Alignment.Bottom) {
+ Text("${(top.percent ?: 0.0).roundToInt()}%", style = style(36f, if ((top.percent ?: 0.0) >= 90) danger else ink, FontWeight.Medium))
+ Spacer(GlanceModifier.width(8.dp))
+ Text("${top.title} · highest usage", GlanceModifier.padding(bottom = 6.dp), style = style(11f, secondary), maxLines = 2)
+ }
+ }
+ for (window in provider.windows.take(if (layout == ProviderLayout.Large) 4 else 2)) WindowRow(context, window, tint)
+ }
+ }
+}
+
+@Composable private fun WindowRow(context: Context, window: UsageWindow, tint: Int) {
+ Column(GlanceModifier.fillMaxWidth().padding(bottom = 6.dp)) {
+ Row(GlanceModifier.fillMaxWidth()) {
+ Text(window.title, GlanceModifier.defaultWeight(), style = style(11f, secondary, FontWeight.Medium), maxLines = 1)
+ Text("${(window.percent ?: 0.0).roundToInt()}%", style = style(13f, if ((window.percent ?: 0.0) >= 90) danger else ink, FontWeight.Medium))
+ }
+ Spacer(GlanceModifier.height(3.dp))
+ Ticks(context, window.percent ?: 0.0, tint, 12.dp)
+ window.resetsShort()?.let { Text(it, GlanceModifier.fillMaxWidth(), style = TextStyle(secondary, 9.sp, textAlign = TextAlign.End), maxLines = 1) }
+ }
+}
+
+/** Fine, separated ticks (iOS `UsageTicks`), as a bitmap: widgets can't draw. */
+@Composable private fun Ticks(context: Context, percent: Double, tint: Int, height: Dp) {
+ val red = danger.getColor(context).toArgb()
+ val bitmap = remember(percent, tint, red) { ticks(percent, tint, red) }
+ Image(ImageProvider(bitmap), "${percent.roundToInt()} percent", GlanceModifier.fillMaxWidth().height(height), contentScale = ContentScale.FillBounds)
+}
+
+private fun ticks(percent: Double, tint: Int, red: Int): Bitmap {
+ val count = 60; val unit = 8f; val gap = 3f
+ val bitmap = Bitmap.createBitmap((count * (unit + gap)).toInt(), 26, Bitmap.Config.ARGB_8888)
+ val canvas = Canvas(bitmap)
+ val value = if (percent.isFinite()) percent.coerceIn(0.0, 100.0) else 0.0
+ val color = if (value >= 90) red else tint
+ val filled = (count * value / 100).roundToInt()
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG)
+ for (i in 0 until count) {
+ paint.color = if (i < filled) color else (color and 0x00FFFFFF) or (0x29 shl 24)
+ canvas.drawRoundRect(RectF(i * (unit + gap), 0f, i * (unit + gap) + unit, 26f), 2f, 2f, paint)
+ }
+ return bitmap
+}
+
+@Composable private fun Face(context: Context, shape: String, color: String, size: Dp, highlight: Int? = null) {
+ val pixels = (size.value * context.resources.displayMetrics.density).toInt().coerceIn(1, 256)
+ val inkColor = ink.getColor(context).toArgb()
+ val bitmap = remember(shape, color, pixels, inkColor, highlight) { characterAvatarBitmap(shape, color, pixels, inkColor, highlight) }
+ Image(ImageProvider(bitmap), null, GlanceModifier.size(size))
+}
+
+private fun rank(bot: WidgetBot) = when (bot.status) { "needsInput" -> 0; "working" -> 1; else -> 2 }
+
+private fun stateWord(bot: WidgetBot): Pair<String, Ink> = when (bot.status) {
+ "needsInput" -> "Needs you" to attention
+ "error" -> "Failed" to danger
+ "working" -> "Working" to ink
+ else -> "Ready" to secondary
+}
+
+/** Who needs you and who's still working: a count, then the bots in that order. */
+@Composable private fun BotsCard(context: Context, feed: WidgetFeed, layout: ProviderLayout, sample: Boolean) {
+ val bots = feed.bots.sortedBy(::rank)
+ val needs = bots.count { it.status == "needsInput" }
+ val working = bots.count { it.status == "working" }
+ val count = if (needs > 0) needs else if (working > 0) working else bots.size
+ val label = if (needs > 0) (if (needs == 1) "Needs you" else "Need you") else if (working > 0) "Working" else if (bots.isEmpty()) "No bots yet" else "All quiet"
+ Column(GlanceModifier.fillMaxSize()) {
+ Row(GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
+ Text("Bots", GlanceModifier.defaultWeight(), style = style(13f, ink, FontWeight.Medium))
+ Image(ImageProvider(requireNotNull(com.codync.android.design.symbolRes("bubble.left.and.bubble.right"))), null, GlanceModifier.size(15.dp), colorFilter = ColorFilter.tint(secondary))
+ }
+ Spacer(GlanceModifier.height(10.dp))
+ when (layout) {
+ ProviderLayout.Large -> {
+ Row(GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.Bottom) {
+ Summary(count, label, needs > 0, GlanceModifier.defaultWeight())
+ Text("${bots.size} total · $working working", style = style(11f, secondary))
+ }
+ Spacer(GlanceModifier.height(10.dp))
+ Box(GlanceModifier.fillMaxWidth().height(1.dp).background(divider)) {}
+ Spacer(GlanceModifier.height(10.dp))
+ BotRows(context, feed, bots.take(6), sample)
+ }
+ ProviderLayout.Medium -> Row(GlanceModifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) {
+ Summary(count, label, needs > 0, GlanceModifier.width(76.dp))
+ Spacer(GlanceModifier.width(16.dp))
+ Box(GlanceModifier.width(1.dp).fillMaxHeight().background(divider)) {}
+ Spacer(GlanceModifier.width(16.dp))
+ Box(GlanceModifier.defaultWeight()) { BotRows(context, feed, bots.take(3), sample) }
+ }
+ ProviderLayout.Small -> {
+ Spacer(GlanceModifier.defaultWeight())
+ Summary(count, label, needs > 0, GlanceModifier)
+ Row(GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
+ for (bot in bots.take(3)) Face(context, bot.avatarShape, bot.avatarColor, 23.dp)
+ Spacer(GlanceModifier.defaultWeight())
+ if (working > 0 && needs > 0) Text("$working working", style = style(9f, secondary))
+ }
+ }
+ }
+ }
+}
+
+@Composable private fun Summary(count: Int, label: String, needs: Boolean, modifier: GlanceModifier) {
+ Column(modifier) {
+ Text("$count", style = style(36f, if (needs) attention else ink, FontWeight.Medium))
+ Text(label, style = style(12f, secondary, FontWeight.Medium), maxLines = 1)
+ }
+}
+
+@Composable private fun BotRows(context: Context, feed: WidgetFeed, bots: List<WidgetBot>, sample: Boolean) {
+ Column(GlanceModifier.fillMaxWidth()) {
+ for (bot in bots) {
+ val (word, tint) = stateWord(bot)
+ val open = if (sample) GlanceModifier else GlanceModifier.clickable(actionStartActivity(widgetIntent(context, feed, bot.id)))
+ Row(open.fillMaxWidth().padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
+ Face(context, bot.avatarShape, bot.avatarColor, 24.dp)
+ Spacer(GlanceModifier.width(7.dp))
+ Text(bot.name, GlanceModifier.defaultWeight(), style = style(11f, ink, FontWeight.Medium), maxLines = 1)
+ Text(word, style = style(10f, tint, if (bot.status == "needsInput") FontWeight.Medium else FontWeight.Normal), maxLines = 1)
+ }
+ }
+ if (bots.isEmpty()) Text("Create your first bot in Codync.", style = style(12f, secondary))
+ }
+}
+
+/** Four bots in a 2×2 grid, each in its mood with a dot for its state; empty spots sleep. */
+@Composable private fun TeamCard(context: Context, feed: WidgetFeed, picks: List<String?>, sample: Boolean) {
+ val slots = teamSlots(feed.bots, picks)
+ Column(GlanceModifier.fillMaxSize()) {
+ for ((index, row) in slots.chunked(2).withIndex()) {
+ if (index > 0) Spacer(GlanceModifier.height(8.dp))
+ Row(GlanceModifier.fillMaxWidth().defaultWeight()) {
+ for ((column, bot) in row.withIndex()) {
+ if (column > 0) Spacer(GlanceModifier.width(8.dp))
+ val open = if (sample || bot == null) GlanceModifier else GlanceModifier.clickable(actionStartActivity(widgetIntent(context, feed, bot.id)))
+ Box(open.defaultWeight().fillMaxHeight().background(tile).cornerRadius(16.dp), contentAlignment = Alignment.Center) {
+ if (bot == null) Face(context, "blob", "gray", 26.dp)
+ else Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Face(context, bot.avatarShape, bot.avatarColor, 30.dp)
+ Text(bot.name, style = style(9f, ink, FontWeight.Medium), maxLines = 1)
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+internal fun widgetIntent(context: Context, feed: WidgetFeed, bot: String? = null, usage: Boolean = false): Intent {
+ val intent = Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
+ val computer = feed.computerId ?: return intent
+ if (bot != null || usage) intent.data = Uri.Builder().scheme(BuildConfig.URL_SCHEME).authority(if (usage) "usage" else "bot")
+ .apply { if (bot != null) appendPath(bot) }.appendQueryParameter("scope", feed.scope).appendQueryParameter("computer", computer).build()
+ return intent
+}
+
+/** The launcher's picker preview: the State tab's sample data. */
+internal fun sampleFeed(): WidgetFeed = WidgetFeed(computerId = "sample", computerName = "Sample computer", bots = WidgetPreview.bots,
+ botsAt = System.currentTimeMillis(), usage = WidgetPreview.usage, usageAt = System.currentTimeMillis())
+
+class ProviderWidgetReceiver : CodyncWidgetReceiver() { override val glanceAppWidget = ProviderWidget() }
+class BotsWidgetReceiver : CodyncWidgetReceiver() { override val glanceAppWidget = BotsWidget() }
+class TeamWidgetReceiver : CodyncWidgetReceiver() { override val glanceAppWidget = TeamWidget() }
+
+abstract class CodyncWidgetReceiver : GlanceAppWidgetReceiver() {
+ override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {
+ super.onUpdate(context, manager, ids)
+ WidgetRefreshWorker.schedule(context, WidgetStore.feed(context).computerId != null)
+ }
+ override fun onDeleted(context: Context, ids: IntArray) { WidgetStore.remove(context, ids); super.onDeleted(context, ids) }
+ override fun onDisabled(context: Context) { super.onDisabled(context); WidgetRefreshWorker.schedule(context, WidgetStore.feed(context).computerId != null) }
+}
+
+internal object CodyncWidgets {
+ val receivers = listOf(ProviderWidgetReceiver::class.java, BotsWidgetReceiver::class.java, TeamWidgetReceiver::class.java)
+ fun installed(context: Context): Int = receivers.sumOf { AppWidgetManager.getInstance(context).getAppWidgetIds(ComponentName(context, it)).size }
+ suspend fun update(context: Context) {
+ if (installed(context) == 0) return
+ ProviderWidget().updateAll(context); BotsWidget().updateAll(context); TeamWidget().updateAll(context)
+ }
+ fun pin(context: Context, kind: WidgetKind): Boolean {
+ val manager = AppWidgetManager.getInstance(context)
+ if (!manager.isRequestPinAppWidgetSupported) return false
+ val receiver = when (kind) { WidgetKind.Provider -> ProviderWidgetReceiver::class.java; WidgetKind.Bots -> BotsWidgetReceiver::class.java
+ WidgetKind.Team -> TeamWidgetReceiver::class.java }
+ return manager.requestPinAppWidget(ComponentName(context, receiver), null, null)
+ }
+}
+
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ComposioViews.kt b/apps/android/app/src/main/kotlin/com/codync/android/ComposioViews.kt
new file mode 100644
index 00000000..d0bb7daf
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ComposioViews.kt
@@ -0,0 +1,201 @@
+package com.codync.android
+
+import androidx.activity.compose.LocalActivity
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalUriHandler
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.CatalogPage
+import com.codync.android.core.ComposioApp
+import com.codync.android.core.ComposioStatus
+import com.codync.android.design.*
+import java.util.UUID
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.launch
+
+// Apps through Composio (host/src/market/composio.rs): set up a key once, connect apps with
+// Composio's hosted sign-in, then turn them on per bot like any other connector.
+
+/** The Extensions page's "Apps" section (iOS `ComposioSection`). */
+@Composable internal fun ComposioSection(query: String, searchToken: Int, state: AppState, store: AppStore) {
+ var status by remember { mutableStateOf<ComposioStatus?>(null) }
+ var apps by remember { mutableStateOf(CatalogPage<ComposioApp>()) }
+ var loading by remember { mutableStateOf(true) }
+ var error by remember { mutableStateOf<String?>(null) }
+ var settingUp by remember { mutableStateOf(false) }
+ var connecting by remember { mutableStateOf<ComposioApp?>(null) }
+ var reload by remember { mutableIntStateOf(0) }
+ LaunchedEffect(searchToken, reload) {
+ loading = true
+ try {
+ val answer = store.composioStatus()
+ val page = if (answer.configured) store.composioApps(query, null).items else emptyList()
+ status = answer; apps = CatalogPage<ComposioApp>().append(page) { it.slug }; error = null
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't load apps." }
+ finally { loading = false }
+ }
+ MarketSection("Apps") {
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ when {
+ status?.configured != true -> MarketRow("Composio", "Gmail, Slack, GitHub, Notion and 1,000 more apps", added = false,
+ busy = status == null && loading, addLabel = "Set up", icon = { TileIcon("square.grid.3x3") }) { settingUp = true }
+ loading -> SkeletonRows()
+ apps.items.isEmpty() -> Text(if (query.isEmpty()) "Couldn't load apps." else "No apps match “$query”.", style = Type.body, color = Palette.secondary)
+ else -> Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (app in apps.visible) MarketRow(app.name, app.description ?: app.slug, app.connected, addLabel = "Connect",
+ icon = { AppLogo(app.logo, app.name) }) { connecting = app }
+ }
+ }
+ if (!loading && apps.hasHidden && status?.configured == true)
+ Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { SecondaryButton("Load more apps") { apps = apps.reveal() } }
+ error?.let { Text(it, style = Type.footnote, color = Palette.danger) }
+ if (status?.configured == true) Row(Modifier.plainButton { settingUp = true }, verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Symbol("key", size = 14.dp, tint = Palette.tertiary)
+ Text("Composio settings", style = Type.footnote, color = Palette.tertiary)
+ }
+ }
+ }
+ CodyncSheet(settingUp, { settingUp = false }) { ComposioKeySheet(status, state, store) { status = it; reload++ } }
+ CodyncSheet(connecting, { connecting = null }) { ComposioConnectSheet(it, state, store) { reload++; store.refreshPlugins() } }
+}
+
+/** Paste (or remove) the Composio API key; the host checks it with Composio first (iOS `ComposioKeySheet`). */
+@Composable internal fun ComposioKeySheet(status: ComposioStatus?, state: AppState, store: AppStore, done: (ComposioStatus) -> Unit) {
+ val dismiss = LocalDismissModal.current
+ val scope = rememberCoroutineScope()
+ var key by remember { mutableStateOf("") }
+ var saving by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf<String?>(null) }
+ fun save(value: String) {
+ saving = true; error = null
+ scope.launch {
+ try { done(store.composioKey(value)); dismiss() }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "The key wasn't confirmed." }
+ finally { saving = false }
+ }
+ }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader("Composio") {
+ if (saving) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
+ else IconButton("Save", "checkmark", enabled = key.isNotBlank()) { save(key.trim()) }
+ }
+ CardForm(Modifier.weight(1f)) {
+ CardSection("Composio API key", "Composio signs you in to apps like Gmail and Slack and runs their tools for your bots. The key stays on ${state.hostName}.") {
+ row { PlainInput(key, { key = it }, if (status?.configured == true) "Saved (paste to replace)" else "ak_…", secret = true) }
+ row { WebLink("Get a key from Composio", status?.keyUrl ?: "https://platform.composio.dev", Type.footnote) }
+ }
+ if (status?.configured == true) CardSection(footer = "Bots lose the apps you connected until you add a key again.") {
+ row { LinkButton("Remove key", enabled = !saving, color = Palette.danger) { save("") } }
+ }
+ error?.let { CardSection { row { ErrorRow(it) } } }
+ }
+ }
+}
+
+/**
+ * Connects one app (iOS `ComposioConnectSheet`): Composio's sign-in page, opened here and
+ * finished anywhere, or a form for apps that use a key. A chat's request finishes once it's connected.
+ */
+@Composable internal fun ComposioConnectSheet(app: ComposioApp, state: AppState, store: AppStore, requestId: String? = null, done: () -> Unit = {}) {
+ val dismiss = LocalDismissModal.current
+ val uri = LocalUriHandler.current
+ val activity = LocalActivity.current
+ val owner = rememberSaveable { UUID.randomUUID().toString() }
+ var connectionId by rememberSaveable { mutableStateOf<String?>(null) }
+ val session = remember(owner) { store.appConnection(owner, app.slug, connectionId) }
+ val status by session.state.collectAsState()
+ var opened by rememberSaveable { mutableStateOf(false) }
+ var finished by rememberSaveable { mutableStateOf(false) }
+ var values by remember { mutableStateOf(emptyMap<String, String>()) }
+ var error by remember { mutableStateOf<String?>(null) }
+ fun open(url: String) { if (runCatching { uri.openUri(url) }.isFailure) error = "Couldn't open the sign-in browser." }
+ DisposableEffect(session) {
+ onDispose {
+ // Rotation keeps the attempt; leaving ends it.
+ if (activity?.isChangingConfigurations != true) store.closeAppConnection(owner)
+ if (finished) done()
+ }
+ }
+ LaunchedEffect(status.connectionId) { status.connectionId?.let { connectionId = it } }
+ LaunchedEffect(status.plan?.url) { status.plan?.url?.let { if (!opened) { opened = true; open(it) } } }
+ LaunchedEffect(status.connected) {
+ if (!status.connected || finished) return@LaunchedEffect
+ try { requestId?.let { store.finishConnectionRequest(it, connectorId = "composio-${app.slug}") }; values = emptyMap(); finished = true }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "The app is connected, but the request wasn't confirmed." }
+ }
+ val plan = status.plan
+ val connected = status.connected && finished
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader("Connect ${app.name}") {
+ if (connected) IconButton("Done", "checkmark", action = dismiss)
+ else if (plan?.status == "needsFields") {
+ if (status.saving) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
+ else IconButton("Connect", "checkmark", enabled = plan.complete(values)) { session.submit(values) }
+ }
+ }
+ CardForm(Modifier.weight(1f)) {
+ CardSection {
+ row {
+ Row(Modifier.padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ AppLogo(app.logo, app.name, 52.dp)
+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(app.name, style = Type.title3.semibold, color = Palette.text)
+ app.description?.let { Text(it, style = Type.subheadline, color = Palette.secondary, maxLines = 3) }
+ }
+ }
+ }
+ }
+ when {
+ connected -> CardSection(footer = "Turn ${app.name} on for a bot in the bot's settings, under Connectors.") {
+ row { IconLabel("Connected", "checkmark.circle.fill", Palette.added, style = Type.body) }
+ }
+ plan?.status == "needsFields" -> CardSection(footer = "Sent to Composio, which keeps it for ${app.name}.") {
+ for (field in plan.fields.orEmpty()) row {
+ NotedInput(values[field.name].orEmpty(), { values = values + (field.name to it) }, field.label,
+ field.description?.let { it + if (field.required) "" else " (optional)" }, secret = field.secret)
+ }
+ }
+ plan?.status == "redirect" || status.connectionId != null -> CardSection(footer = "Sign in on the page that opened. This updates by itself when you're done.") {
+ plan?.url?.let { url ->
+ row {
+ SecondaryButton({ open(url) }) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol("safari", size = 18.dp, tint = Palette.text)
+ Text("Open the sign-in page")
+ }
+ }
+ }
+ }
+ row { Waiting("Waiting for you to finish signing in…") }
+ }
+ status.error == null && error == null -> CardSection { row { Waiting("Asking Composio…") } }
+ }
+ (error ?: status.error)?.let { CardSection { row { ErrorRow(it) } } }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
new file mode 100644
index 00000000..68ce713a
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
@@ -0,0 +1,27 @@
+package com.codync.android
+
+import com.codync.android.core.LinkState
+
+/** Cached bots remain readable while the connection reports its actual state. */
+internal fun connectionLabel(link: LinkState): String = when (link) {
+ is LinkState.Ready -> "Connected"
+ LinkState.Connecting -> "Connecting…"
+ is LinkState.ComputerOffline -> "Computer offline"
+ is LinkState.Failed -> if (link.status == 403) "Access denied" else if (link.status == 426) "Update required" else "Disconnected"
+}
+
+internal data class EmptyRoster(val title: String, val detail: String? = null, val canCreate: Boolean = false)
+
+internal fun emptyRoster(state: AppState, query: String, hidden: Boolean): EmptyRoster = when {
+ state.computers.isEmpty() -> EmptyRoster("No computer yet")
+ query.isNotBlank() -> EmptyRoster("No matching bots")
+ state.connection !is LinkState.Ready -> EmptyRoster(connectionLabel(state.connection),
+ when (val link = state.connection) {
+ is LinkState.Failed -> link.message
+ is LinkState.ComputerOffline -> "Your bots and chats will appear when the computer reconnects."
+ else -> "Waiting for your computer’s bot list."
+ })
+ !state.rosterLoaded -> EmptyRoster("Syncing bots…")
+ hidden -> EmptyRoster("No hidden bots")
+ else -> EmptyRoster("No bots yet", canCreate = state.actualConnection is LinkState.Ready)
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionRequestCard.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionRequestCard.kt
new file mode 100644
index 00000000..c4d0517e
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionRequestCard.kt
@@ -0,0 +1,128 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.platform.testTag
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.AgentBackend
+import com.codync.android.core.ComposioApp
+import com.codync.android.core.ConnectionRequest
+import com.codync.android.core.Entry
+import com.codync.android.core.MarketConnector
+import com.codync.android.core.WireJson
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+import java.io.IOException
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.launch
+import kotlinx.serialization.json.decodeFromJsonElement
+
+/**
+ * A bot asking for a connection in the chat (iOS `ConnectionRequestCard`). Credentials go through
+ * the setup API; only the request's state is a chat entry. Apps and registry connectors open their
+ * sheets over the chat (`openApp` / `install`); an agent's sign-in opens its sheet here.
+ */
+@Composable internal fun ConnectionRequestCard(entry: Entry, state: AppState, store: AppStore,
+ openApp: (String, ComposioApp) -> Unit, install: (String, MarketConnector) -> Unit) {
+ val request = entry.data["connectionRequest"]?.let { runCatching { WireJson.decodeFromJsonElement<ConnectionRequest>(it) }.getOrNull() }
+ if (request == null || request.botId != entry.botId && state.bots.none { it.id == request.botId }) {
+ Text("This connection request needs a newer app.", style = Type.body, color = Palette.secondary); return
+ }
+ val scope = rememberCoroutineScope()
+ var value by remember(entry.id) { mutableStateOf("") }
+ var username by remember(entry.id) { mutableStateOf("") }
+ var busy by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf<String?>(null) }
+ var agent by remember { mutableStateOf<AgentBackend?>(null) }
+ val pending = request.status == "pending"
+ val working = busy || "connection:${entry.id}" in state.busy
+ fun connect() {
+ busy = true; error = null
+ scope.launch {
+ try {
+ when {
+ // The host completes the card and resends the messages once the sheet finds it signed in.
+ request.kind == "agent" -> agent = agentBackends(state).firstOrNull { it.id == request.backend }
+ ?: throw IOException("Open ${request.title} in Extensions to sign in.")
+ request.kind == "app" -> openApp(entry.id, ComposioApp(requireNotNull(request.toolkit), request.title))
+ request.kind == "login" -> { store.finishConnectionRequest(entry.id, value = value, username = username); value = "" }
+ request.kind == "secret" -> { store.finishConnectionRequest(entry.id, value = value); value = "" }
+ request.connectorId != null -> {
+ val id = requireNotNull(request.connectorId)
+ // The store finishes the request itself once a sign-in comes back.
+ if (store.installedConnectors().firstOrNull { it.id == id }?.needsSignIn == true) {
+ if (!store.signInConnector(id, entry.id)) throw IOException("Sign-in wasn't confirmed. Connect again to retry.")
+ } else store.finishConnectionRequest(entry.id, connectorId = id)
+ }
+ request.registryName != null -> install(entry.id, store.connectorInfo(requireNotNull(request.registryName)))
+ }
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Connection wasn't confirmed. Check its setup and try again." }
+ finally { busy = false }
+ }
+ }
+ // A card, not a banner: full width on a phone, capped on wider screens; no fill, so each field gets one.
+ Column(Modifier.testTag("connection:${entry.id}").widthIn(max = 400.dp).fillMaxWidth().border(1.dp, Palette.border, RoundedRectangle(20.dp))
+ .padding(horizontal = 16.dp, vertical = 14.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ RequestLogo(request, state)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(request.title, style = Type.body.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ if (entry.text.isNotBlank()) Text(entry.text, style = Type.subheadline, color = Palette.secondary, maxLines = 2, overflow = TextOverflow.Ellipsis)
+ }
+ if (pending) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ if (working) Spinner()
+ PrimaryButton(when (request.kind) { "agent" -> "Sign in"; "login" -> "Save"; else -> "Connect" },
+ enabled = !working && request.canConnect && state.actualConnection is com.codync.android.core.LinkState.Ready &&
+ (request.kind !in listOf("secret", "login") || value.isNotEmpty()), action = ::connect)
+ } else Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ if (request.status == "ready") Symbol("checkmark", size = 14.dp, tint = Palette.secondary)
+ Text(if (request.status != "ready") "Cancelled" else when (request.kind) { "agent" -> "Signed in"; "login" -> "Saved"; else -> "Connected" },
+ style = Type.subheadline, color = Palette.secondary)
+ }
+ }
+ if (pending && request.kind == "login") {
+ Box(Modifier.pill(Palette.bubbleAgent)) { PlainInput(username, { username = it }, "Username or email") }
+ Box(Modifier.pill(Palette.bubbleAgent)) { PlainInput(value, { value = it }, "Password or op:// reference", secret = true) }
+ Text("Saved securely on this computer. The bot types it into the sign-in page but never sees it.", style = Type.caption, color = Palette.secondary)
+ } else if (pending && request.kind == "secret") {
+ Text("${request.field ?: "Credential"} · ${request.location.orEmpty()}", style = Type.caption, color = Palette.secondary)
+ Box(Modifier.pill(Palette.bubbleAgent)) { PlainInput(value, { value = it }, "Credential or op:// reference", secret = true) }
+ Text("Saved securely on this computer. Never added to the conversation.", style = Type.caption, color = Palette.secondary)
+ }
+ error?.let { Text(it, style = Type.footnote, color = Palette.danger) }
+ }
+ CodyncSheet(agent, { agent = null }) { AgentSheet(it, state, store, recheck = true) }
+}
+
+/** The agent, website or service the request is for. */
+@Composable private fun RequestLogo(request: ConnectionRequest, state: AppState) {
+ when (request.kind) {
+ "agent" -> Box(Modifier.size(46.dp).clip(RoundedRectangle(12.dp)).background(Palette.bubbleAgent), contentAlignment = Alignment.Center) {
+ AgentIcon(agentBackends(state).firstOrNull { it.id == request.backend }?.registry ?: request.backend, 26.dp)
+ }
+ "app" -> AppLogo(request.logo, request.title)
+ // A login's site is a domain, or an app's name (no logo to find for that).
+ "login" -> ServiceLogo(null, request.title, site = request.site?.takeIf { '.' in it })
+ else -> ServiceLogo(null, request.title, request.registryName)
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectorOAuthBook.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectorOAuthBook.kt
new file mode 100644
index 00000000..1c3313b3
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ConnectorOAuthBook.kt
@@ -0,0 +1,23 @@
+package com.codync.android
+
+import android.util.AtomicFile
+import com.codync.android.core.PendingConnectorOAuth
+import com.codync.android.core.WireJson
+import java.io.File
+import kotlinx.serialization.encodeToString
+
+/** One short-lived state hash, excluded from backup; codes and credentials are never saved. */
+internal class ConnectorOAuthBook(directory: File) {
+ private val file = AtomicFile(File(directory, "connector-oauth.json"))
+ fun read(): PendingConnectorOAuth? {
+ if (!file.baseFile.exists()) return null
+ check(file.baseFile.length() <= 4096) { "The pending connector sign-in is damaged." }
+ return WireJson.decodeFromString(file.readFully().toString(Charsets.UTF_8))
+ }
+ fun save(pending: PendingConnectorOAuth) {
+ val output = file.startWrite()
+ try { output.write(WireJson.encodeToString(pending).toByteArray()); file.finishWrite(output) }
+ catch (error: Throwable) { file.failWrite(output); throw error }
+ }
+ fun clear() = file.delete()
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectorSheets.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectorSheets.kt
new file mode 100644
index 00000000..7f9fcfe3
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ConnectorSheets.kt
@@ -0,0 +1,253 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.InstalledConnector
+import com.codync.android.core.MarketConnector
+import com.codync.android.design.*
+import java.io.IOException
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.launch
+
+/** Adds a registry connector (iOS `InstallConnectorSheet`): where it runs, its keys, then its sign-in. */
+@Composable internal fun InstallConnectorSheet(item: MarketConnector, state: AppState, store: AppStore, requestId: String? = null, done: () -> Unit = {}) {
+ val dismiss = LocalDismissModal.current
+ val scope = rememberCoroutineScope()
+ var optionId by remember(item.name) { mutableStateOf(item.options.firstOrNull()?.id.orEmpty()) }
+ var values by remember(item.name) { mutableStateOf(emptyMap<String, String>()) }
+ var installed by remember(item.name) { mutableStateOf<InstalledConnector?>(null) }
+ var saving by remember { mutableStateOf(false) }
+ var signingIn by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf<String?>(null) }
+ val option = item.options.firstOrNull { it.id == optionId } ?: item.options.firstOrNull()
+ fun install() {
+ val choice = option ?: return
+ if (saving) return
+ saving = true; error = null
+ scope.launch {
+ try {
+ val connector = installed?.let { known -> store.installedConnectors().firstOrNull { it.id == known.id } ?: known }
+ ?: store.installConnector(item, choice, values).also { installed = it; values = emptyMap() }
+ if (connector.needsSignIn) {
+ // The store finishes a chat's request itself once the sign-in comes back.
+ signingIn = true
+ if (!store.signInConnector(connector.id, requestId)) throw IOException("Sign-in wasn't confirmed. Try Add again to sign in.")
+ } else if (requestId != null) store.finishConnectionRequest(requestId, connectorId = connector.id)
+ if (requestId == null) store.verifyConnector(connector.id)
+ done(); dismiss()
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't add this connector." }
+ finally { saving = false; signingIn = false }
+ }
+ }
+ // Nothing to fill in: it adds itself.
+ LaunchedEffect(item.name) { if (item.options.size == 1 && item.options[0].inputs.isEmpty()) install() }
+ val ready = installed != null || option?.complete(values) == true
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader("Add connector") {
+ if (saving) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
+ else IconButton("Add", "plus", enabled = ready) { install() }
+ }
+ CardForm(Modifier.weight(1f)) {
+ CardSection {
+ row {
+ Column(Modifier.padding(vertical = 4.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(item.title, style = Type.title3.semibold, color = Palette.text)
+ item.description?.let { Text(it, style = Type.body, color = Palette.secondary) }
+ item.website?.let { WebLink(it, it, Type.footnote) }
+ }
+ }
+ }
+ if (item.options.size > 1) CardSection("Runs") {
+ row {
+ ChoiceList(optionId, item.options.map { Triple(it.id, if (it.kind == "remote") "Hosted by ${item.title}" else "On ${state.hostName} (${it.kind})", null) },
+ { optionId = it; values = emptyMap() })
+ }
+ }
+ if (option != null) CardSection("Setup", "Keys are saved on ${state.hostName} only.") {
+ if (option.inputs.isEmpty()) row {
+ Text(if (option.kind == "remote") "No keys needed here. If ${item.title} wants you to sign in, its sign-in page opens next." else "No setup needed.",
+ style = Type.body, color = Palette.secondary)
+ }
+ for (input in option.inputs) row {
+ NotedInput(values[input.name].orEmpty(), { values = values + (input.name to it) },
+ if (input.secret) input.name else input.defaultValue ?: input.placeholder ?: input.name,
+ input.description?.let { it + if (input.required) "" else " (optional)" }, secret = input.secret)
+ }
+ }
+ if (signingIn) CardSection { row { Waiting("Finish signing in to ${item.title} in the browser…") } }
+ error?.let { CardSection { row { ErrorRow(it) } } }
+ }
+ }
+}
+
+/** A spinner with what it waits for. */
+@Composable internal fun Waiting(text: String) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Spinner()
+ Text(text, style = Type.body, color = Palette.secondary)
+ }
+}
+
+private enum class CustomMode { Command, Url, Config }
+
+/** Any MCP server: a command, a URL, or a pasted config (iOS `CustomConnectorSheet`). */
+@Composable internal fun CustomConnectorSheet(state: AppState, store: AppStore) {
+ val dismiss = LocalDismissModal.current
+ val scope = rememberCoroutineScope()
+ var mode by remember { mutableStateOf(CustomMode.Command) }
+ var name by remember { mutableStateOf("") }
+ var target by remember { mutableStateOf("") }
+ var envText by remember { mutableStateOf("") }
+ var config by remember { mutableStateOf("") }
+ var saving by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf<String?>(null) }
+ val ready = if (mode == CustomMode.Config) config.isNotBlank() else name.isNotBlank() && target.isNotBlank()
+ fun save() {
+ saving = true; error = null
+ val remote = mode == CustomMode.Url
+ val pairs = envText.lines().mapNotNull { line ->
+ val parts = line.split(if (remote) ':' else '=', limit = 2).map(String::trim)
+ if (parts.size == 2 && parts[0].isNotEmpty()) parts[0] to parts[1] else null
+ }.toMap()
+ scope.launch {
+ try {
+ val added = if (mode == CustomMode.Config) store.importConnectors(config)
+ else listOf(store.addConnector(name.trim(), target.trim().takeUnless { remote }, target.trim().takeIf { remote },
+ if (remote) emptyMap() else pairs, if (remote) pairs else emptyMap()))
+ for (connector in added.filter { it.needsSignIn }) {
+ if (!store.signInConnector(connector.id)) throw IOException("${connector.name} was added, but its sign-in wasn't confirmed. Sign in from Installed.")
+ }
+ dismiss()
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't add this connector." }
+ finally { saving = false }
+ }
+ }
+ val host = state.hostName
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader("Custom connector") {
+ if (saving) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
+ else IconButton("Add", "plus", enabled = ready) { save() }
+ }
+ CardForm(Modifier.weight(1f)) {
+ CardSection(footer = when (mode) {
+ CustomMode.Command -> "Runs on $host in the bot's project folder. Quotes work like in a shell."
+ CustomMode.Url -> "A remote MCP server, streamable HTTP or SSE."
+ CustomMode.Config -> "Paste the MCP config from a README or another app (Claude, Cursor, VS Code). Every server in it is added. Saved on $host only."
+ }) {
+ row { SegmentedChoice(mode, listOf(CustomMode.Command to "Command", CustomMode.Url to "URL", CustomMode.Config to "Config"), { mode = it }) }
+ if (mode == CustomMode.Config) row {
+ PlainInput(config, { config = it }, "{ \"mcpServers\": { … } }", style = Type.callout.monospaced, minLines = 6, maxLines = 16)
+ } else {
+ row { PlainInput(name, { name = it }, "Name") }
+ row { PlainInput(target, { target = it }, if (mode == CustomMode.Url) "https://example.com/mcp" else "npx -y @scope/server", style = Type.callout.monospaced) }
+ }
+ }
+ if (mode == CustomMode.Url) CardSection("Headers", "Optional, one Name: value per line. Leave empty if the service has you sign in. Saved on $host only.") {
+ row { PlainInput(envText, { envText = it }, "Authorization: Bearer …", style = Type.callout.monospaced, minLines = 2, maxLines = 6) }
+ } else if (mode == CustomMode.Command) CardSection("Environment", "One KEY=value per line. Saved on $host only.") {
+ row { PlainInput(envText, { envText = it }, "API_KEY=…", style = Type.callout.monospaced, minLines = 2, maxLines = 6) }
+ }
+ error?.let { CardSection { row { ErrorRow(it) } } }
+ }
+ }
+}
+
+/** Write a skill a bot can follow (iOS `NewSkillSheet`). */
+@Composable internal fun NewSkillSheet(store: AppStore) {
+ val dismiss = LocalDismissModal.current
+ val scope = rememberCoroutineScope()
+ var name by remember { mutableStateOf("") }
+ var summary by remember { mutableStateOf("") }
+ var instructions by remember { mutableStateOf("") }
+ var saving by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf<String?>(null) }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader("New skill") {
+ if (saving) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
+ else IconButton("Save", "checkmark", enabled = name.isNotBlank() && instructions.isNotBlank()) {
+ saving = true; error = null
+ scope.launch {
+ try { store.addSkill(name, summary, instructions); dismiss() }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't save the skill." }
+ finally { saving = false }
+ }
+ }
+ }
+ CardForm(Modifier.weight(1f)) {
+ CardSection(footer = "The bot sees the name and when to use it, and reads the instructions only when a task fits.") {
+ row { PlainInput(name, { name = it }, "Name") }
+ row { PlainInput(summary, { summary = it }, "When to use it", minLines = 2, maxLines = 4) }
+ }
+ CardSection("Instructions") { row { PlainInput(instructions, { instructions = it }, "Step by step, in plain words…", minLines = 6, maxLines = 20) } }
+ error?.let { CardSection { row { ErrorRow(it) } } }
+ }
+ }
+}
+
+/** The skill a details sheet shows: an installed one, or one from the catalog (`source`). */
+internal data class SkillRef(val id: String, val name: String, val description: String, val source: String? = null, val installed: Boolean = true)
+
+/** A skill's details (iOS `SkillSheet`): what it tells the bot, its `SKILL.md`, with Add while it isn't installed. */
+@Composable internal fun SkillSheet(skill: SkillRef, state: AppState, store: AppStore) {
+ val scope = rememberCoroutineScope()
+ var markdown by remember(skill.id) { mutableStateOf<String?>(null) }
+ var error by remember(skill.id) { mutableStateOf<String?>(null) }
+ var adding by remember { mutableStateOf(false) }
+ val added = skill.source == null || skill.installed || state.plugins?.skills?.any { it.id == skill.source.lowercase() } == true
+ LaunchedEffect(skill.id) {
+ try { markdown = store.skillDetails(skill.id, skill.source) }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't load this skill." }
+ }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader(skill.name) {
+ when {
+ added -> Box(Modifier.size(32.dp), contentAlignment = Alignment.Center) { Symbol("checkmark", size = 16.dp, tint = Palette.secondary, contentDescription = "Added") }
+ adding -> Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
+ else -> IconButton("Add", "plus") {
+ adding = true; error = null
+ scope.launch {
+ try { store.installSkill(requireNotNull(skill.source)) }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't add this skill." }
+ finally { adding = false }
+ }
+ }
+ }
+ }
+ CardForm(Modifier.weight(1f)) {
+ if (skill.description.isNotEmpty()) CardSection { row { Text(skill.description, style = Type.subheadline, color = Palette.secondary) } }
+ CardSection("Instructions", if (added) "Bots read these before using the skill." else "Add it to let bots use these instructions.") {
+ row {
+ val text = markdown
+ when {
+ text == null -> if (error == null) Spinner()
+ text.isEmpty() -> Text("No instructions.", style = Type.body, color = Palette.secondary)
+ else -> MarkdownText(text)
+ }
+ }
+ }
+ error?.let { CardSection { row { Text(it, style = Type.footnote, color = Palette.danger) } } }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CrashReports.kt b/apps/android/app/src/main/kotlin/com/codync/android/CrashReports.kt
new file mode 100644
index 00000000..fa3542eb
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CrashReports.kt
@@ -0,0 +1,59 @@
+package com.codync.android
+
+import android.content.Context
+import java.io.File
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonArray
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.put
+
+/**
+ * Crashes as `$exception` events for PostHog Error Tracking (iOS `CrashReports`): an uncaught
+ * exception is written down as it happens and sent on the next launch, with the exception's type
+ * and frames but never its message.
+ */
+internal object CrashReports {
+ private const val MAX_FRAMES = 50
+
+ fun start(context: Context) {
+ val file = File(context.noBackupFilesDir, "crash-report.json")
+ // The previous run's crash, now that analytics is up.
+ if (file.exists()) {
+ runCatching { com.codync.android.core.WireJson.parseToJsonElement(file.readText()).jsonObject }.getOrNull()
+ ?.let { Analytics.record("\$exception", it); Analytics.flush() }
+ file.delete()
+ }
+ val previous = Thread.getDefaultUncaughtExceptionHandler()
+ Thread.setDefaultUncaughtExceptionHandler { thread, error ->
+ runCatching { if (Analytics.enabled) file.writeText(JsonObject(properties(error)).toString()) }
+ previous?.uncaughtException(thread, error)
+ }
+ }
+
+ /** The `$exception` properties for one crash: type and frames, oldest first and the crashing frame last. */
+ internal fun properties(error: Throwable): Map<String, JsonElement> {
+ val frames = error.stackTrace.take(MAX_FRAMES).reversed().map { frame ->
+ buildJsonObject {
+ put("platform", "custom"); put("lang", "kotlin")
+ put("function", "${frame.className}.${frame.methodName}")
+ // A file name only; a path or anything outside Codync's code stays out.
+ frame.fileName?.let { put("filename", it.substringAfterLast('/')) }
+ if (frame.lineNumber > 0) put("lineno", frame.lineNumber)
+ put("in_app", frame.className.startsWith("com.codync."))
+ put("resolved", true)
+ }
+ }
+ val exception = buildJsonObject {
+ put("type", error.javaClass.simpleName.ifEmpty { "Crash" })
+ put("value", "")
+ put("mechanism", buildJsonObject { put("type", "uncaught"); put("handled", false); put("synthetic", false) })
+ put("stacktrace", buildJsonObject { put("type", "raw"); put("frames", JsonArray(frames)) })
+ }
+ return mapOf("\$exception_list" to buildJsonArray { add(exception) }, "\$exception_level" to JsonPrimitive("fatal"),
+ "process" to JsonPrimitive("android"), "app_version" to JsonPrimitive(BuildConfig.VERSION_NAME))
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CredentialsView.kt b/apps/android/app/src/main/kotlin/com/codync/android/CredentialsView.kt
new file mode 100644
index 00000000..99b2cbb6
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CredentialsView.kt
@@ -0,0 +1,165 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.size
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.CredentialStatus
+import com.codync.android.core.InstalledConnector
+import com.codync.android.core.SavedLogin
+import com.codync.android.design.*
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.launch
+
+/** Where the computer keeps secrets (iOS `CredentialsView`): connection keys, sign-ins and 1Password. */
+@Composable internal fun CredentialsView(state: AppState, store: AppStore) {
+ val scope = rememberCoroutineScope()
+ var selected by remember { mutableStateOf<InstalledConnector?>(null) }
+ var token by remember { mutableStateOf("") }
+ var status by remember { mutableStateOf<CredentialStatus?>(null) }
+ var busy by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf<String?>(null) }
+ LaunchedEffect(Unit) {
+ store.refreshPlugins()
+ try { status = store.credentialStatus() }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't reach the credential store." }
+ }
+ fun save(value: String) {
+ busy = true; error = null
+ scope.launch {
+ try { status = store.onePasswordToken(value); token = "" }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "1Password wasn't confirmed." }
+ finally { busy = false }
+ }
+ }
+ val saved = state.plugins?.connectors.orEmpty().filter { it.keys.isNotEmpty() }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader("Credentials")
+ CardForm(Modifier.weight(1f)) {
+ CardSection("Storage") {
+ row { Text(status?.provider ?: "System credential store", style = Type.body, color = Palette.text) }
+ row { Text("Encrypted on the connected computer.", style = Type.body, color = Palette.secondary) }
+ }
+ CardSection("Saved connections") {
+ for (connector in saved) row {
+ Row(Modifier.fillMaxWidth().plainButton { selected = connector }, verticalAlignment = Alignment.CenterVertically) {
+ Text(connector.name, Modifier.weight(1f), style = Type.body, color = Palette.text)
+ Symbol("chevron.right", size = 13.dp, tint = Palette.tertiary)
+ }
+ }
+ if (saved.isEmpty()) row { Text("No saved connection credentials yet.", style = Type.caption, color = Palette.secondary) }
+ row { Text("Values stay hidden. Select a connection to replace its credentials.", style = Type.caption, color = Palette.secondary) }
+ }
+ LoginsSection(store)
+ CardSection("1Password", "Use a service account with read access only to a dedicated shared vault. The 1Password CLI must be installed on the computer.") {
+ row { Text(if (status?.onePasswordConnected == true) "Connected" else "Connect a shared vault", style = Type.body, color = Palette.text) }
+ row { FieldRow("Service account token") { PlainInput(token, { token = it }, "Paste your token", secret = true) } }
+ row {
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ PrimaryButton("Connect", enabled = !busy && token.isNotEmpty()) { save(token) }
+ if (status?.onePasswordConnected == true) SecondaryButton("Disconnect", enabled = !busy) { save("") }
+ }
+ }
+ row {
+ Text("Use op://vault/item/field in a connector's credential field. Codync retrieves the value when the connector runs.",
+ style = Type.footnote, color = Palette.secondary)
+ }
+ }
+ if (busy) Spinner()
+ error?.let { ErrorRow(it) }
+ }
+ }
+ CodyncSheet(selected, { selected = null }) { ConnectorCredentialEditor(it, store) }
+}
+
+/** Website and app logins bots type through the computer tool; passwords stay hidden. */
+@Composable private fun LoginsSection(store: AppStore) {
+ val scope = rememberCoroutineScope()
+ var logins by remember { mutableStateOf(emptyList<SavedLogin>()) }
+ var site by remember { mutableStateOf("") }
+ var username by remember { mutableStateOf("") }
+ var password by remember { mutableStateOf("") }
+ var busy by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf<String?>(null) }
+ suspend fun load() {
+ try { logins = store.savedLogins() }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't load sign-ins." }
+ }
+ LaunchedEffect(Unit) { load() }
+ fun run(work: suspend () -> Unit) {
+ busy = true; error = null
+ scope.launch {
+ try { work() }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "That didn't go through." }
+ finally { busy = false }
+ }
+ }
+ CardSection("Sign-ins", "Bots type these into the matching website or app and never see the password. You can use an op:// reference.") {
+ for (login in logins) row {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(login.site, style = Type.body, color = Palette.text)
+ if (login.username.isNotEmpty()) Text(login.username, style = Type.caption, color = Palette.secondary)
+ }
+ IconButton("Remove", "trash", enabled = !busy) { run { store.removeLogin(login.id); logins = logins - login } }
+ }
+ }
+ row { FieldRow("Website or app") { PlainInput(site, { site = it }, "github.com") } }
+ row { FieldRow("Username or email") { PlainInput(username, { username = it }, "[email protected]") } }
+ row { FieldRow("Password") { PlainInput(password, { password = it }, "Password or op:// reference", secret = true) } }
+ row {
+ PrimaryButton("Save sign-in", enabled = !busy && site.isNotEmpty() && password.isNotEmpty()) {
+ run { store.saveLogin(site, username, password); site = ""; username = ""; password = ""; load() }
+ }
+ }
+ error?.let { row { Text(it, style = Type.footnote, color = Palette.danger) } }
+ }
+}
+
+/** Replaces a connection's saved values; blank fields keep what's saved (iOS `ConnectorCredentialEditor`). */
+@Composable private fun ConnectorCredentialEditor(connector: InstalledConnector, store: AppStore) {
+ val dismiss = LocalDismissModal.current
+ val scope = rememberCoroutineScope()
+ var fields by remember(connector.id) { mutableStateOf(emptyMap<String, String>()) }
+ var saving by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf<String?>(null) }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader(connector.name) {
+ if (saving) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
+ else IconButton("Save credentials", "checkmark", enabled = fields.values.any(String::isNotEmpty)) {
+ saving = true; error = null
+ scope.launch {
+ try { store.updateConnectorCredentials(connector, fields.filterValues(String::isNotEmpty)); fields = emptyMap(); dismiss() }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "The updated credentials weren't verified." }
+ finally { saving = false }
+ }
+ }
+ }
+ CardForm(Modifier.weight(1f)) {
+ CardSection(footer = "Enter only the values you want to replace. You can use an op:// reference.") {
+ for (key in connector.keys) row { PlainInput(fields[key].orEmpty(), { fields = fields + (key to it) }, key, secret = true) }
+ }
+ error?.let { ErrorRow(it) }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/DraftBook.kt b/apps/android/app/src/main/kotlin/com/codync/android/DraftBook.kt
new file mode 100644
index 00000000..c7d6a436
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/DraftBook.kt
@@ -0,0 +1,74 @@
+package com.codync.android
+
+import android.util.AtomicFile
+import com.codync.android.core.MAX_FILE_BYTES
+import com.codync.android.core.MirrorSnapshot
+import com.codync.android.core.OutgoingFile
+import com.codync.android.core.WireJson
+import java.io.File
+import java.util.UUID
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.encodeToString
+import kotlinx.serialization.json.*
+
+@Serializable
+data class ComposerDraft(val botId: String, val threadId: String? = null, val text: String = "",
+ val files: List<OutgoingFile> = emptyList(), val nonce: String = UUID.randomUUID().toString()) {
+ val lane: String get() = lane(botId, threadId)
+ companion object {
+ fun lane(botId: String, threadId: String?): String = JsonArray(listOf(JsonPrimitive(botId), threadId?.let(::JsonPrimitive) ?: JsonNull)).toString()
+ }
+}
+
+/** One bounded draft book per account/computer; a draft's nonce also identifies its durable send. */
+class DraftBook(private val directory: File, computerId: String) {
+ private val file: AtomicFile
+ init {
+ require(computerId.matches(Regex("[A-Za-z0-9_-]{22}")))
+ file = AtomicFile(File(directory, "drafts-$computerId.json"))
+ }
+
+ @Synchronized fun read(): List<ComposerDraft> {
+ if (!file.baseFile.exists()) return emptyList()
+ require(file.baseFile.length() <= MAX_BYTES) { "The saved drafts are too large." }
+ val drafts = WireJson.decodeFromString<List<ComposerDraft>>(file.readFully().toString(Charsets.UTF_8))
+ validate(drafts)
+ return drafts
+ }
+
+ /** A crash between pending-send commit and draft removal cannot offer the same draft twice. */
+ @Synchronized fun recover(snapshot: MirrorSnapshot): List<ComposerDraft> {
+ val queued = snapshot.pending.map { it.nonce }.toSet() + snapshot.entries.mapNotNull { it.clientNonce }
+ val drafts = read().filter { it.nonce !in queued }
+ save(drafts)
+ return drafts
+ }
+
+ @Synchronized fun save(drafts: Collection<ComposerDraft>) {
+ validate(drafts)
+ if (drafts.isEmpty()) { file.delete(); return }
+ val bytes = WireJson.encodeToString(drafts.toList()).toByteArray()
+ require(bytes.size <= MAX_BYTES) { "The saved drafts are too large." }
+ val output = file.startWrite()
+ try { output.write(bytes); file.finishWrite(output) }
+ catch (error: Throwable) { file.failWrite(output); throw error }
+ }
+
+ fun validate(drafts: Collection<ComposerDraft>, checkPaths: Boolean = true) {
+ require(drafts.size <= 64) { "Too many drafts. Send or clear an older draft first." }
+ require(drafts.map { it.lane }.distinct().size == drafts.size) { "The saved drafts contain duplicate conversations." }
+ val outgoing = if (checkPaths) File(directory, "outgoing").canonicalFile else null
+ for (draft in drafts) {
+ require(draft.botId.isNotBlank() && draft.botId.length <= 128 && (draft.threadId == null || draft.threadId.isNotBlank() && draft.threadId.length <= 128))
+ require(UUID.fromString(draft.nonce).toString() == draft.nonce) { "A saved draft has an invalid message ID." }
+ require(draft.text.toByteArray().size <= 64 * 1024) { "Draft messages must be 64 KiB or smaller." }
+ require(draft.files.size <= 20) { "Choose at most 20 files for one message." }
+ for (attachment in draft.files) {
+ require(attachment.size in 0..MAX_FILE_BYTES && attachment.name.isNotBlank())
+ if (checkPaths) require(File(attachment.path).canonicalFile.parentFile == outgoing) { "A draft attachment belongs to another account." }
+ }
+ }
+ }
+
+ companion object { private const val MAX_BYTES = 8 * 1024 * 1024 }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/EditorControls.kt b/apps/android/app/src/main/kotlin/com/codync/android/EditorControls.kt
new file mode 100644
index 00000000..74da751b
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/EditorControls.kt
@@ -0,0 +1,100 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.selected
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.input.KeyboardCapitalization
+import androidx.compose.ui.unit.dp
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+
+// The settings-form pieces of iOS `BotEditorView`: labelled fields, switch rows, the avatar
+// picker and the connector/skill toggles.
+
+/** A labeled input inside a section row: label (and an optional note) over the field. */
+@Composable internal fun Field(label: String, detail: String? = null, content: @Composable () -> Unit) {
+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {
+ Text(label, style = Type.body, color = Palette.text)
+ if (detail != null) Text(detail, style = Type.caption.copy(lineHeight = Type.caption.lineHeight * 1.12f), color = Palette.secondary)
+ }
+ content()
+ }
+}
+
+/** A rounded input box (`fieldBox`): a plain field on the ground color. */
+@Composable internal fun FieldBox(text: String, onChange: (String) -> Unit, prompt: String, minLines: Int = 1, maxLines: Int = 1,
+ style: TextStyle = Type.body, fill: Color = Palette.background, capitalize: Boolean = true, imeAction: ImeAction = ImeAction.Default,
+ actions: KeyboardActions = KeyboardActions.Default) {
+ Box(Modifier.fillMaxWidth().clip(RoundedRectangle(12.dp)).background(fill).padding(horizontal = 14.dp, vertical = 11.dp)) {
+ PlainTextField(text, onChange, Modifier.fillMaxWidth(), prompt, singleLine = maxLines == 1, style = style, minLines = minLines,
+ maxLines = maxLines, keyboard = KeyboardOptions(capitalization = if (capitalize) KeyboardCapitalization.Sentences else KeyboardCapitalization.None,
+ autoCorrectEnabled = capitalize, imeAction = imeAction), actions = actions)
+ }
+}
+
+/** An on/off row: title and a short note, the switch on the right. */
+@Composable internal fun SwitchRow(title: String, detail: String? = null, isOn: Boolean, onChange: (Boolean) -> Unit, enabled: Boolean = true) {
+ CodyncSwitch(isOn, onChange, Modifier.fillMaxWidth(), enabled) {
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
+ Text(title, style = Type.body, color = Palette.text)
+ if (detail != null) Text(detail, style = Type.caption.copy(lineHeight = Type.caption.lineHeight * 1.12f), color = Palette.secondary)
+ }
+ }
+}
+
+/** The bot's face: a row of shapes over a row of colors, each with a ring when chosen. */
+@Composable internal fun AvatarPicker(shape: String, color: String, chooseShape: (String) -> Unit, chooseColor: (String) -> Unit) {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Row(Modifier.horizontalScroll(rememberScrollState()).padding(4.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ for (option in AvatarPalette.shapes) Box(Modifier.clip(Capsule()).border(2.dp, if (option == shape) Palette.accent else Color.Transparent, Capsule())
+ .clickable(role = Role.RadioButton) { chooseShape(option) }.semantics { contentDescription = "$option shape"; selected = option == shape }
+ .padding(4.dp)) { CharacterAvatar(option, color, 36.dp) }
+ }
+ Row(Modifier.horizontalScroll(rememberScrollState()).padding(4.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ for ((id, hex) in AvatarPalette.colors) Box(Modifier.clip(Capsule()).border(2.dp, if (id == color) Palette.accent else Color.Transparent, Capsule())
+ .clickable(role = Role.RadioButton) { chooseColor(id) }.semantics { contentDescription = id.replaceFirstChar(Char::uppercase); selected = id == color }
+ .padding(4.dp)) { Box(Modifier.size(26.dp).clip(Capsule()).background(Color(hex))) }
+ }
+ }
+}
+
+/** A card of on/off switches for the connectors or skills installed on the computer. */
+@Composable internal fun PluginToggles(title: String, empty: String, items: List<Triple<String, String, String>>, selection: List<String>,
+ change: (List<String>) -> Unit, info: ((String) -> Unit)? = null) {
+ CardSection(title) {
+ if (items.isEmpty()) row { Text(empty, style = Type.body, color = Palette.secondary) }
+ for ((id, name, detail) in items) row {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ Box(Modifier.weight(1f)) {
+ SwitchRow(name, detail.ifEmpty { null }, id in selection, { on -> change(selection.filter { it != id } + if (on) listOf(id) else emptyList()) })
+ }
+ if (info != null) IconButton("About $name", "info.circle") { info(id) }
+ }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/FolderPicker.kt b/apps/android/app/src/main/kotlin/com/codync/android/FolderPicker.kt
new file mode 100644
index 00000000..8dd0eba6
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/FolderPicker.kt
@@ -0,0 +1,94 @@
+package com.codync.android
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.slideInHorizontally
+import androidx.compose.animation.slideOutHorizontally
+import androidx.compose.animation.togetherWith
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.DirListing
+import com.codync.android.design.*
+import kotlinx.coroutines.CancellationException
+
+/** Browses folders on the computer, drilling down in place (iOS `FolderPicker`). */
+@Composable internal fun FolderPicker(start: String?, online: Boolean, load: suspend (String?) -> DirListing, pick: (String) -> Unit) {
+ var stack by remember { mutableStateOf(listOf(start)) }
+ var forward by remember { mutableStateOf(true) }
+ BackHandler(stack.size > 1) { forward = false; stack = stack.dropLast(1) }
+ Column(Modifier.fillMaxSize()) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ if (stack.size > 1) Box(Modifier.padding(start = 12.dp)) { BackButton { forward = false; stack = stack.dropLast(1) } }
+ Box(Modifier.weight(1f)) { ModalHeader(stack.last()?.trimEnd('/')?.substringAfterLast('/')?.ifEmpty { "/" } ?: "Folders") }
+ }
+ AnimatedContent(stack, transitionSpec = {
+ val sign = if (forward) 1 else -1
+ slideInHorizontally(Motion.layoutOffset) { it * sign } togetherWith slideOutHorizontally(Motion.layoutOffset) { -it * sign }
+ }, label = "Folder") { shown ->
+ FolderLevel(shown.last(), online, load, pick) { forward = true; stack = stack + it }
+ }
+ }
+}
+
+/** One folder's subfolders, filterable, with "Use" on top. */
+@Composable private fun FolderLevel(path: String?, online: Boolean, load: suspend (String?) -> DirListing, pick: (String) -> Unit, open: (String) -> Unit) {
+ var listing by remember { mutableStateOf<DirListing?>(null) }
+ var error by remember { mutableStateOf<String?>(null) }
+ var filter by remember { mutableStateOf("") }
+ LaunchedEffect(path, online) {
+ if (!online) { error = "Connect to this computer to browse its folders."; return@LaunchedEffect }
+ try { listing = load(path); error = null }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't open this folder." }
+ }
+ Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(22.dp)) {
+ SearchField(filter, { filter = it })
+ val current = listing
+ when {
+ current != null -> {
+ CardSection(footer = current.path) {
+ row {
+ Row(Modifier.fillMaxWidth().plainButton { pick(current.path) }, verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol("checkmark.circle.fill", size = 20.dp, tint = Palette.accent)
+ Text("Use “${current.path.trimEnd('/').substringAfterLast('/').ifEmpty { "/" }}”", style = Type.headline, color = Palette.accent)
+ }
+ }
+ }
+ val dirs = current.dirs.filter { filter.isBlank() || it.name.contains(filter.trim(), ignoreCase = true) }
+ if (dirs.isNotEmpty()) CardSection {
+ for (dir in dirs) row {
+ Row(Modifier.fillMaxWidth().plainButton { open(dir.path) }, verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Box(Modifier.width(20.dp), contentAlignment = Alignment.Center) {
+ Symbol(if (dir.isGit) "arrow.triangle.branch" else "folder", size = 18.dp, tint = if (dir.isGit) Palette.accent else Palette.secondary)
+ }
+ Text(dir.name, Modifier.weight(1f), style = Type.body, color = Palette.text, maxLines = 1)
+ Symbol("chevron.right", size = 13.dp, tint = Palette.tertiary)
+ }
+ }
+ }
+ }
+ error != null -> Text(error.orEmpty(), style = Type.body, color = Palette.danger)
+ else -> Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { Spinner(20.dp) }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/GroupEditor.kt b/apps/android/app/src/main/kotlin/com/codync/android/GroupEditor.kt
new file mode 100644
index 00000000..7bed9512
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/GroupEditor.kt
@@ -0,0 +1,110 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.animateContentSize
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Bot
+import com.codync.android.core.GroupDraft
+import com.codync.android.design.*
+
+/**
+ * Create a group chat, or change its name, what it's for and who's in it (iOS `GroupEditorView`).
+ * Bots are picked like recipients: members on top, a search, and the bots not in it yet.
+ */
+@Composable internal fun GroupEditor(state: AppState, initial: GroupDraft, store: AppStore) {
+ val dismiss = LocalDismissModal.current
+ var draft by remember(initial.id) { mutableStateOf(initial) }
+ var query by remember { mutableStateOf("") }
+ // A new group starts in the picker; an existing one shows its members first.
+ var adding by remember { mutableStateOf(initial.id == null && initial.members.isEmpty()) }
+ var confirmDelete by remember { mutableStateOf(false) }
+ val saving = "editor" in state.busy
+ val picked = draft.members.mapNotNull { id -> state.bots.firstOrNull { it.id == id } }
+ val candidates = roster(state.bots).filter { it.kind != "group" && it.id !in draft.members && it.name.contains(query.trim(), ignoreCase = true) }
+ val defaultName = picked.joinToString(", ") { it.name }.ifEmpty { "Name" }
+ fun toggle(id: String) {
+ draft = draft.copy(members = if (id in draft.members) draft.members - id else draft.members + id)
+ query = ""
+ }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader(if (draft.id == null) "New group chat" else "Group chat") {
+ if (saving) Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { Spinner() }
+ else IconButton(if (draft.id == null) "Create" else "Save", "checkmark", enabled = draft.members.isNotEmpty()) {
+ store.saveGroup(draft) { dismiss() }
+ }
+ }
+ Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(start = 20.dp, end = 20.dp, top = 8.dp, bottom = 24.dp),
+ verticalArrangement = Arrangement.spacedBy(28.dp)) {
+ Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ GroupAvatar(picked.map { AvatarFace(it.avatarShape, it.avatarColor, it.status) }, 84.dp)
+ PlainTextField(draft.name, { draft = draft.copy(name = it) }, Modifier.fillMaxWidth().padding(top = 6.dp), defaultName, singleLine = true,
+ style = Type.title2.semibold.copy(textAlign = TextAlign.Center))
+ PlainTextField(draft.description, { draft = draft.copy(description = it) }, Modifier.fillMaxWidth(), "What this group works on",
+ style = Type.subheadline.copy(textAlign = TextAlign.Center, color = Palette.secondary), maxLines = 4)
+ }
+ Column(Modifier.fillMaxWidth().animateContentSize(Motion.layoutSize)) {
+ Text("Members", Modifier.padding(bottom = 4.dp), style = Type.subheadline.semibold, color = Palette.secondary)
+ for (bot in picked) MemberRow(bot, state.bots) { IconButton("Remove ${bot.name}", "xmark") { toggle(bot.id) } }
+ if (adding) {
+ Box(Modifier.padding(vertical = 6.dp)) {
+ FieldBox(query, { query = it }, "Search bots", fill = Palette.surface, imeAction = ImeAction.Done,
+ actions = KeyboardActions(onDone = { candidates.firstOrNull()?.let { toggle(it.id) } }))
+ }
+ for (bot in candidates) Box(Modifier.plainButton { toggle(bot.id) }.semantics(mergeDescendants = true) { contentDescription = "Add ${bot.name}" }) {
+ MemberRow(bot, state.bots, dimmed = true) { Symbol("plus.circle", size = 20.dp, tint = Palette.secondary) }
+ }
+ } else if (candidates.isNotEmpty()) Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).plainButton { adding = true },
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ Box(Modifier.width(32.dp), contentAlignment = Alignment.Center) { Symbol("plus", size = 18.dp, tint = Palette.secondary) }
+ Text("Add Member", style = Type.body, color = Palette.secondary)
+ }
+ Text("Everyone answers in turn unless you @mention someone.", Modifier.padding(top = 10.dp), style = Type.caption, color = Palette.tertiary)
+ }
+ AnimatedVisibility(state.error != null, enter = fadeIn(Motion.fade()), exit = fadeOut(Motion.fade())) {
+ Text(state.error.orEmpty(), style = Type.footnote, color = Palette.danger)
+ }
+ if (draft.id != null) LinkButton("Delete group chat", color = Palette.danger) { confirmDelete = true }
+ }
+ }
+ val group = state.bots.firstOrNull { it.id == draft.id }
+ CodyncDialog("Delete ${group?.name ?: "group chat"}?", confirmDelete, { confirmDelete = false }, "Its bots and their own chats stay.") {
+ listOf(DialogAction("Delete group chat", destructive = true) { group?.let { store.deleteBot(it) { dismiss() } } })
+ }
+}
+
+/** A member or candidate: avatar, name, and a trailing control. */
+@Composable private fun MemberRow(bot: Bot, bots: List<Bot>, dimmed: Boolean = false, trailing: @Composable () -> Unit) {
+ Row(Modifier.fillMaxWidth().heightIn(min = 48.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ BotAvatar(bot, bots, 32.dp)
+ Text(bot.name, Modifier.weight(1f), style = Type.body, color = if (dimmed) Palette.secondary else Palette.text, maxLines = 1)
+ trailing()
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/InstalledView.kt b/apps/android/app/src/main/kotlin/com/codync/android/InstalledView.kt
new file mode 100644
index 00000000..64ddeeb4
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/InstalledView.kt
@@ -0,0 +1,94 @@
+package com.codync.android
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.size
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.design.*
+import java.io.IOException
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.launch
+
+private data class Removal(val id: String, val name: String, val skill: Boolean)
+
+/** What's installed on the computer: connectors (sign in, remove) and skills (details, remove) (iOS `InstalledView`). */
+@Composable internal fun InstalledView(state: AppState, store: AppStore, back: () -> Unit) {
+ val scope = rememberCoroutineScope()
+ var removing by remember { mutableStateOf<Removal?>(null) }
+ var signingIn by remember { mutableStateOf<String?>(null) }
+ var viewingSkill by remember { mutableStateOf<SkillRef?>(null) }
+ var error by remember { mutableStateOf<String?>(null) }
+ val connectors = state.plugins?.connectors.orEmpty()
+ val skills = state.plugins?.skills.orEmpty()
+ BackHandler(onBack = back)
+ fun run(work: suspend () -> Unit) = scope.launch {
+ error = null
+ try { work() }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "That didn't go through." }
+ }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ScreenHeader({ BackButton(back) }, { Text("Connectors & skills", style = Type.body.semibold, color = Palette.text) })
+ CardForm(Modifier.weight(1f)) {
+ if (connectors.isEmpty() && skills.isEmpty()) MarketEmpty("shippingbox", "Nothing installed", "Connectors and skills you add show up here.")
+ if (connectors.isNotEmpty()) CardSection("Connectors") {
+ for (c in connectors) row {
+ InstalledRow(c.name, if (c.needsSignIn) "Sign in so bots can use it" else c.command ?: c.url ?: c.description, icon = {
+ if (c.kind == "composio") AppLogo(c.logo, c.name, 32.dp) else ServiceLogo(null, c.name, c.registryName, 32.dp)
+ }, accessory = {
+ if (signingIn == c.id) Spinner()
+ else if (c.needsSignIn) PrimaryButton("Sign in") {
+ signingIn = c.id
+ run { try { if (!store.signInConnector(c.id)) throw IOException("Sign-in to ${c.name} wasn't confirmed.") } finally { signingIn = null } }
+ }
+ }) { removing = Removal(c.id, c.name, skill = false) }
+ }
+ }
+ if (skills.isNotEmpty()) CardSection("Skills") {
+ for (s in skills) row {
+ InstalledRow(s.name, s.description, { viewingSkill = SkillRef(s.id, s.name, s.description) },
+ icon = { Box(Modifier.size(32.dp)) { SkillGlyph() } }) { removing = Removal(s.id, s.name, skill = true) }
+ }
+ }
+ error?.let { ErrorRow(it) }
+ }
+ }
+ val target = removing
+ CodyncDialog("Remove ${target?.name.orEmpty()}?", target != null, { removing = null },
+ if (target?.skill == true) "Bots stop using this skill." else "Bots lose this connector, and the keys saved for it are deleted.") {
+ listOf(DialogAction("Remove", destructive = true) { target?.let { r -> run { store.removePlugin(if (r.skill) "removeSkill" else "removeConnector", r.id) } } })
+ }
+ CodyncSheet(viewingSkill, { viewingSkill = null }) { SkillSheet(it, state, store) }
+}
+
+@Composable private fun InstalledRow(title: String, subtitle: String, open: (() -> Unit)? = null, icon: @Composable () -> Unit,
+ accessory: @Composable () -> Unit = {}, remove: () -> Unit) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Row(Modifier.weight(1f).then(if (open != null) Modifier.plainButton(action = open) else Modifier), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ icon()
+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(title, style = Type.body, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(subtitle, style = Type.caption, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ }
+ accessory()
+ IconButton("Remove $title", "trash", action = remove)
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/LaunchSplash.kt b/apps/android/app/src/main/kotlin/com/codync/android/LaunchSplash.kt
new file mode 100644
index 00000000..cc93ad42
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/LaunchSplash.kt
@@ -0,0 +1,69 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.EnterTransition
+import androidx.compose.animation.core.Animatable
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.scaleOut
+import androidx.compose.animation.core.LinearEasing
+import androidx.compose.animation.core.RepeatMode
+import androidx.compose.animation.core.Spring
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.infiniteRepeatable
+import androidx.compose.animation.core.rememberInfiniteTransition
+import androidx.compose.animation.core.spring
+import androidx.compose.animation.core.tween
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import kotlinx.coroutines.delay
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.unit.dp
+import com.codync.android.design.CharacterAvatar
+import com.codync.android.design.Palette
+import com.codync.android.design.reduceMotion
+import kotlin.math.PI
+import kotlin.math.sin
+
+/**
+ * Cold launch, as iOS `LaunchSplash`: the app-icon bot pops out of the blank system splash and
+ * looks around while the computer catches up, then grows a little as it fades into the app.
+ */
+/** The splash over the app until the store is ready, held at least 0.7 s so the motion reads. */
+@Composable internal fun LaunchLayer(loading: Boolean) {
+ var visible by remember { mutableStateOf(true) }
+ val started = remember { System.currentTimeMillis() }
+ LaunchedEffect(loading) {
+ if (!loading) { delay(maxOf(0L, 700 - (System.currentTimeMillis() - started))); visible = false }
+ }
+ AnimatedVisibility(visible, enter = EnterTransition.None,
+ exit = fadeOut(tween(300)) + scaleOut(tween(300), targetScale = if (reduceMotion()) 1f else 1.15f)) { LaunchSplash() }
+}
+
+@Composable private fun LaunchSplash() {
+ val still = reduceMotion()
+ val shown = remember { Animatable(if (still) 1f else 0.6f) }
+ val opacity = remember { Animatable(0f) }
+ LaunchedEffect(Unit) {
+ opacity.animateTo(1f, tween(200))
+ }
+ LaunchedEffect(Unit) { shown.animateTo(1f, spring(dampingRatio = 0.55f, stiffness = 158f)) }
+ val bob by rememberInfiniteTransition(label = "Bob").animateFloat(0f, 1f,
+ infiniteRepeatable(tween((2 * PI / 2.4 * 1000).toInt(), easing = LinearEasing), RepeatMode.Restart), label = "Phase")
+ Box(Modifier.fillMaxSize().background(Palette.background).semantics { contentDescription = "Connecting" }, contentAlignment = Alignment.Center) {
+ Box(Modifier.graphicsLayer {
+ scaleX = shown.value; scaleY = shown.value; alpha = opacity.value
+ translationY = if (still) 0f else sin(bob * 2 * PI).toFloat() * 4.dp.toPx()
+ }) { CharacterAvatar("squircle", "gray", 112.dp, status = "working", monochrome = Palette.text) }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/LiveUpdateGallery.kt b/apps/android/app/src/main/kotlin/com/codync/android/LiveUpdateGallery.kt
new file mode 100644
index 00000000..0d9316ec
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/LiveUpdateGallery.kt
@@ -0,0 +1,245 @@
+package com.codync.android
+
+import android.app.NotificationManager
+import android.content.Context
+import android.content.Intent
+import android.os.Build
+import android.provider.Settings
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.animateContentSize
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.slideInVertically
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableLongStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.unit.dp
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.coroutines.delay
+
+/** A sample task's phase, as iOS `BotActivityPresentation.Phase`. */
+internal enum class TaskPhase(val title: String) {
+ Sending("Sending"), Queued("Waiting for your computer"), Working("Working"), NeedsInput("Needs you"),
+ Completed("Done"), Failed("Failed"), Stale("Update delayed");
+
+ val live get() = this == Working || this == NeedsInput
+}
+
+@Composable internal fun TaskPhase.tint(): Color = when (this) {
+ TaskPhase.NeedsInput -> Palette.attention
+ TaskPhase.Failed -> Palette.danger
+ TaskPhase.Completed -> Palette.added
+ TaskPhase.Working -> Palette.text
+ else -> Palette.secondary
+}
+
+/** Live updates (on Android 16, promoted ongoing notifications) are what iOS calls Live Activities. */
+internal object LiveUpdates {
+ /** Promoted notifications (Live updates, the status bar chip) need Android 16 QPR1. */
+ val supported: Boolean get() = Build.VERSION.SDK_INT >= 36 && Build.VERSION.SDK_INT_FULL >= Build.VERSION_CODES_FULL.BAKLAVA_1
+
+ /** Android lets the user turn promotion off per app. */
+ fun promoted(context: Context): Boolean = supported &&
+ context.getSystemService(NotificationManager::class.java).canPostPromotedNotifications()
+
+ fun openSettings(context: Context) {
+ val action = if (supported) Settings.ACTION_APP_NOTIFICATION_PROMOTION_SETTINGS else Settings.ACTION_APP_NOTIFICATION_SETTINGS
+ context.startActivity(Intent(action).putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ }
+}
+
+/**
+ * The Live update and Status bar pages: one switch (the chip shows the same Live update), a
+ * sample task in any phase, and what each presentation shows.
+ */
+@Composable internal fun LiveUpdateGallery(state: AppState, store: AppStore?, chip: Boolean) {
+ val context = LocalContext.current
+ val notifications = rememberOnResume { notificationsAllowed(context) }
+ val promoted = rememberOnResume { LiveUpdates.promoted(context) }
+ var phase by rememberSaveable { mutableStateOf(TaskPhase.Working) }
+ val started = remember { System.currentTimeMillis() - 154_000 }
+ Column(Modifier.fillMaxWidth().clip(RoundedRectangle(20.dp)).background(Palette.surface).padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ CodyncSwitch(state.tasks, { store?.taskNotifications(it) }) {
+ Text(if (chip) "Show in the status bar" else "Show Live updates", style = Type.subheadline.medium, color = Palette.text)
+ }
+ Text(if (chip) "The status bar chip shows the same Live update as the Lock Screen, so this switch turns off both."
+ else "Starts when you send a task from this phone. Follow its progress, then open the conversation when your bot needs you.",
+ style = Type.footnote, color = Palette.secondary)
+ when {
+ !notifications -> SettingsNote("Notifications are turned off in Android settings.") { openNotificationSettings(context) }
+ !LiveUpdates.supported -> Text("On this Android version a task shows as an ongoing notification. Live updates and the status bar chip need Android 16 QPR1.",
+ style = Type.footnote, color = Palette.secondary)
+ !promoted -> SettingsNote("Live updates are turned off for Codync in Android settings.") { LiveUpdates.openSettings(context) }
+ }
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text("Preview", Modifier.weight(1f), style = Type.subheadline.medium, color = Palette.text)
+ Text("Sample task", style = Type.caption, color = Palette.secondary)
+ }
+ ChoicePicker(phase, listOf(TaskPhase.Sending to "Sending", TaskPhase.Queued to "Waiting for computer", TaskPhase.Working to "Working",
+ TaskPhase.NeedsInput to "Needs you", TaskPhase.Completed to "Done", TaskPhase.Failed to "Error", TaskPhase.Stale to "Update delayed"), { phase = it })
+ Box(Modifier.fillMaxWidth().heightIn(min = 90.dp).clip(RoundedRectangle(28.dp)).background(Palette.bubbleAgent).padding(12.dp),
+ contentAlignment = Alignment.Center) {
+ if (chip) StatusBarPreview(phase, started) else LiveUpdatePreview(phase, started)
+ }
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
+ if (chip) {
+ Explanation("Chip", "The bot and its running time beside the clock, in the state's color. It becomes a check or a warning when the task ends.")
+ Explanation("Tap", "Tap the chip to see the task's Live update; tap that to open the conversation.")
+ } else {
+ Explanation("Lock Screen and notifications", "The bot in its mood, its current step in the state's color, the running time and progress. When the bot needs you, Review opens the request.")
+ }
+ }
+ Text("Android chooses how Live updates appear based on your device and other tasks. These previews don't start one. Approvals are handled inside Codync.",
+ style = Type.footnote, color = Palette.secondary)
+}
+
+@Composable private fun SettingsNote(text: String, open: () -> Unit) {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(text, style = Type.footnote, color = Palette.secondary)
+ LinkButton("Open Android settings", style = Type.footnote.medium, color = Palette.accent, action = open)
+ }
+}
+
+@Composable private fun Explanation(title: String, detail: String) {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ SectionTitle(title)
+ Text(detail, style = Type.footnote, color = Palette.secondary)
+ }
+}
+
+@Composable private fun SectionTitle(title: String) = Text(title, style = Type.subheadline.medium, color = Palette.text)
+
+/** The step (or state) in its color, then the running time while the task is live. */
+@Composable private fun Caption(phase: TaskPhase, started: Long) {
+ val caption = if (phase.live) (if (phase == TaskPhase.NeedsInput) "Review the proposed changes." else "Running the test suite.") else phase.title
+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(caption, Modifier.weight(1f, fill = false), style = Type.system(12f), color = if (phase == TaskPhase.Working) Palette.secondary else phase.tint(), maxLines = 1)
+ if (phase.live) {
+ Text("·", style = Type.system(12f), color = Palette.tertiary)
+ Text(elapsed(started), style = Type.system(12f).monospacedDigit, color = Palette.secondary)
+ }
+ }
+}
+
+@Composable private fun elapsed(started: Long): String {
+ var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
+ LaunchedEffect(started) { while (true) { now = System.currentTimeMillis(); delay(1000) } }
+ val seconds = (now - started) / 1000
+ return "%d:%02d".format(seconds / 60, seconds % 60)
+}
+
+/** The end mark: a thinking orb while it runs, a check or a warning once it ends. */
+@Composable private fun PhaseMark(phase: TaskPhase, size: androidx.compose.ui.unit.Dp) {
+ when (phase) {
+ TaskPhase.Completed -> Symbol("checkmark", size = size, tint = phase.tint())
+ TaskPhase.Failed -> Symbol("exclamationmark.triangle.fill", size = size, tint = phase.tint())
+ TaskPhase.Queued -> Symbol("desktopcomputer", size = size, tint = phase.tint())
+ else -> ThinkingOrb(when (phase) { TaskPhase.Working -> ThinkingOrbState.Working; TaskPhase.NeedsInput -> ThinkingOrbState.Listening
+ else -> ThinkingOrbState.Connecting }, size, phase.tint())
+ }
+}
+
+private val TaskPhase.mood get() = when (this) { TaskPhase.Working -> "working"; TaskPhase.NeedsInput -> "needsInput"; else -> "idle" }
+
+/** The Lock Screen Live update: app and time, the bot in its mood, its step, a progress line, Review when it needs you. */
+@Composable private fun LiveUpdatePreview(phase: TaskPhase, started: Long) {
+ Column(Modifier.fillMaxWidth().clip(RoundedRectangle(22.dp)).background(Palette.surface).padding(14.dp).animateContentSize(Motion.layoutSize),
+ verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Box(Modifier.size(18.dp).clip(Capsule()).background(Palette.accentFill), contentAlignment = Alignment.Center) {
+ androidx.compose.foundation.Image(painterResource(R.drawable.ic_notification), null, Modifier.size(12.dp),
+ colorFilter = androidx.compose.ui.graphics.ColorFilter.tint(Palette.onAccent))
+ }
+ Text(androidx.compose.ui.res.stringResource(R.string.app_name), style = Type.caption.medium, color = Palette.secondary)
+ Text("· now", style = Type.caption, color = Palette.tertiary)
+ }
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ CharacterAvatar("blob", "green", 40.dp, phase.mood)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text("Reviewer", style = Type.system(14f).semibold, color = Palette.text, maxLines = 1)
+ Caption(phase, started)
+ }
+ PhaseMark(phase, 20.dp)
+ }
+ ProgressLine(phase)
+ AnimatedVisibility(phase == TaskPhase.NeedsInput, enter = fadeIn(Motion.fade()) + slideInVertically { it / 2 }, exit = fadeOut(Motion.fade())) {
+ Row(Modifier.fillMaxWidth().height(34.dp).clip(Capsule()).background(phase.tint()), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.Center) {
+ Symbol("hand.raised.fill", size = 15.dp, tint = Palette.onAccent)
+ Spacer(Modifier.width(6.dp))
+ Text("Review", style = Type.system(13f).semibold, color = Palette.onAccent)
+ }
+ }
+ }
+}
+
+/** Android's Live update progress: segments that fill as the task moves, in the state's color. */
+@Composable private fun ProgressLine(phase: TaskPhase) {
+ val tint = phase.tint()
+ val filled = when (phase) { TaskPhase.Sending, TaskPhase.Queued -> 1; TaskPhase.Working, TaskPhase.Stale -> 2; TaskPhase.NeedsInput -> 3; else -> 4 }
+ Canvas(Modifier.fillMaxWidth().height(6.dp).semantics { contentDescription = "Progress, step $filled of 4" }) {
+ val gap = 3.dp.toPx(); val width = (size.width - gap * 3) / 4
+ for (i in 0 until 4) drawRoundRect(if (i < filled) tint else tint.copy(alpha = 0.16f), Offset(i * (width + gap), 0f),
+ Size(width, size.height), CornerRadius(size.height / 2))
+ }
+}
+
+/** The status bar with the task's chip beside the clock (Android 16's promoted notification chip). */
+@Composable private fun StatusBarPreview(phase: TaskPhase, started: Long) {
+ Row(Modifier.fillMaxWidth().clip(RoundedRectangle(18.dp)).background(Color.Black).padding(horizontal = 16.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically) {
+ Text("9:41", style = Type.system(14f).semibold.monospacedDigit, color = Color.White)
+ Spacer(Modifier.width(8.dp))
+ Row(Modifier.clip(Capsule()).background(if (phase == TaskPhase.NeedsInput || phase == TaskPhase.Failed) phase.tint() else Color(0xFF2C2C2C))
+ .padding(start = 7.dp, end = 10.dp, top = 4.dp, bottom = 4.dp).animateContentSize(Motion.layoutSize),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ // Android draws the app's small icon in the chip.
+ androidx.compose.foundation.Image(painterResource(R.drawable.ic_notification), null, Modifier.size(16.dp),
+ colorFilter = androidx.compose.ui.graphics.ColorFilter.tint(Color.White))
+ Text(when { phase.live && phase != TaskPhase.NeedsInput -> elapsed(started); phase == TaskPhase.NeedsInput -> "Needs you"
+ phase == TaskPhase.Completed -> "Done"; phase == TaskPhase.Failed -> "Failed"; else -> phase.title },
+ style = Type.system(12f).semibold.monospacedDigit, color = Color.White, maxLines = 1)
+ }
+ Spacer(Modifier.weight(1f))
+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically) {
+ Symbol("wifi", size = 15.dp, tint = Color.White)
+ Symbol("battery.75percent", size = 18.dp, tint = Color.White)
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/LocalStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/LocalStore.kt
new file mode 100644
index 00000000..5aebcd3e
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/LocalStore.kt
@@ -0,0 +1,104 @@
+package com.codync.android
+
+import android.content.Context
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyProperties
+import android.util.AtomicFile
+import com.codync.android.core.Computer
+import com.codync.android.core.DeviceIdentity
+import java.io.File
+import java.security.KeyStore
+import java.security.MessageDigest
+import java.security.SecureRandom
+import javax.crypto.Cipher
+import javax.crypto.KeyGenerator
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+import kotlinx.serialization.json.Json
+
+/** Account-scoped, atomic storage excluded from both backup and device transfer. */
+class LocalStore(context: Context, val contextId: String = "local") {
+ private val scopeId = MessageDigest.getInstance("SHA-256").digest(contextId.toByteArray())
+ .joinToString("") { "%02x".format(it) }
+ val referenceId = referenceId(contextId)
+ internal val directory = File(context.noBackupFilesDir, scopeId).apply { mkdirs() }
+ private val alias = "codync.identity.$scopeId"
+ private val json = Json { ignoreUnknownKeys = true }
+
+ @Synchronized
+ fun identity(): DeviceIdentity {
+ val file = AtomicFile(File(directory, "identity"))
+ val seeds = if (file.baseFile.exists()) {
+ val sealed = file.readFully()
+ require(sealed.size == 12 + 64 + 16) { "Device identity is damaged. Start over to pair again." }
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.DECRYPT_MODE, wrappingKey(), GCMParameterSpec(128, sealed.copyOf(12)))
+ cipher.updateAAD(scopeId.toByteArray())
+ cipher.doFinal(sealed.copyOfRange(12, sealed.size))
+ } else {
+ val fresh = ByteArray(64).also(SecureRandom()::nextBytes)
+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")
+ cipher.init(Cipher.ENCRYPT_MODE, wrappingKey())
+ cipher.updateAAD(scopeId.toByteArray())
+ write(file, cipher.iv + cipher.doFinal(fresh))
+ fresh
+ }
+ try {
+ require(seeds.size == 64)
+ return DeviceIdentity(seeds.copyOfRange(0, 32), seeds.copyOfRange(32, 64))
+ } finally { seeds.fill(0) }
+ }
+
+ private fun wrappingKey(): SecretKey {
+ val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ val existing = keyStore.getKey(alias, null) as? SecretKey
+ if (existing != null) return existing
+ val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
+ generator.init(KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+ .setKeySize(256).build())
+ return generator.generateKey()
+ }
+
+ fun computers(): List<Computer> {
+ val file = AtomicFile(File(directory, "computers.json"))
+ if (!file.baseFile.exists()) return emptyList()
+ val computers = json.decodeFromString<List<Computer>>(file.readFully().toString(Charsets.UTF_8))
+ computers.forEach(Computer::validate)
+ return computers
+ }
+
+ fun saveComputers(computers: List<Computer>) {
+ computers.forEach(Computer::validate)
+ write(AtomicFile(File(directory, "computers.json")), json.encodeToString(computers).toByteArray())
+ }
+
+ fun setupComplete(): Boolean = File(directory, "setup-complete").exists()
+ fun hasIdentity(): Boolean = File(directory, "identity").exists()
+ fun completeSetup() = write(AtomicFile(File(directory, "setup-complete")), byteArrayOf(1))
+
+ fun erase() {
+ check(directory.deleteRecursively()) { "Couldn't erase this phone's local data." }
+ val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ keyStore.deleteEntry(alias)
+ check(directory.mkdirs()) { "Couldn't create new local storage." }
+ }
+
+ private fun write(file: AtomicFile, bytes: ByteArray) {
+ val output = file.startWrite()
+ try { output.write(bytes); file.finishWrite(output) }
+ catch (error: Throwable) { file.failWrite(output); throw error }
+ }
+
+ companion object {
+ fun referenceId(contextId: String): String = if (contextId == "local") "local" else MessageDigest.getInstance("SHA-256")
+ .digest(contextId.toByteArray()).joinToString("") { "%02x".format(it) }
+ /** Reset includes inactive accounts and their wrapping keys, never host data. */
+ fun eraseAll(context: Context) {
+ context.noBackupFilesDir.listFiles()?.filter { it.isDirectory && it.name.matches(Regex("[a-f0-9]{64}")) }
+ ?.forEach { check(it.deleteRecursively()) { "Couldn't erase local account data." } }
+ val keys = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ keys.aliases().toList().filter { it.startsWith("codync.identity.") }.forEach(keys::deleteEntry)
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/LocalVoiceAudio.kt b/apps/android/app/src/main/kotlin/com/codync/android/LocalVoiceAudio.kt
new file mode 100644
index 00000000..6aecfcc3
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/LocalVoiceAudio.kt
@@ -0,0 +1,189 @@
+package com.codync.android
+
+import android.Manifest
+import android.content.Context
+import android.content.pm.PackageManager
+import android.media.*
+import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
+import android.speech.tts.TextToSpeech
+import android.speech.tts.UtteranceProgressListener
+import androidx.core.content.ContextCompat
+import com.codync.android.core.*
+import java.io.File
+import java.io.IOException
+import java.util.Locale
+import kotlinx.coroutines.*
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import org.json.JSONObject
+import org.vosk.LibVosk
+import org.vosk.Model
+import org.vosk.Recognizer
+import kotlin.math.log10
+
+/** Offline English recognition and an installed local TTS voice. No PCM is written to disk. */
+internal class LocalVoiceAudio(private val context: Context) : VoiceAudio {
+ private val worker = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val main = Handler(Looper.getMainLooper())
+ @Volatile private var model: Model? = null
+ @Volatile private var recorder: AudioRecord? = null
+ private var recording: Job? = null
+ private var speech: TextToSpeech? = null
+ private var completion: ((Long, String?) -> Unit)? = null
+ private var speakingId: Long? = null; private var lastChunk: String? = null
+ val recordingSessionId: Int? get() = recorder?.audioSessionId
+
+ override suspend fun initialize(): String {
+ require(ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)
+ withContext(Dispatchers.IO) {
+ try {
+ LibVosk.vosk_set_log_level(-1)
+ val directory = VoiceModels.english(context)
+ currentCoroutineContext().ensureActive()
+ model = Model(directory.absolutePath)
+ } catch (error: LinkageError) { throw IOException("The local speech engine couldn't load.", error) }
+ }
+ val ready = CompletableDeferred<Int>()
+ val engine = TextToSpeech(context) { ready.complete(it) }
+ speech = engine
+ val status = withTimeoutOrNull(20_000) { ready.await() }
+ ?: throw VoiceUnavailable("Android's text-to-speech engine didn't start. Try the call again.")
+ if (status != TextToSpeech.SUCCESS) throw VoiceUnavailable("Install a text-to-speech engine in Android's speech settings.")
+ val voices = engine.voices.orEmpty().filter { !it.isNetworkConnectionRequired && it.locale.language == "en" }
+ val voice = voices.maxWithOrNull(compareBy<android.speech.tts.Voice> { it.locale == Locale.US }.thenBy { it.quality })
+ ?: throw VoiceUnavailable("Install an offline English voice in Android's text-to-speech settings.")
+ check(engine.setVoice(voice) == TextToSpeech.SUCCESS)
+ engine.setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
+ .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build())
+ engine.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
+ override fun onStart(utteranceId: String?) { }
+ override fun onDone(utteranceId: String?) { main.post {
+ if (utteranceId == lastChunk) { val id = speakingId; val callback = completion
+ speakingId = null; lastChunk = null; completion = null; if (id != null) callback?.invoke(id, null) }
+ } }
+ @Deprecated("Required by older TTS engines") override fun onError(utteranceId: String?) { failed(utteranceId) }
+ override fun onError(utteranceId: String?, errorCode: Int) { failed(utteranceId) }
+ private fun failed(utteranceId: String?) { main.post {
+ val id = speakingId ?: return@post
+ if (utteranceId?.startsWith("codync-$id-") != true) return@post
+ val callback = completion; speakingId = null; lastChunk = null; completion = null
+ callback?.invoke(id, "Couldn't read the reply. Check the installed offline voice.")
+ } }
+ })
+ return "Offline English · Vosk"
+ }
+ override suspend fun listen(generation: Long, events: (VoiceInput) -> Unit) {
+ check(recording == null)
+ require(ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)
+ val installed = requireNotNull(model)
+ recording = worker.launch {
+ var microphone: AudioRecord? = null; var decoder: Recognizer? = null
+ try {
+ val format = AudioFormat.Builder().setSampleRate(16_000).setChannelMask(AudioFormat.CHANNEL_IN_MONO)
+ .setEncoding(AudioFormat.ENCODING_PCM_16BIT).build()
+ val minimum = AudioRecord.getMinBufferSize(16_000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
+ check(minimum > 0)
+ microphone = AudioRecord.Builder().setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION)
+ .setAudioFormat(format).setBufferSizeInBytes(maxOf(minimum, 12_800)).build()
+ recorder = microphone
+ check(microphone.state == AudioRecord.STATE_INITIALIZED)
+ decoder = Recognizer(installed, 16_000f)
+ ensureActive(); microphone.startRecording()
+ check(microphone.recordingState == AudioRecord.RECORDSTATE_RECORDING)
+ val buffer = ShortArray(3_200); var previous = ""
+ while (isActive) {
+ val count = microphone.read(buffer, 0, buffer.size, AudioRecord.READ_BLOCKING)
+ if (!isActive) break
+ if (count < 0) throw IOException("Microphone read failed")
+ if (count == 0) { delay(10); continue }
+ var power = 0.0
+ for (i in 0 until count) { val sample = buffer[i].toDouble() / 32_768; power += sample * sample }
+ val db = 10 * log10(maxOf(power / count, 1e-10))
+ events(VoiceInput.Level(generation, ((db + 50) / 50).toFloat().coerceIn(0f, 1f)))
+ if (decoder.acceptWaveForm(buffer, count)) {
+ val text = JSONObject(decoder.result).optString("text")
+ previous = ""; if (text.isNotBlank()) events(VoiceInput.Text(generation, text, true))
+ } else {
+ val text = JSONObject(decoder.partialResult).optString("partial")
+ if (text != previous) { previous = text; events(VoiceInput.Text(generation, text, false)) }
+ }
+ }
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) { if (isActive) events(VoiceInput.Failed(generation, "Couldn't use the microphone. Check its permission and other audio apps.")) }
+ finally {
+ runCatching { microphone?.stop() }; runCatching { microphone?.release() }
+ if (recorder === microphone) recorder = null
+ decoder?.close()
+ }
+ }
+ }
+ override suspend fun stopListening() {
+ withContext(NonCancellable) {
+ val old = recording; recording = null
+ old?.cancel(); runCatching { recorder?.stop() }; old?.join()
+ }
+ }
+ override suspend fun speak(id: Long, text: String, rate: Float, completed: (Long, String?) -> Unit) {
+ val engine = requireNotNull(speech)
+ val chunks = SpokenText.chunks(text)
+ speakingId = id; completion = completed; lastChunk = "codync-$id-${chunks.lastIndex}"
+ check(engine.setSpeechRate(rate) == TextToSpeech.SUCCESS)
+ for ((index, chunk) in chunks.withIndex()) {
+ check(engine.speak(chunk, TextToSpeech.QUEUE_ADD, Bundle(), "codync-$id-$index") == TextToSpeech.SUCCESS)
+ }
+ }
+ override suspend fun stopSpeaking() { completion = null; speakingId = null; lastChunk = null; speech?.stop() }
+ override suspend fun close() {
+ try { stopListening() }
+ finally {
+ worker.cancel()
+ try { stopSpeaking() }
+ finally {
+ val engine = speech; speech = null
+ try { engine?.shutdown() }
+ finally { withContext(Dispatchers.IO) { val old = model; model = null; old?.close() } }
+ }
+ }
+ }
+}
+
+/** Public linguistic weights are shared; account credentials and captured audio never enter this directory. */
+internal object VoiceModels {
+ private val lock = Mutex()
+ private const val source = "voice/vosk-model-small-en-us-0.15"
+ suspend fun english(context: Context): File = lock.withLock {
+ val destination = File(context.noBackupFilesDir, "voice-models/en-us-0.15")
+ if (File(destination, ".complete").isFile) return@withLock destination
+ val temporary = File(destination.parentFile, "en-us-0.15-pending")
+ temporary.deleteRecursively(); temporary.mkdirs()
+ suspend fun copy(folder: String, target: File) {
+ val children = context.assets.list(folder).orEmpty()
+ for (child in children) {
+ currentCoroutineContext().ensureActive()
+ val path = "$folder/$child"; val output = File(target, child)
+ if (context.assets.list(path).orEmpty().isNotEmpty()) { output.mkdirs(); copy(path, output) }
+ else context.assets.open(path).use { input -> output.outputStream().use { input.copyTo(it) } }
+ }
+ }
+ try {
+ copy(source, temporary)
+ check(File(temporary, "am/final.mdl").isFile && File(temporary, "conf/model.conf").isFile)
+ File(temporary, ".complete").writeText("0.15")
+ destination.deleteRecursively(); check(temporary.renameTo(destination))
+ destination
+ } finally { temporary.deleteRecursively() }
+ }
+}
+
+internal object VoicePreferences {
+ fun load(context: Context): VoiceSettings {
+ val stored = context.getSharedPreferences("codync-voice", Context.MODE_PRIVATE)
+ return runCatching { VoiceSettings(stored.getLong("pause", 1_500), stored.getFloat("rate", 1f)) }.getOrDefault(VoiceSettings())
+ }
+ fun save(context: Context, settings: VoiceSettings) {
+ context.getSharedPreferences("codync-voice", Context.MODE_PRIVATE).edit()
+ .putLong("pause", settings.pauseMillis).putFloat("rate", settings.rate).apply()
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt b/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt
new file mode 100644
index 00000000..386bb7a8
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt
@@ -0,0 +1,95 @@
+package com.codync.android
+
+import android.content.Intent
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.activity.enableEdgeToEdge
+import androidx.activity.viewModels
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.key
+import androidx.compose.runtime.LaunchedEffect
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import com.codync.android.design.CodyncTheme
+import com.codync.android.design.OverlayRoot
+import coil3.ImageLoader
+import coil3.disk.DiskCache
+import java.io.File
+import okio.Path.Companion.toOkioPath
+
+class MainActivity : ComponentActivity() {
+ private val store: AppStore by viewModels()
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ NativeAccounts.initialize(this)
+ Analytics.start(applicationContext)
+ Analytics.userId = { store.state.value.account.userId }
+ NotificationDisplay.channels(this)
+ enableEdgeToEdge()
+ setContent {
+ val state by store.state.collectAsStateWithLifecycle()
+ val notifications = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { store.syncPush() }
+ LaunchedEffect(state.computers.isNotEmpty(), state.contextId) {
+ if (BuildConfig.PUSH_CONFIGURED && state.computers.isNotEmpty() && android.os.Build.VERSION.SDK_INT >= 33 && !PushPreferences.asked(applicationContext)) {
+ PushPreferences.markAsked(applicationContext)
+ notifications.launch(android.Manifest.permission.POST_NOTIFICATIONS)
+ }
+ }
+ val images = remember(state.contextId, state.generation) { AccountImages.open(applicationContext, state.contextId) }
+ DisposableEffect(images) { onDispose { AccountImages.close(images) } }
+ CompositionLocalProvider(LocalNetworkImages provides images) {
+ key(state.contextId, state.generation) {
+ CodyncTheme { OverlayRoot { CodyncApp(state, store); LaunchLayer(state.loading) } }
+ }
+ }
+ }
+ // Rotation keeps its ViewModel/navigation; process restoration gets a fresh owner.
+ if (savedInstanceState?.getString("codync:activityOwner") != store.activityOwnerId) handle(intent)
+ }
+ override fun onSaveInstanceState(outState: Bundle) {
+ outState.putString("codync:activityOwner", store.activityOwnerId)
+ super.onSaveInstanceState(outState)
+ }
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ setIntent(intent)
+ handle(intent)
+ }
+ override fun onStart() { super.onStart(); store.setForeground(true); Analytics.becameActive() }
+ override fun onStop() {
+ store.setForeground(false)
+ // A rotation isn't a trip to the background.
+ if (!isChangingConfigurations) Analytics.enteredBackground()
+ super.onStop()
+ }
+ private fun handle(intent: Intent?) {
+ val uri = intent?.data ?: return
+ if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "pair") {
+ intent.data = null
+ store.pair(uri.toString())
+ }
+ // Retain the scoped, non-secret destination for Activity/process restoration.
+ if (uri.scheme == BuildConfig.URL_SCHEME && uri.host in setOf("bot", "usage")) store.openLink(uri)
+ if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "oauth") { intent.data = null; store.finishConnectorSignIn(uri) }
+ }
+}
+
+/** One active loader: switching accounts closes old requests before their cache can be erased. */
+internal object AccountImages {
+ private var current: ImageLoader? = null
+ @Synchronized fun open(context: android.content.Context, id: String): ImageLoader {
+ retire()
+ val images = ImageLoader.Builder(context).diskCache {
+ DiskCache.Builder().directory(File(context.cacheDir, "codync-images-$id").toOkioPath()).maxSizeBytes(64L * 1024 * 1024).build()
+ }.build()
+ current = images
+ return images
+ }
+ @Synchronized fun close(images: ImageLoader) { images.shutdown(); if (current === images) current = null }
+ @Synchronized fun retire() { current?.shutdown(); current = null }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MainTabs.kt b/apps/android/app/src/main/kotlin/com/codync/android/MainTabs.kt
new file mode 100644
index 00000000..cc7e4abf
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MainTabs.kt
@@ -0,0 +1,74 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.slideInVertically
+import androidx.compose.animation.slideOutVertically
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.asPaddingValues
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.navigationBars
+import androidx.compose.foundation.layout.padding
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.input.pointer.PointerEventPass
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.zIndex
+import androidx.compose.ui.semantics.clearAndSetSemantics
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Bot
+import com.codync.android.design.*
+
+private enum class AppTab { Bots, State }
+
+/**
+ * The system tab bar over Bots and State, as iOS `RootView.tabs`: both tabs stay alive, the bar
+ * floats as glass over their content and hides while a conversation is open.
+ */
+@Composable internal fun MainTabs(state: AppState, store: AppStore, account: () -> Unit, manage: () -> Unit, usage: () -> Unit,
+ newBot: () -> Unit, newGroup: () -> Unit, edit: (Bot) -> Unit, chat: @Composable () -> Unit) {
+ var tab by rememberSaveable { mutableStateOf(AppTab.Bots) }
+ // Opening a bot (notification, widget, link) always lands on the Bots tab.
+ if (state.selectedBot != null && tab != AppTab.Bots) tab = AppTab.Bots
+ val bottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()
+ val barSpace = bottom + 62.dp + 24.dp
+ GlassStage(Modifier.fillMaxSize(), chrome = {
+ // An account computer this phone asked on its own after sign-in: the code to check, until it answers.
+ val ticket = state.access
+ AnimatedVisibility(ticket != null && state.selectedBot == null, Modifier.align(Alignment.BottomCenter).padding(bottom = barSpace - 16.dp),
+ enter = fadeIn(Motion.fade()) + slideInVertically(Motion.layoutOffset) { it }, exit = fadeOut(Motion.fade()) + slideOutVertically(Motion.layoutOffset) { it }) {
+ if (ticket != null) AccessBanner(ticket, state.cloudComputers.firstOrNull { it.computerId == ticket.computerId }?.name ?: "Your computer",
+ store::cancelAccess)
+ }
+ AnimatedVisibility(state.selectedBot == null, Modifier.align(Alignment.BottomCenter),
+ enter = fadeIn(Motion.fade()) + slideInVertically(Motion.layoutOffset) { it / 2 },
+ exit = fadeOut(Motion.fade()) + slideOutVertically(Motion.layoutOffset) { it / 2 }) {
+ GlassTabBar(tab, listOf(TabItem(AppTab.Bots, "Bots", "bubble.left.and.bubble.right.fill", 33.dp),
+ TabItem(AppTab.State, "State", "rectangle.stack.fill")), { tab = it },
+ Modifier.padding(bottom = maxOf(bottom - 4.dp, 12.dp)))
+ }
+ }) {
+ Box(Modifier.fillMaxSize().tabLayer(tab == AppTab.Bots)) {
+ NavStack(listOfNotNull("roster", state.selectedBot), key = { it }, pop = { store.openBot(null) }) { entry ->
+ if (entry == "roster") BotListView(state, store, account, manage, newBot, newGroup, edit, barSpace)
+ else chat()
+ }
+ }
+ Box(Modifier.fillMaxSize().tabLayer(tab == AppTab.State)) { StateScreen(state, store, usage, barSpace, active = tab == AppTab.State) }
+ }
+}
+
+/** One tab's content: visible and interactive only while selected; the other sits under it, deaf to touches. */
+private fun Modifier.tabLayer(selected: Boolean): Modifier = zIndex(if (selected) 1f else 0f)
+ .graphicsLayer { alpha = if (selected) 1f else 0f }
+ .then(if (selected) Modifier else Modifier.clearAndSetSemantics {}.pointerInput(Unit) {
+ awaitPointerEventScope { while (true) awaitPointerEvent(PointerEventPass.Initial).changes.forEach { it.consume() } }
+ })
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MarkdownText.kt b/apps/android/app/src/main/kotlin/com/codync/android/MarkdownText.kt
new file mode 100644
index 00000000..bd26a527
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MarkdownText.kt
@@ -0,0 +1,157 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.IntrinsicSize
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.staticCompositionLocalOf
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.AnnotatedString
+import androidx.compose.ui.text.LinkAnnotation
+import androidx.compose.ui.text.SpanStyle
+import androidx.compose.ui.text.TextLinkStyles
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.buildAnnotatedString
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontStyle
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextDecoration
+import androidx.compose.ui.unit.dp
+import coil3.ImageLoader
+import com.codync.android.core.MarkdownBlocks
+import com.codync.android.core.MarkdownBlocks.Block
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+import org.commonmark.ext.gfm.strikethrough.Strikethrough
+import org.commonmark.ext.gfm.strikethrough.StrikethroughExtension
+import org.commonmark.node.Code
+import org.commonmark.node.Emphasis
+import org.commonmark.node.HardLineBreak
+import org.commonmark.node.HtmlInline
+import org.commonmark.node.Image
+import org.commonmark.node.Link
+import org.commonmark.node.Node
+import org.commonmark.node.SoftLineBreak
+import org.commonmark.node.StrongEmphasis
+import org.commonmark.parser.Parser
+
+val LocalNetworkImages = staticCompositionLocalOf<ImageLoader> { error("Missing image loader") }
+
+/**
+ * The reply renderer of iOS `MarkdownText`: `MarkdownBlocks` for the blocks, inline styling for
+ * bold, italic, code, strikethrough and links. Images show as their text: a reply never makes
+ * the phone fetch an address.
+ */
+@Composable fun MarkdownText(source: String, selectable: Boolean = true, color: Color = Palette.text) {
+ val blocks = remember(source) { MarkdownBlocks.parse(source) }
+ val content: @Composable () -> Unit = {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { for (block in blocks) MarkdownBlock(block, color) }
+ }
+ if (selectable) SelectionContainer(content = content) else content()
+}
+
+@Composable private fun MarkdownBlock(block: Block, ink: Color) {
+ val code = Palette.text.copy(alpha = 0.08f)
+ when (block) {
+ is Block.Paragraph -> Text(inline(block.text, code), style = Type.body, color = ink)
+ is Block.Heading -> Text(inline(block.text, code), style = when (block.level) {
+ 1 -> Type.title3.bold; 2 -> Type.headline; else -> Type.subheadline.bold
+ }, color = ink)
+ is Block.Bullet -> Row(Modifier.padding(start = 16.dp * block.depth), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(block.marker, style = Type.body.monospacedDigit, color = Palette.secondary)
+ Text(inline(block.text, code), style = Type.body, color = ink)
+ }
+ Block.Rule -> Box(Modifier.padding(vertical = 4.dp).fillMaxWidth().height(1.dp).background(Palette.border))
+ is Block.Table -> MarkdownTable(block, code, ink)
+ is Block.Quote -> Row(Modifier.height(IntrinsicSize.Min)) {
+ Box(Modifier.width(3.dp).fillMaxHeight().background(Palette.border))
+ Text(inline(block.text, code), Modifier.padding(start = 10.dp), style = Type.body, color = Palette.secondary)
+ }
+ is Block.Code -> Box(Modifier.fillMaxWidth().clip(RoundedRectangle(8.dp)).background(Palette.codeBackground)
+ .horizontalScroll(rememberScrollState())) {
+ Text(block.text, Modifier.padding(10.dp), style = Type.footnote.monospaced, color = Palette.text, softWrap = false)
+ }
+ }
+}
+
+/** A table: a bold header and hairlines between rows, scrolling sideways when wide. */
+@Composable private fun MarkdownTable(table: Block.Table, code: Color, ink: Color) {
+ val columns = maxOf(table.header.size, table.rows.maxOfOrNull { it.size } ?: 0)
+ val rows = listOf(table.header) + table.rows
+ Box(Modifier.horizontalScroll(rememberScrollState()).padding(vertical = 2.dp)) {
+ Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
+ for (column in 0 until columns) Column(Modifier.width(IntrinsicSize.Max), verticalArrangement = Arrangement.spacedBy(7.dp)) {
+ for ((index, row) in rows.withIndex()) {
+ if (index > 0) Box(Modifier.fillMaxWidth().height(1.dp).background(Palette.border))
+ Text(inline(row.getOrElse(column) { "" }, code), Modifier.heightIn(min = 22.dp),
+ style = if (index == 0) Type.body.semibold else Type.body, color = ink, softWrap = false)
+ }
+ }
+ }
+ }
+}
+
+private val inlineParser = Parser.builder().extensions(listOf(StrikethroughExtension.create())).build()
+
+/** Inline Markdown: links underlined (the theme is monochrome), inline code on a soft tint. */
+internal fun inline(source: String, codeTint: Color): AnnotatedString {
+ // Inline only: indentation would otherwise read as a code block.
+ val document = inlineParser.parse(source.lines().joinToString("\n") { it.trimStart() })
+ return buildAnnotatedString {
+ fun visit(node: Node) {
+ val style = when (node) {
+ is StrongEmphasis -> SpanStyle(fontWeight = FontWeight.SemiBold)
+ is Emphasis -> SpanStyle(fontStyle = FontStyle.Italic)
+ is Code -> SpanStyle(fontFamily = FontFamily.Monospace, background = codeTint)
+ is Strikethrough -> SpanStyle(textDecoration = TextDecoration.LineThrough)
+ else -> null
+ }
+ if (style != null) pushStyle(style)
+ val link = (node as? Link)?.destination?.takeIf { it.startsWith("https://") || it.startsWith("http://") || it.startsWith("mailto:") }
+ if (link != null) pushLink(LinkAnnotation.Url(link, TextLinkStyles(SpanStyle(textDecoration = TextDecoration.Underline))))
+ when (node) {
+ is org.commonmark.node.Text -> append(node.literal)
+ is Code -> append(node.literal)
+ is SoftLineBreak, is HardLineBreak -> append("\n")
+ is HtmlInline -> append(node.literal)
+ is org.commonmark.node.HtmlBlock -> append(node.literal.trimEnd())
+ is org.commonmark.node.FencedCodeBlock -> append(node.literal.trimEnd())
+ is Image -> children(node).forEach(::visit)
+ else -> children(node).forEach(::visit)
+ }
+ if (link != null) pop()
+ if (style != null) pop()
+ }
+ // Paragraphs of a multi-line block keep their line breaks.
+ children(document).forEachIndexed { index, paragraph -> if (index > 0) append("\n\n"); visit(paragraph) }
+ }
+}
+
+private fun children(node: Node): List<Node> = buildList {
+ var child = node.firstChild
+ while (child != null) { add(child); child = child.next }
+}
+
+/** A monospaced box for commands and output (iOS `CodeBox`). */
+@Composable fun CodeBox(text: String, style: TextStyle = Type.caption.monospaced) {
+ Box(Modifier.fillMaxWidth().heightIn(max = 240.dp).clip(RoundedRectangle(8.dp)).background(Palette.codeBackground)
+ .horizontalScroll(rememberScrollState())) {
+ SelectionContainer { Text(text, Modifier.padding(8.dp), style = style, color = Palette.text, softWrap = false) }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MarketActions.kt b/apps/android/app/src/main/kotlin/com/codync/android/MarketActions.kt
new file mode 100644
index 00000000..67e5a7fb
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MarketActions.kt
@@ -0,0 +1,62 @@
+package com.codync.android
+
+import com.codync.android.core.InstalledConnector
+import com.codync.android.core.WireJson
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.withTimeoutOrNull
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.decodeFromJsonElement
+import kotlinx.serialization.json.encodeToJsonElement
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.put
+
+// The Extensions calls a sheet waits on (iOS `BotStore+Plugins`): the host does the work, the
+// installed list refreshes after, and failures stay on the sheet that asked.
+
+/** A connector you describe yourself: a command line with env, or an https URL with headers. */
+internal suspend fun AppStore.addConnector(name: String, command: String?, url: String?, env: Map<String, String>,
+ headers: Map<String, String>): InstalledConnector {
+ val response = hostCall("installConnector", buildJsonObject {
+ put("name", name); command?.let { put("command", it) }; url?.let { put("url", it) }
+ put("env", WireJson.encodeToJsonElement(env)); put("headers", WireJson.encodeToJsonElement(headers))
+ }, 45_000)
+ refreshPlugins()
+ return WireJson.decodeFromJsonElement(response.jsonObject.getValue("connector"))
+}
+
+internal suspend fun AppStore.removePlugin(method: String, id: String) {
+ require(method in listOf("removeConnector", "removeSkill"))
+ hostCall(method, buildJsonObject { put("id", id) }, 60_000)
+ refreshPlugins()
+}
+
+internal suspend fun AppStore.installSkill(source: String) {
+ hostCall("installSkill", buildJsonObject { put("source", source) }, 60_000)
+ refreshPlugins()
+}
+
+internal suspend fun AppStore.addSkill(name: String, description: String, instructions: String) {
+ hostCall("installSkill", buildJsonObject { put("name", name); put("description", description); put("instructions", instructions) }, 60_000)
+ refreshPlugins()
+}
+
+/** A skill's `SKILL.md` without its front matter: an installed one by `id`, a catalog one by `source`. */
+internal suspend fun AppStore.skillDetails(id: String?, source: String?): String =
+ hostCall("skillDetails", buildJsonObject { if (source != null) put("source", source) else put("id", requireNotNull(id)) }, 60_000)
+ .jsonObject.getValue("markdown").jsonPrimitive.content
+
+/**
+ * Signs in to a connector and waits while the browser finishes it (the store catches the return);
+ * false when the store reports a failure or ten minutes pass.
+ */
+internal suspend fun AppStore.signInConnector(id: String, requestId: String? = null): Boolean {
+ clearError()
+ connectorSignIn(id, requestId)
+ fun signedIn(s: AppState) = s.plugins?.connectors?.any { it.id == id && it.auth == "signedIn" } == true
+ val settled = withTimeoutOrNull(600_000) { state.first { signedIn(it) || it.error != null } } ?: return false
+ return signedIn(settled)
+}
+
+/** The computer's own name (its hello), the one everything here installs on. */
+internal val AppState.hostName: String get() = hello?.text("name") ?: computers.firstOrNull()?.name ?: "your computer"
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MarketFields.kt b/apps/android/app/src/main/kotlin/com/codync/android/MarketFields.kt
new file mode 100644
index 00000000..6002c9d2
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MarketFields.kt
@@ -0,0 +1,61 @@
+package com.codync.android
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.input.KeyboardCapitalization
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.text.input.VisualTransformation
+import androidx.compose.ui.unit.dp
+import com.codync.android.design.*
+
+/**
+ * A plain field in a card row (`TextField` / `SecureField` with `.plainTextInput()`): no chrome,
+ * no autocorrect, the prompt in the tertiary ink; a secret one hides what's typed.
+ */
+@Composable internal fun PlainInput(text: String, onChange: (String) -> Unit, prompt: String, modifier: Modifier = Modifier,
+ secret: Boolean = false, style: TextStyle = Type.body, minLines: Int = 1, maxLines: Int = 1, enabled: Boolean = true) {
+ BasicTextField(text, onChange, modifier.fillMaxWidth().semantics { contentDescription = prompt }, enabled = enabled,
+ singleLine = maxLines == 1, minLines = minLines, maxLines = maxLines, textStyle = style.copy(color = Palette.text),
+ cursorBrush = SolidColor(Palette.accent),
+ visualTransformation = if (secret) PasswordVisualTransformation() else VisualTransformation.None,
+ keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.None, autoCorrectEnabled = false,
+ keyboardType = if (secret) KeyboardType.Password else KeyboardType.Text),
+ decorationBox = { field ->
+ Box(contentAlignment = Alignment.CenterStart) {
+ if (text.isEmpty()) Text(prompt, style = style, color = Palette.tertiary, maxLines = maxLines)
+ field()
+ }
+ })
+}
+
+/** A small caption over a field (iOS `CredentialFieldRow`). */
+@Composable internal fun FieldRow(title: String, content: @Composable () -> Unit) {
+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(title, style = Type.caption, color = Palette.secondary)
+ content()
+ }
+}
+
+/** A field with its note under it, the iOS setup forms' row. */
+@Composable internal fun NotedInput(text: String, onChange: (String) -> Unit, prompt: String, note: String?, secret: Boolean = false) {
+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ PlainInput(text, onChange, prompt, secret = secret)
+ if (note != null) Text(note, style = Type.caption, color = Palette.secondary)
+ }
+}
+
+/** An error inside a card. */
+@Composable internal fun ErrorRow(text: String) = Text(text, style = Type.body, color = Palette.danger)
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MarketRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/MarketRows.kt
new file mode 100644
index 00000000..16eb431e
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MarketRows.kt
@@ -0,0 +1,191 @@
+package com.codync.android
+
+import androidx.compose.animation.core.RepeatMode
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.infiniteRepeatable
+import androidx.compose.animation.core.rememberInfiniteTransition
+import androidx.compose.animation.core.tween
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.ColorFilter
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalUriHandler
+import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.semantics.clearAndSetSemantics
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.heading
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextDecoration
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import androidx.core.net.toUri
+import coil3.compose.AsyncImage
+import com.codync.android.core.AgentBackend
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+
+// The Extensions page's building blocks (iOS `MarketRows`): sections, rows, agent cards and logos.
+
+@Composable internal fun MarketSection(title: String, content: @Composable () -> Unit) {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Text(title, Modifier.padding(start = 4.dp).semantics { heading() }, style = Type.headline, color = Palette.text)
+ content()
+ }
+}
+
+/** One catalog item: its icon, name and line, then Add (or a check once added). */
+@Composable internal fun MarketRow(title: String, subtitle: String, added: Boolean, busy: Boolean = false, addLabel: String = "Add",
+ open: (() -> Unit)? = null, icon: @Composable () -> Unit, add: () -> Unit) {
+ // The whole row opens the item's details; without it the row does what its button does.
+ val rowAction = open ?: if (added || busy) null else add
+ Row(Modifier.fillMaxWidth().clip(RoundedRectangle(16.dp)).then(if (rowAction != null) Modifier.plainButton(action = rowAction) else Modifier)
+ .padding(horizontal = 12.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ Box(Modifier.size(46.dp), contentAlignment = Alignment.Center) { icon() }
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(title, style = Type.body.medium, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(subtitle, style = Type.subheadline, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ when {
+ busy -> Box(Modifier.width(60.dp), contentAlignment = Alignment.Center) { ThinkingOrb(size = 18.dp, color = Palette.secondary) }
+ added -> Box(Modifier.width(60.dp), contentAlignment = Alignment.Center) {
+ Symbol("checkmark", size = 16.dp, tint = Palette.secondary, contentDescription = "Added")
+ }
+ else -> Text(addLabel, Modifier.clip(Capsule()).background(Palette.bubbleAgent).plainButton(action = add)
+ .padding(horizontal = 16.dp, vertical = 7.dp), style = Type.subheadline.semibold, color = Palette.text)
+ }
+ }
+}
+
+/** An agent in the Agents row: its logo on a tile, its name and where it stands. */
+@Composable internal fun AgentCard(backend: AgentBackend, action: () -> Unit) {
+ val status = when {
+ !backend.installed && backend.curated -> "Not installed"
+ backend.needsNode -> "Needs Node.js"
+ !backend.installed -> "Sets up on first use"
+ backend.signedIn == false -> "Not signed in"
+ else -> "Installed"
+ }
+ Column(Modifier.width(128.dp).clip(RoundedRectangle(18.dp)).background(Palette.bubbleAgent.copy(alpha = 0.45f)).plainButton(action = action)
+ .semantics(mergeDescendants = true) {}.padding(horizontal = 10.dp, vertical = 18.dp),
+ horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Box(Modifier.size(64.dp).clip(RoundedRectangle(18.dp)).background(Palette.bubbleAgent), contentAlignment = Alignment.Center) {
+ AgentIcon(backend.registry ?: backend.id, 34.dp)
+ }
+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(backend.name, style = Type.subheadline.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(status, style = Type.caption, color = Palette.secondary, maxLines = 1)
+ }
+ }
+}
+
+/** A coding agent's logo by ACP registry id, in its brand color when it has one; a terminal glyph otherwise. */
+@Composable internal fun AgentIcon(registry: String?, size: Dp) {
+ val tint = AGENT_TINTS[registry]?.let { Color(it) } ?: Palette.text
+ val res = agentIconRes(registry)
+ if (res != null) Image(painterResource(res), null, Modifier.size(size).clearAndSetSemantics {}, colorFilter = ColorFilter.tint(tint))
+ else Symbol("terminal", Modifier.padding(size * 0.1f), size = size * 0.8f, tint = tint)
+}
+
+// Registry logos are one color; these carry their brand's (a gradient's middle for Gemini and omp).
+private val AGENT_TINTS = mapOf("claude-acp" to 0xFFD97857, "gemini" to 0xFF9178C7, "antigravity-acp" to 0xFF4285F5,
+ "mistral-vibe" to 0xFFFA520F, "qwen-code" to 0xFF615CED, "amp-acp" to 0xFFF24F40, "kiro" to 0xFF8F45FF,
+ "cortex-code" to 0xFF29B5E8, "omp" to 0xFF9C4DFF)
+
+/** Placeholder rows while a list loads, shaped like the real ones. */
+@Composable internal fun SkeletonRows() {
+ val dim by rememberInfiniteTransition(label = "Skeleton").animateFloat(1f, 0.5f, infiniteRepeatable(tween(900), RepeatMode.Reverse), label = "Dim")
+ Column(Modifier.graphicsLayer { alpha = dim }.clearAndSetSemantics { contentDescription = "Loading" }) {
+ repeat(4) {
+ Row(Modifier.padding(horizontal = 12.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ Box(Modifier.size(46.dp).clip(RoundedRectangle(12.dp)).background(Palette.bubbleAgent))
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Box(Modifier.size(120.dp, 12.dp).clip(Capsule()).background(Palette.bubbleAgent))
+ Box(Modifier.size(190.dp, 10.dp).clip(Capsule()).background(Palette.bubbleAgent))
+ }
+ }
+ }
+ }
+}
+
+/** A service's logo from its website favicon, on a white tile; its initial otherwise. */
+@Composable internal fun ServiceLogo(website: String?, name: String, registryName: String? = null, size: Dp = 46.dp, site: String? = null) {
+ val domain = site ?: serviceDomain(website, name, registryName)
+ var loaded by remember(domain) { mutableStateOf(false) }
+ val shape = RoundedRectangle(size * 0.26f)
+ Box(Modifier.size(size).clip(shape).background(if (loaded) Color.White else Palette.bubbleAgent).clearAndSetSemantics {},
+ contentAlignment = Alignment.Center) {
+ if (!loaded) Text(name.firstOrNull()?.uppercase() ?: "?", style = Type.system(size.value * 0.4f, FontWeight.SemiBold), color = Palette.text)
+ if (domain != null) AsyncImage("https://www.google.com/s2/favicons?domain=$domain&sz=128", null, imageLoader = LocalNetworkImages.current,
+ modifier = Modifier.fillMaxSize().padding(size * 0.2f), contentScale = ContentScale.Fit, onSuccess = { loaded = true })
+ }
+}
+
+/** MCP Registry names are reverse-DNS ("com.notion/mcp"): the owner's domain; a website's host otherwise. */
+internal fun serviceDomain(website: String?, name: String, registryName: String?): String? {
+ website?.let { it.toUri().host }?.takeIf { it != "github.com" }?.let { return it }
+ val labels = registryName?.substringBefore('/')?.split('.') ?: return null
+ // io.github.<user> is a GitHub account, not the service's own site.
+ if (labels.size < 2 || labels[0] == "io" && labels[1] == "github") return if (name.contains("github", ignoreCase = true)) "github.com" else null
+ return "${labels[1]}.${labels[0]}"
+}
+
+/** An app's logo from Composio, a letter tile until it loads. */
+@Composable internal fun AppLogo(url: String?, name: String, size: Dp = 46.dp) {
+ Box(Modifier.size(size).clip(RoundedRectangle(size * 0.28f)).background(Palette.bubbleAgent).clearAndSetSemantics {},
+ contentAlignment = Alignment.Center) {
+ Text(name.take(1).uppercase(), style = Type.system(size.value * 0.4f, FontWeight.SemiBold), color = Palette.secondary)
+ if (url != null) AsyncImage(url, null, imageLoader = LocalNetworkImages.current,
+ modifier = Modifier.fillMaxSize().background(Palette.bubbleAgent).padding(size * 0.18f), contentScale = ContentScale.Fit)
+ }
+}
+
+@Composable internal fun TileIcon(systemImage: String) {
+ Box(Modifier.fillMaxSize().clip(RoundedRectangle(12.dp)).background(Palette.bubbleAgent), contentAlignment = Alignment.Center) {
+ Symbol(systemImage, size = 20.dp, tint = Palette.text)
+ }
+}
+
+@Composable internal fun SkillGlyph() = TileIcon("book.pages")
+
+/** Text that opens a web page (iOS `WebLink`). */
+@Composable internal fun WebLink(title: String, url: String, style: androidx.compose.ui.text.TextStyle = Type.body) {
+ val uri = LocalUriHandler.current
+ var failed by remember { mutableStateOf(false) }
+ Text(if (failed) "$title (couldn't open the browser)" else title,
+ Modifier.plainButton { failed = runCatching { uri.openUri(url) }.isFailure }, style = style.copy(textDecoration = TextDecoration.Underline),
+ color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+}
+
+/** A quiet "nothing here" message. */
+@Composable internal fun MarketEmpty(icon: String, title: String, detail: String) {
+ Column(Modifier.fillMaxWidth().padding(vertical = 40.dp), horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol(icon, size = 30.dp, tint = Palette.tertiary)
+ Text(title, style = Type.body.semibold, color = Palette.text)
+ Text(detail, style = Type.subheadline, color = Palette.secondary)
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt b/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt
new file mode 100644
index 00000000..f0ecd109
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt
@@ -0,0 +1,285 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.slideInHorizontally
+import androidx.compose.animation.slideOutHorizontally
+import androidx.compose.animation.togetherWith
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.layout.layout
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.AgentBackend
+import com.codync.android.core.CatalogPage
+import com.codync.android.core.MarketConnector
+import com.codync.android.core.MarketSkill
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import java.util.UUID
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.launch
+
+/**
+ * Extensions (iOS `MarketplaceView`): one page of agents, connectors, apps and skills for the bots on
+ * this computer. Installing happens on the computer; each bot turns connectors and skills on in its settings.
+ */
+@Composable internal fun MarketplaceView(state: AppState, store: AppStore) {
+ var showInstalled by remember { mutableStateOf(false) }
+ AnimatedContent(showInstalled, transitionSpec = {
+ (slideInHorizontally(Motion.layoutOffset) { if (targetState) it else -it } + fadeIn(Motion.fade())) togetherWith
+ (slideOutHorizontally(Motion.layoutOffset) { if (targetState) -it else it } + fadeOut(Motion.fade()))
+ }, label = "Extensions") { installed ->
+ if (installed) InstalledView(state, store) { showInstalled = false } else MarketplacePage(state, store) { showInstalled = true }
+ }
+}
+
+@Composable private fun MarketplacePage(state: AppState, store: AppStore, showInstalled: () -> Unit) {
+ val dismiss = LocalDismissModal.current
+ val scope = rememberCoroutineScope()
+ var search by remember { mutableStateOf("") }
+ // Bumped on each submitted search, so every section searches again.
+ var searchToken by remember { mutableIntStateOf(0) }
+ var connectors by remember { mutableStateOf(CatalogPage<MarketConnector>()) }
+ var connectorRequest by remember { mutableStateOf("") }
+ var connectorQuery by remember { mutableStateOf("") }
+ // The registry page after the ones shown; null at the end.
+ var connectorCursor by remember { mutableStateOf<String?>(null) }
+ var loadingConnectors by remember { mutableStateOf(true) }
+ var loadingMore by remember { mutableStateOf(false) }
+ var skills by remember { mutableStateOf(emptyList<MarketSkill>()) }
+ var loadingSkills by remember { mutableStateOf(true) }
+ var error by remember { mutableStateOf<String?>(null) }
+ var installing by remember { mutableStateOf<MarketConnector?>(null) }
+ var busySkill by remember { mutableStateOf<String?>(null) }
+ var addingConnector by remember { mutableStateOf(false) }
+ var writingSkill by remember { mutableStateOf(false) }
+ var viewingSkill by remember { mutableStateOf<SkillRef?>(null) }
+ var agent by remember { mutableStateOf<AgentBackend?>(null) }
+ var addingNode by remember { mutableStateOf(false) }
+ var showCredentials by remember { mutableStateOf(false) }
+ // Agents shown before "Load more agents".
+ var agentLimit by remember { mutableIntStateOf(10) }
+ val query = search.trim()
+ suspend fun loadConnectors() {
+ val request = UUID.randomUUID().toString()
+ connectorRequest = request; connectorQuery = query; loadingConnectors = true; loadingMore = false
+ try {
+ val page = store.marketConnectors(query, null)
+ if (connectorRequest != request) return
+ connectors = CatalogPage<MarketConnector>().append(page.items) { it.name }; connectorCursor = page.nextCursor?.takeIf(String::isNotBlank); error = null
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) {
+ if (connectorRequest != request) return
+ connectors = CatalogPage(); connectorCursor = null; error = failure.message ?: "Couldn't load connectors."
+ } finally { if (connectorRequest == request) loadingConnectors = false }
+ }
+ fun loadMoreConnectors() {
+ if (loadingMore || loadingConnectors) return
+ if (connectors.hasHidden) { connectors = connectors.reveal(); return }
+ val cursor = connectorCursor ?: return
+ val request = connectorRequest
+ loadingMore = true
+ scope.launch {
+ try {
+ val page = store.marketConnectors(connectorQuery, cursor)
+ if (connectorRequest != request) return@launch
+ connectors = connectors.append(page.items) { it.name }.reveal()
+ connectorCursor = page.nextCursor?.takeIf { it.isNotBlank() && it != cursor }; error = null
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { if (connectorRequest == request) error = failure.message ?: "Couldn't load more connectors." }
+ finally { if (connectorRequest == request) loadingMore = false }
+ }
+ }
+ fun submit() { searchToken++; agentLimit = 10; scope.launch { loadConnectors() } }
+ LaunchedEffect(Unit) { store.refreshPlugins(); store.refreshBackends() }
+ LaunchedEffect(Unit) { loadConnectors() }
+ LaunchedEffect(Unit) {
+ try { skills = store.marketSkills() }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't load skills." }
+ finally { loadingSkills = false }
+ }
+ val backends = agentBackends(state)
+ val agents = backends.filter { it.available || it.installed || it.curated }.filter { query.isEmpty() || it.name.contains(query, ignoreCase = true) }
+ val installedSkills = state.plugins?.skills.orEmpty()
+ val shownSkills = if (query.isEmpty()) skills else skills.filter { it.name.contains(query, true) || it.description.contains(query, true) }
+ val inset = Modifier.padding(horizontal = 44.dp)
+ Box(Modifier.fillMaxSize().background(Palette.background)) {
+ Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(vertical = 20.dp), verticalArrangement = Arrangement.spacedBy(28.dp)) {
+ Header(state, inset, showInstalled)
+ SearchBox(search, { search = it }, inset, ::submit) { search = ""; submit() }
+ if (agents.isNotEmpty()) Box(inset) {
+ MarketSection(if (query.isEmpty()) "Agents" else "Agents matching “$query”") {
+ if (backends.any { it.needsNode }) NodeNotice(state) { addingNode = true }
+ // The row runs edge to edge, past the page's margins.
+ LazyRow(Modifier.bleed(24.dp), contentPadding = PaddingValues(horizontal = 24.dp),
+ horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ items(agents.take(agentLimit), key = { it.id }) { backend -> AgentCard(backend) { agent = backend } }
+ }
+ if (agents.size > agentLimit) Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
+ SecondaryButton("Load more agents") { agentLimit += 10 }
+ }
+ }
+ }
+ Box(inset) {
+ MarketSection("Connectors") {
+ when {
+ loadingConnectors -> SkeletonRows()
+ connectors.items.isEmpty() -> Text(if (query.isEmpty()) "Couldn't load connectors." else "No connectors match “$query”.", style = Type.body, color = Palette.secondary)
+ else -> Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (c in connectors.visible) MarketRow(c.title, c.description ?: c.name, c.installed,
+ icon = { ServiceLogo(c.website, c.title, c.name) }) { installing = c }
+ if (connectors.hasHidden || connectorCursor != null) Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
+ SecondaryButton(if (loadingMore) "Loading…" else "Load more connectors", enabled = !loadingMore, action = ::loadMoreConnectors)
+ }
+ }
+ }
+ }
+ }
+ Box(inset) { ComposioSection(query, searchToken, state, store) }
+ Box(inset) {
+ MarketSection("Skills") {
+ if (loadingSkills) SkeletonRows()
+ else Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (s in shownSkills) {
+ val added = s.installed || installedSkills.any { it.id == s.source.lowercase() }
+ MarketRow(s.name, s.description, added, busy = busySkill == s.source,
+ open = { viewingSkill = SkillRef("catalog/${s.source}", s.name, s.description, s.source, added) }, icon = { SkillGlyph() }) {
+ busySkill = s.source
+ scope.launch {
+ try { store.installSkill(s.source) }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't add ${s.name}." }
+ finally { busySkill = null }
+ }
+ }
+ }
+ }
+ }
+ }
+ Box(inset) {
+ SecondaryButton({ showCredentials = true }) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol("lock.shield", size = 18.dp, tint = Palette.text)
+ Text("Credentials")
+ }
+ }
+ }
+ Box(inset) {
+ MarketSection("Make your own") {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ MarketRow("Custom connector", "Any MCP server: a command or a URL", added = false, addLabel = "New",
+ icon = { TileIcon("point.3.connected.trianglepath.dotted") }) { addingConnector = true }
+ MarketRow("Your own skill", "Write instructions a bot can follow", added = false, addLabel = "New",
+ icon = { TileIcon("square.and.pencil") }) { writingSkill = true }
+ }
+ }
+ }
+ error?.let { Text(it, inset, style = Type.footnote, color = Palette.danger) }
+ Text("Connectors come from the official MCP Registry, apps through Composio, skills from Anthropic, agents from the ACP registry. Everything installs on ${state.hostName}.",
+ inset, style = Type.footnote, color = Palette.tertiary)
+ }
+ // The sheet's own close, over the page.
+ Box(Modifier.align(Alignment.TopEnd).padding(8.dp)) { IconButton("Close", "xmark", action = dismiss) }
+ }
+ CodyncSheet(installing, { installing = null }) { InstallConnectorSheet(it, state, store) { scope.launch { loadConnectors() } } }
+ CodyncSheet(showCredentials, { showCredentials = false }) { CredentialsView(state, store) }
+ CodyncSheet(addingConnector, { addingConnector = false }) { CustomConnectorSheet(state, store) }
+ CodyncSheet(viewingSkill, { viewingSkill = null }) { SkillSheet(it, state, store) }
+ CodyncSheet(writingSkill, { writingSkill = false }) { NewSkillSheet(store) }
+ CodyncSheet(agent, { agent = null }) { AgentSheet(it, state, store) }
+ CodyncSheet(addingNode, { addingNode = false }) { SetupTerminal(null, "node", null, state, store) { addingNode = false } }
+}
+
+/** Widens a child past its parent's margins by `amount` on each side. */
+private fun Modifier.bleed(amount: Dp) = layout { measurable, constraints ->
+ val extra = amount.roundToPx()
+ val width = constraints.maxWidth + 2 * extra
+ val placeable = measurable.measure(constraints.copy(minWidth = width, maxWidth = width))
+ layout(constraints.maxWidth, placeable.height) { placeable.place(-extra, 0) }
+}
+
+/** The computer it all lives on, and the way to what's installed. */
+@Composable private fun Header(state: AppState, modifier: Modifier, showInstalled: () -> Unit) {
+ val connectors = state.plugins?.connectors.orEmpty()
+ val count = connectors.size + state.plugins?.skills.orEmpty().size
+ Column(modifier.padding(top = 28.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ ComputerBadge(state.hello?.text("device"), 32.dp)
+ Column {
+ Text("Extensions", style = Type.title2.semibold, color = Palette.text, maxLines = 1)
+ Text(state.hostName, style = Type.subheadline, color = Palette.secondary, maxLines = 1)
+ }
+ }
+ if (count > 0) Row(Modifier.plainButton(action = showInstalled), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Row(horizontalArrangement = Arrangement.spacedBy((-8).dp)) {
+ for (c in connectors.take(3)) ServiceLogo(null, c.name, c.registryName, 26.dp)
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text("$count installed", style = Type.body, color = Palette.secondary)
+ Text("Connectors & skills", style = Type.caption, color = Palette.secondary)
+ }
+ Symbol("chevron.right", size = 13.dp, tint = Palette.tertiary)
+ }
+ }
+}
+
+@Composable private fun SearchBox(text: String, onChange: (String) -> Unit, modifier: Modifier, submit: () -> Unit, clear: () -> Unit) {
+ Row(modifier.fillMaxWidth().height(38.dp).clip(Capsule()).background(Palette.bubbleAgent).padding(horizontal = 14.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Symbol("magnifyingglass", size = 18.dp, tint = Palette.secondary)
+ PlainTextField(text, onChange, Modifier.weight(1f), "Search agents, connectors and skills", singleLine = true,
+ imeAction = ImeAction.Search, actions = KeyboardActions(onSearch = { submit() }))
+ if (text.isNotEmpty()) Box(Modifier.plainButton(action = clear).semantics { contentDescription = "Clear search" }) {
+ Symbol("xmark.circle.fill", size = 18.dp, tint = Palette.tertiary)
+ }
+ }
+}
+
+/** Above the agents while some of them run on Node.js and the computer has none: one place to add Codync's copy for all. */
+@Composable private fun NodeNotice(state: AppState, add: () -> Unit) {
+ Row(Modifier.fillMaxWidth().clip(RoundedRectangle(18.dp)).background(Palette.bubbleAgent.copy(alpha = 0.45f))
+ .padding(horizontal = 14.dp, vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Symbol("shippingbox", Modifier.padding(top = 1.dp), size = 18.dp, tint = Palette.secondary)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text("Node.js isn't on ${state.hostName}", style = Type.subheadline.semibold, color = Palette.text)
+ Text("Some agents need it to run. Codync can add a copy just for them.", style = Type.caption, color = Palette.secondary)
+ }
+ Text("Add Node.js", Modifier.clip(Capsule()).background(Palette.accentFill).plainButton(action = add).padding(horizontal = 14.dp, vertical = 7.dp),
+ style = Type.subheadline.semibold, color = Palette.onAccent)
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MemoryCard.kt b/apps/android/app/src/main/kotlin/com/codync/android/MemoryCard.kt
new file mode 100644
index 00000000..66bfad9a
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MemoryCard.kt
@@ -0,0 +1,184 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.MemoryDraft
+import com.codync.android.core.MemoryFact
+import com.codync.android.design.*
+import java.text.DateFormat
+import java.util.Date
+
+private val FILTERS = listOf("all" to "All", "profile" to "About you", "pinned" to "Pinned", "review" to "Needs review")
+private enum class Backup { Export, Import }
+
+/** What a bot remembers, in its settings (iOS `MemoryCard`): search, edit, pin, history, backups. */
+@Composable fun MemoryCard(botId: String, store: AppStore) {
+ val scope = rememberCoroutineScope()
+ val memory = remember(botId) { MemoryModel(botId, store, scope) }
+ var editor by remember { mutableStateOf<MemoryDraft?>(null) }
+ var history by remember { mutableStateOf(false) }
+ var backup by remember { mutableStateOf<Backup?>(null) }
+ var confirmClear by remember { mutableStateOf(false) }
+ LaunchedEffect(botId) { memory.load() }
+ CardSection("Memory", accessory = {
+ IconButton("Add memory", "plus", enabled = !memory.busy) { editor = MemoryDraft.of(botId, null) }
+ DropdownMenu({ listOf(
+ MenuItem("Refresh", icon = "arrow.clockwise") { memory.refresh() },
+ MenuItem("Export", icon = "square.and.arrow.up") { backup = Backup.Export; memory.export() },
+ MenuItem("Import", icon = "square.and.arrow.down") { backup = Backup.Import },
+ MenuItem("Forget everything", icon = "trash", destructive = true, divider = true) { confirmClear = true },
+ ) }, Modifier.size(32.dp), label = "More") { Symbol("ellipsis", size = 20.dp, tint = Palette.secondary) }
+ }) {
+ row {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ SearchField(memory.query, { memory.search(it) }, Modifier.weight(1f), "Search memories")
+ ChoicePicker(memory.filter, FILTERS, { memory.search(memory.query, it) }, fill = Palette.bubbleAgent, label = "Show")
+ }
+ }
+ memory.error?.let { row { SelectionContainer { Text(it, style = Type.body, color = Palette.danger) } } }
+ if (!memory.loaded && memory.error == null) row { Text("Loading memory…", style = Type.body, color = Palette.secondary) }
+ if (memory.loaded && memory.facts.isEmpty()) row {
+ Column(Modifier.fillMaxWidth().padding(vertical = 18.dp), horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol("brain", size = 24.dp, tint = Palette.tertiary)
+ Text(if (memory.query.isEmpty() && memory.filter == "all") "Nothing yet. Important details are remembered as you chat." else "No matching memories.",
+ style = Type.body, color = Palette.secondary, textAlign = TextAlign.Center)
+ }
+ }
+ for (fact in memory.facts) row {
+ FactRow(fact, memory.busy, { editor = MemoryDraft.of(botId, fact) }) { pick ->
+ when (pick) {
+ "history" -> { history = true; memory.inspect(fact) }
+ else -> memory.action(pick, fact)
+ }
+ }
+ }
+ if (memory.nextOffset != null) row {
+ Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
+ LinkButton("Load more (${memory.total})", color = Palette.secondary) { memory.refresh(more = true) }
+ }
+ }
+ }
+ CodyncSheet(editor, { editor = null }) { MemoryEditor(memory, it) }
+ CodyncSheet(history, { history = false }) { MemoryHistory(memory) }
+ CodyncSheet(backup, { backup = null }) { MemoryBackup(memory, it) }
+ CodyncDialog("Forget everything this bot remembers?", confirmClear, { confirmClear = false }) {
+ listOf(DialogAction("Forget everything", destructive = true) { memory.action("clearMemory") })
+ }
+}
+
+@Composable private fun FactRow(fact: MemoryFact, busy: Boolean, open: () -> Unit, act: (String) -> Unit) {
+ Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Column(Modifier.weight(1f).plainButton(action = open), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ if (fact.pinned) Symbol("pin.fill", size = 12.dp, tint = Palette.secondary)
+ Text(fact.title.ifEmpty { fact.content.take(40) }, style = Type.body.semibold, color = Palette.text)
+ }
+ Text(fact.content, style = Type.body, color = Palette.text, maxLines = 3, overflow = TextOverflow.Ellipsis)
+ Text("${if (fact.kind == "profile") "About you" else fact.memoryType} · ${DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date(fact.createdAt))} · " +
+ "${fact.revisionCount} revisions", style = Type.caption, color = Palette.secondary)
+ }
+ DropdownMenu({ buildList {
+ add(MenuItem(if (fact.pinned) "Unpin" else "Pin", icon = if (fact.pinned) "pin.slash" else "pin") { act("pinMemory") })
+ add(MenuItem("History", icon = "clock.arrow.circlepath") { act("history") })
+ if (fact.reviewAfter != null) add(MenuItem("Mark reviewed", icon = "checkmark.circle") { act("reviewMemory") })
+ add(MenuItem("Forget", icon = "trash", destructive = true, divider = true) { act("forgetMemory") })
+ } }, Modifier.size(32.dp), enabled = !busy, label = "Memory actions") { Symbol("ellipsis", size = 20.dp, tint = Palette.secondary) }
+ }
+}
+
+/** Add or edit one memory (iOS `MemoryEditorView`). */
+@Composable private fun MemoryEditor(memory: MemoryModel, initial: MemoryDraft) {
+ val dismiss = LocalDismissModal.current
+ var draft by remember(initial) { mutableStateOf(initial) }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader(if (draft.id == null) "Add memory" else "Edit memory")
+ Column(Modifier.verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
+ LabeledBox("Title") { FieldBox(draft.title, { draft = draft.copy(title = it) }, "Title", fill = Palette.surface) }
+ LabeledBox("Memory") {
+ Box(Modifier.heightIn(min = 160.dp)) { FieldBox(draft.content, { draft = draft.copy(content = it) }, "", 7, 20, fill = Palette.surface) }
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ for ((scope, label) in listOf("project" to "Work", "personal" to "About you", "global" to "General")) {
+ LinkButton(label, style = if (draft.scope == scope) Type.body.semibold else Type.body) { draft = draft.copy(scope = scope) }
+ }
+ }
+ LabeledBox("Category") { FieldBox(draft.memoryType, { draft = draft.copy(memoryType = it) }, "Category", fill = Palette.surface, capitalize = false) }
+ LabeledBox("Topic (optional)") { FieldBox(draft.topicKey, { draft = draft.copy(topicKey = it) }, "Topic (optional)", fill = Palette.surface, capitalize = false) }
+ memory.error?.let { Text(it, style = Type.body, color = Palette.danger) }
+ PrimaryButton(if (memory.busy) "Saving…" else "Save", enabled = !memory.busy && draft.title.isNotBlank() && draft.content.isNotBlank()) {
+ memory.save(draft) { dismiss() }
+ }
+ }
+ }
+}
+
+@Composable private fun LabeledBox(title: String, content: @Composable () -> Unit) {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(title, style = Type.caption, color = Palette.secondary)
+ content()
+ }
+}
+
+/** A memory's earlier versions and the session it came from (iOS `MemoryHistoryView`). */
+@Composable private fun MemoryHistory(memory: MemoryModel) {
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader("Memory history")
+ Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
+ memory.error?.let { Text(it, style = Type.body, color = Palette.danger) }
+ val detail = memory.detail
+ if (detail == null) Text("Loading history…", style = Type.body, color = Palette.secondary)
+ else {
+ SelectionContainer { Text(detail.history.result, style = Type.body, color = Palette.text) }
+ detail.history.cursor?.let { cursor -> LinkButton("Older versions") { memory.inspect(detail.fact, cursor) } }
+ Text("Session timeline", style = Type.body.semibold, color = Palette.text)
+ SelectionContainer { Text(detail.timeline.result, style = Type.body, color = Palette.text) }
+ }
+ }
+ }
+}
+
+/** Copy an Engram backup out, or paste one in (iOS `MemoryBackupView`). */
+@Composable private fun MemoryBackup(memory: MemoryModel, mode: Backup) {
+ val dismiss = LocalDismissModal.current
+ var text by remember { mutableStateOf("") }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader(if (mode == Backup.Export) "Export memories" else "Import memories")
+ Column(Modifier.verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
+ Text(if (mode == Backup.Export) "Copy this Engram backup to keep or import your memories."
+ else "Paste an Engram JSON backup. Import merges memories and preserves newer changes. A backup is saved first.",
+ style = Type.body, color = Palette.text)
+ if (mode == Backup.Export) SelectionContainer {
+ Text(memory.backup.ifEmpty { "Preparing backup…" }, style = Type.caption.monospaced, color = Palette.text)
+ } else {
+ Box(Modifier.heightIn(min = 280.dp)) { FieldBox(text, { text = it }, "", 12, 40, style = Type.caption.monospaced, fill = Palette.surface, capitalize = false) }
+ PrimaryButton("Import", enabled = !memory.busy && text.isNotEmpty()) { memory.importBackup(text) { dismiss() } }
+ }
+ memory.error?.let { Text(it, style = Type.body, color = Palette.danger) }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MemoryModel.kt b/apps/android/app/src/main/kotlin/com/codync/android/MemoryModel.kt
new file mode 100644
index 00000000..81bdd230
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MemoryModel.kt
@@ -0,0 +1,112 @@
+package com.codync.android
+
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import com.codync.android.core.MemoryDetail
+import com.codync.android.core.MemoryDraft
+import com.codync.android.core.MemoryFact
+import com.codync.android.core.MemoryListing
+import com.codync.android.core.WireJson
+import java.util.UUID
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.decodeFromJsonElement
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.put
+
+/** One bot's Engram memory on the computer (iOS `MemoryStore`): search, edit, history and backups. */
+internal class MemoryModel(private val botId: String, private val store: AppStore, private val scope: CoroutineScope) {
+ var facts by mutableStateOf(emptyList<MemoryFact>()); private set
+ var query by mutableStateOf(""); private set
+ var filter by mutableStateOf("all"); private set
+ var total by mutableIntStateOf(0); private set
+ var nextOffset by mutableStateOf<Int?>(null); private set
+ var loaded by mutableStateOf(false); private set
+ var busy by mutableStateOf(false); private set
+ var error by mutableStateOf<String?>(null)
+ var detail by mutableStateOf<MemoryDetail?>(null); private set
+ var backup by mutableStateOf(""); private set
+ private var request = 0
+ private var detailRequest = 0
+ private var searching: Job? = null
+
+ suspend fun load(more: Boolean = false) {
+ val asked = ++request
+ val offset = (if (more) nextOffset else 0) ?: return
+ error = null
+ try {
+ val listing = MemoryListing.decode(store.hostCall("memory", buildJsonObject {
+ put("botId", botId); put("query", query); put("filter", filter); put("offset", offset)
+ }))
+ if (asked != request) return
+ facts = if (more) facts + listing.facts else listing.facts
+ total = listing.total; nextOffset = listing.nextOffset; loaded = true
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { if (asked == request) error = failure.message ?: "Couldn't load memory." }
+ }
+
+ fun refresh(more: Boolean = false) = scope.launch { load(more) }
+
+ fun search(text: String, filter: String = this.filter) {
+ query = text; this.filter = filter; request++
+ searching?.cancel()
+ searching = scope.launch { delay(250); load() }
+ }
+
+ fun action(method: String, fact: MemoryFact? = null) = perform {
+ store.hostCall(method, buildJsonObject { put("botId", botId); fact?.let { put("id", it.id); put("pinned", !it.pinned) } })
+ }
+
+ fun save(draft: MemoryDraft, done: () -> Unit) = perform(done) { store.hostCall("saveMemory", draft.body()) }
+
+ fun inspect(fact: MemoryFact, cursor: Int? = null) = scope.launch {
+ val asked = ++detailRequest
+ error = null
+ if (cursor == null) detail = null
+ try {
+ val value = WireJson.decodeFromJsonElement<MemoryDetail>(store.hostCall("memoryDetail", buildJsonObject {
+ put("botId", botId); put("id", fact.id); cursor?.let { put("historyCursor", it) }
+ }))
+ if (asked == detailRequest) detail = value
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { if (asked == detailRequest) error = failure.message ?: "Couldn't load the history." }
+ }
+
+ fun export() = scope.launch {
+ backup = ""; error = null
+ try {
+ val result = store.hostCall("exportMemory", buildJsonObject { put("botId", botId) }).jsonObject
+ // A big backup comes back as a file to read.
+ val upload = result["uploadId"]?.jsonPrimitive?.contentOrNull
+ backup = if (upload != null) store.hostFiles().readText(botId, upload) else result["json"]?.jsonPrimitive?.contentOrNull.orEmpty()
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Couldn't export memory." }
+ }
+
+ fun importBackup(text: String, done: () -> Unit) = perform(done) {
+ if (text.toByteArray().size > 384 * 1024) {
+ val id = UUID.randomUUID().toString()
+ store.hostFiles().uploadText(botId, id, "engram-backup.json", text)
+ store.hostCall("importMemory", buildJsonObject { put("botId", botId); put("uploadId", id) })
+ } else store.hostCall("importMemory", buildJsonObject { put("botId", botId); put("json", text) })
+ }
+
+ private fun perform(done: () -> Unit = {}, work: suspend () -> Unit) {
+ if (busy) return
+ busy = true; error = null
+ scope.launch {
+ try { work(); load(); done() }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Something went wrong." }
+ finally { busy = false }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt
new file mode 100644
index 00000000..37970143
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt
@@ -0,0 +1,231 @@
+package com.codync.android
+
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.PickVisualMediaRequest
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.expandVertically
+import androidx.compose.animation.shrinkVertically
+import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import androidx.compose.animation.animateColorAsState
+import androidx.compose.animation.animateContentSize
+import androidx.compose.animation.core.animateDpAsState
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.scaleIn
+import androidx.compose.animation.scaleOut
+import androidx.compose.animation.togetherWith
+import androidx.compose.foundation.ExperimentalFoundationApi
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.content.ReceiveContentListener
+import androidx.compose.foundation.content.consume
+import androidx.compose.foundation.content.contentReceiver
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.foundation.text.input.TextFieldLineLimits
+import androidx.compose.foundation.text.input.rememberTextFieldState
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.snapshotFlow
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.platform.LocalClipboard
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.*
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.coroutines.launch
+
+/** What the composer's one trailing button does now; it morphs between them. */
+private enum class Trailing { Stop, Call, Send }
+
+/**
+ * The message box under a chat or a thread, as iOS `Composer`: a glass + for files, a glass
+ * field whose trailing button morphs between call, send and stop.
+ */
+@OptIn(ExperimentalFoundationApi::class)
+@Composable fun MessageComposer(bot: Bot, thread: String?, state: AppState, store: AppStore, onCall: (() -> Unit)?) {
+ val lane = ComposerDraft.lane(bot.id, thread)
+ val draft = state.drafts[lane]
+ val text = rememberTextFieldState(initialText = draft?.text.orEmpty())
+ val files = draft?.files.orEmpty()
+ val queuing = "draft-send:" + lane in state.busy
+ val importing = "attachments" in state.busy
+ // What this box sent to the store, so a draft set elsewhere (a routine request) can be told from our own echo.
+ val echoes = remember(lane) { ArrayDeque<String>() }
+ LaunchedEffect(text, bot.id, thread) {
+ snapshotFlow { text.text.toString() }.collect {
+ echoes.addLast(it); while (echoes.size > 32) echoes.removeFirst()
+ store.editDraft(bot.id, thread, it)
+ }
+ }
+ LaunchedEffect(draft?.text) {
+ val external = draft?.text.orEmpty()
+ if (external != text.text.toString() && external !in echoes) text.setTextAndPlaceCursorAtEnd(external)
+ }
+ val clipboard = LocalClipboard.current
+ val scope = rememberCoroutineScope()
+ val photos = rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(10)) { uris ->
+ if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, thread, it) }
+ }
+ val documents = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
+ if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, thread, it) }
+ }
+ val receiver = remember(bot.id, importing, queuing) { ReceiveContentListener { content ->
+ if (bot.kind == "group" || importing || queuing) content else {
+ val uris = mutableListOf<android.net.Uri>()
+ val remaining = content.consume { item -> item.uri?.takeIf { it.scheme == "content" }?.let { uris.add(it); true } ?: false }
+ if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, thread, it) }
+ remaining
+ }
+ } }
+ val online = state.actualConnection is LinkState.Ready
+ val empty = text.text.isBlank() && files.isEmpty()
+ // Offline computers still take text when the relay can hold it; files need the computer.
+ val canSend = !empty && !importing && !queuing && (online || files.isEmpty())
+ val working = bot.status in listOf("working", "needsInput") && (thread == null || bot.workingThread == thread)
+ val trailing = when {
+ working && empty -> Trailing.Stop
+ onCall != null && empty && thread == null && bot.kind != "group" -> Trailing.Call
+ else -> Trailing.Send
+ }
+ val placeholder = when {
+ thread != null -> "Reply…"
+ bot.kind == "group" -> "Message everyone · @ to ask one bot"
+ working -> "Queue a message for ${bot.name}"
+ else -> "Ask ${bot.name}"
+ }
+ val typed = text.text.toString()
+ val commands = SlashCommands.query(typed)?.let { SlashCommands.list(bot, it, state.plugins?.skills.orEmpty(), state.hello?.text("version")) }.orEmpty()
+ val mentions = if (bot.kind != "group") emptyList() else mentionQuery(typed)?.let { query ->
+ bot.members.mapNotNull { id -> state.bots.firstOrNull { it.id == id } }.filter { query.isEmpty() || it.name.contains(query, true) }
+ }.orEmpty()
+ fun clear() = text.edit { replace(0, length, "") }
+ fun run(command: SlashCommand) {
+ val skill = command.skill
+ when {
+ skill != null -> text.setTextAndPlaceCursorAtEnd("/$skill ")
+ command.name == "fast" -> { store.command("updateBot", buildJsonObject { put("id", bot.id); put("fastMode", !bot.fastMode) }, "roster:" + bot.id); clear() }
+ else -> { store.command("newSession", body("botId" to bot.id)); clear() }
+ }
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ AnimatedVisibility(commands.isNotEmpty(), enter = fadeIn(Motion.fade()) + expandVertically(Motion.layoutSize),
+ exit = fadeOut(Motion.fade()) + shrinkVertically(Motion.layoutSize)) {
+ CommandList(commands, ::run, Modifier.padding(horizontal = 16.dp))
+ }
+ AnimatedVisibility(mentions.isNotEmpty(), enter = fadeIn(Motion.fade()), exit = fadeOut(Motion.fade())) {
+ MentionChips(mentions, state.bots) { member -> text.setTextAndPlaceCursorAtEnd(typed.substring(0, typed.lastIndexOf('@')) + "@${member.name} ") }
+ }
+ Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, top = 6.dp, bottom = 16.dp), verticalAlignment = Alignment.Bottom,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (bot.kind != "group") {
+ val (source, pressed) = rememberPress()
+ DropdownMenu({ listOf(
+ MenuItem("Photos", icon = "photo.on.rectangle") { photos.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) },
+ MenuItem("Files", icon = "folder") { documents.launch(arrayOf("*/*")) },
+ MenuItem("Paste", icon = "doc.on.clipboard") { scope.launch {
+ val data = clipboard.getClipEntry()?.clipData
+ val uris = if (data == null) emptyList() else (0 until data.itemCount).mapNotNull { data.getItemAt(it).uri }
+ if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, thread, it) }
+ } },
+ ) }, Modifier.size(FIELD_HEIGHT).glass(Capsule(), pressed = pressed), enabled = !queuing, label = "Add files") {
+ Symbol("plus", size = 26.dp, tint = Palette.text)
+ }
+ }
+ Column(Modifier.weight(1f).glass(RoundedRectangle(24.dp)).animateContentSize(Motion.layoutSize)) {
+ if (files.isNotEmpty()) Row(Modifier.horizontalScroll(rememberScrollState()).padding(start = 10.dp, end = 10.dp, top = 8.dp),
+ horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ for (file in files) ComposerAttachment(file) { store.removeDraftFile(bot.id, thread, file) }
+ }
+ Row(Modifier.padding(start = 18.dp, end = 6.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.Bottom,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ BasicTextField(state = text, enabled = !queuing, modifier = Modifier.weight(1f).contentReceiver(receiver).padding(vertical = 10.dp),
+ textStyle = Type.body.copy(color = Palette.text), cursorBrush = SolidColor(Palette.accent),
+ lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 8),
+ decorator = { input -> Box { if (text.text.isEmpty()) Text(placeholder, style = Type.body, color = Palette.tertiary, maxLines = 1); input() } })
+ TrailingButton(trailing, canSend, Modifier.padding(bottom = 4.dp)) {
+ when (trailing) {
+ Trailing.Stop -> store.command("stop", body("botId" to bot.id))
+ Trailing.Call -> onCall?.invoke()
+ Trailing.Send -> {
+ val command = if (files.isEmpty()) SlashCommands.builtIn(bot, typed) else null
+ if (command != null) run(command) else store.sendDraft(bot.id, thread, typed) { clear() }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+private val FIELD_HEIGHT = 54.dp
+
+/** One button that morphs between call, send and stop: its symbol swaps, its fill crossfades and the capsule narrows. */
+@Composable private fun TrailingButton(state: Trailing, canSend: Boolean, modifier: Modifier, action: () -> Unit) {
+ val enabled = state != Trailing.Send || canSend
+ val fill by animateColorAsState(if (state == Trailing.Send && !canSend) Palette.accentDim else Palette.accentFill, Motion.morph(), label = "Fill")
+ val ink = if (state == Trailing.Send && !canSend) Palette.tertiary else Palette.onAccent
+ val width by animateDpAsState(if (state == Trailing.Call) 46.dp else 34.dp, Motion.morph(), label = "Width")
+ val (source, pressed) = rememberPress()
+ Box(modifier.pressScale(pressed).size(width, 34.dp).clip(Capsule()).background(fill)
+ .clickable(source, null, enabled = enabled, role = Role.Button, onClick = action)
+ .semantics { contentDescription = when (state) { Trailing.Stop -> "Stop"; Trailing.Call -> "Call"; Trailing.Send -> "Send" } },
+ contentAlignment = Alignment.Center) {
+ AnimatedContent(state, transitionSpec = { (fadeIn(Motion.morph()) + scaleIn(Motion.morph(), 0.6f)) togetherWith
+ (fadeOut(Motion.morph()) + scaleOut(Motion.morph(), 0.6f)) }, label = "Symbol") { shown ->
+ when (shown) {
+ Trailing.Stop -> Symbol("stop.fill", size = 16.dp, tint = ink)
+ Trailing.Call -> Symbol("waveform", size = 20.dp, tint = ink)
+ Trailing.Send -> Symbol("arrow.up", size = 19.dp, tint = ink)
+ }
+ }
+ }
+}
+
+/** A file going out with the next message, removable before it's sent. */
+@Composable private fun ComposerAttachment(file: OutgoingFile, remove: () -> Unit) {
+ Row(Modifier.clip(RoundedRectangle(12.dp)).background(Palette.surface).padding(start = 10.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Symbol(if (file.name.substringAfterLast('.', "").lowercase() in listOf("png", "jpg", "jpeg", "heic", "gif", "webp")) "photo" else "doc",
+ size = 16.dp, tint = Palette.secondary)
+ Column {
+ Text(file.name, Modifier.width(120.dp), style = Type.footnote, color = Palette.text, maxLines = 1)
+ Text(formatBytes(file.size), style = Type.caption2, color = Palette.tertiary)
+ }
+ Box(Modifier.size(28.dp).clickable(role = Role.Button, onClick = remove).semantics { contentDescription = "Remove ${file.name}" },
+ contentAlignment = Alignment.Center) { Symbol("xmark.circle.fill", size = 18.dp, tint = Palette.tertiary) }
+ }
+}
+
+fun formatBytes(size: Long): String = when {
+ size >= 1024 * 1024 -> "%.1f MB".format(size / (1024.0 * 1024))
+ size >= 1024 -> "%.0f KB".format(size / 1024.0)
+ else -> "$size bytes"
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt b/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt
new file mode 100644
index 00000000..d767ab7c
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt
@@ -0,0 +1,159 @@
+package com.codync.android
+
+import android.content.ContentValues
+import android.content.Context
+import android.database.sqlite.SQLiteDatabase
+import android.database.sqlite.SQLiteOpenHelper
+import com.codync.android.core.Bot
+import com.codync.android.core.Entry
+import com.codync.android.core.MirrorEvent
+import com.codync.android.core.MirrorSnapshot
+import com.codync.android.core.PendingSend
+import com.codync.android.core.SendStatus
+import com.codync.android.core.WireJson
+import java.io.File
+import kotlinx.serialization.encodeToString
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.jsonObject
+
+/** All entity writes, send reconciliation and the event cursor commit together. */
+class MirrorDatabase(context: Context, directory: File, computerId: String) :
+ SQLiteOpenHelper(context, File(directory, "mirror-$computerId.db").absolutePath, null, 2) {
+ init { require(computerId.matches(Regex("[A-Za-z0-9_-]{22}"))) }
+
+ override fun onCreate(db: SQLiteDatabase) {
+ db.execSQL("CREATE TABLE meta(k TEXT PRIMARY KEY, v TEXT NOT NULL)")
+ db.execSQL("CREATE TABLE bots(id TEXT PRIMARY KEY, rev INTEGER NOT NULL, deleted INTEGER NOT NULL, payload TEXT NOT NULL)")
+ db.execSQL("CREATE TABLE entries(id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, thread_id TEXT, seq INTEGER NOT NULL, rev INTEGER NOT NULL, nonce TEXT, payload TEXT NOT NULL)")
+ db.execSQL("CREATE INDEX entries_lane ON entries(bot_id, thread_id, seq)")
+ db.execSQL("CREATE INDEX entries_nonce ON entries(bot_id, nonce)")
+ db.execSQL("CREATE TABLE pending(nonce TEXT PRIMARY KEY, created INTEGER NOT NULL, payload TEXT NOT NULL)")
+ db.execSQL("CREATE TABLE history(lane TEXT PRIMARY KEY)")
+ }
+ override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
+ require(oldVersion == 1 && newVersion == 2) { "Unsupported mirror schema" }
+ db.execSQL("ALTER TABLE entries ADD COLUMN nonce TEXT")
+ db.execSQL("CREATE INDEX entries_nonce ON entries(bot_id, nonce)")
+ rows(db, "SELECT payload FROM entries") { WireJson.decodeFromString<Entry>(it) }.forEach { entry ->
+ if (entry.kind == "user") db.update("entries", ContentValues().apply { put("nonce", entry.clientNonce) }, "id=?", arrayOf(entry.id))
+ }
+ }
+
+ @Synchronized fun snapshot(): MirrorSnapshot {
+ val db = readableDatabase
+ return MirrorSnapshot(
+ rows(db, "SELECT payload FROM bots WHERE deleted=0") { WireJson.decodeFromString<Bot>(it) },
+ rows(db, "SELECT payload FROM entries ORDER BY seq") { WireJson.decodeFromString<Entry>(it) },
+ rows(db, "SELECT payload FROM pending ORDER BY created") { WireJson.decodeFromString<PendingSend>(it) },
+ meta(db, "rev")?.toLong() ?: 0,
+ meta(db, "usage")?.let { WireJson.parseToJsonElement(it).jsonObject } ?: JsonObject(emptyMap()),
+ meta(db, "screen")?.let { WireJson.parseToJsonElement(it).jsonObject },
+ )
+ }
+
+ @Synchronized fun revision(): Long = meta(readableDatabase, "rev")?.toLong() ?: 0
+
+ @Synchronized fun setStamp(hostId: String, stamp: String) = transaction { db ->
+ if (meta(db, "hostId")?.let { it != hostId } == true) reset(db)
+ if (meta(db, "stamp")?.let { it != stamp } == true) setMeta(db, "rev", "0")
+ setMeta(db, "hostId", hostId)
+ setMeta(db, "stamp", stamp)
+ }
+
+ @Synchronized fun apply(event: MirrorEvent) = apply(listOf(event))
+ @Synchronized fun apply(events: List<MirrorEvent>) = transaction { db ->
+ for (event in events) when (event) {
+ is MirrorEvent.Hello -> {
+ if (meta(db, "hostId")?.let { it != event.hostId } == true) reset(db)
+ setMeta(db, "hostId", event.hostId)
+ if (event.rev < (meta(db, "rev")?.toLong() ?: 0)) reset(db)
+ setMeta(db, "usage", event.usage.toString())
+ event.screen?.let { setMeta(db, "screen", it.toString()) }
+ // Hello's head revision precedes catch-up; it is never a checkpoint.
+ }
+ is MirrorEvent.BotChanged -> { writeBot(db, event.bot); bump(db, event.bot.rev) }
+ is MirrorEvent.EntryChanged -> { writeEntry(db, event.entry); bump(db, event.entry.rev) }
+ is MirrorEvent.Usage -> setMeta(db, "usage", event.value.toString())
+ is MirrorEvent.Screen -> setMeta(db, "screen", event.value.toString())
+ MirrorEvent.Resync, MirrorEvent.Ignored -> Unit
+ }
+ }
+
+ // RPC replies and history may arrive ahead of live events; they must not advance the event cursor.
+ @Synchronized fun receive(bot: Bot) = transaction { writeBot(it, bot) }
+ @Synchronized fun receive(bots: Collection<Bot>) = transaction { db -> bots.forEach { writeBot(db, it) } }
+ @Synchronized fun receive(entries: List<Entry>) = transaction { db -> entries.forEach { writeEntry(db, it) } }
+ @Synchronized fun rewind() = transaction { setMeta(it, "rev", "0") }
+ @Synchronized fun save(send: PendingSend) = transaction { db ->
+ writePending(db, send)
+ }
+ private fun writePending(db: SQLiteDatabase, send: PendingSend) {
+ val confirmed = db.rawQuery("SELECT 1 FROM entries WHERE bot_id=? AND nonce=?", arrayOf(send.botId, send.nonce)).use { it.moveToFirst() }
+ if (confirmed) return
+ val count = db.compileStatement("SELECT COUNT(*) FROM pending").use { it.simpleQueryForLong() }
+ val exists = db.rawQuery("SELECT 1 FROM pending WHERE nonce=?", arrayOf(send.nonce)).use { it.moveToFirst() }
+ require(exists || count < 200) { "Too many pending messages. Retry or discard older messages first." }
+ check(db.insertWithOnConflict("pending", null, ContentValues().apply {
+ put("nonce", send.nonce); put("created", send.createdAt); put("payload", WireJson.encodeToString(send))
+ }, SQLiteDatabase.CONFLICT_REPLACE) != -1L) { "Couldn't save the pending message." }
+ }
+ @Synchronized fun discard(nonce: String) = transaction { it.delete("pending", "nonce=?", arrayOf(nonce)) }
+ @Synchronized fun recoverInterrupted() = transaction { db ->
+ rows(db, "SELECT payload FROM pending") { WireJson.decodeFromString<PendingSend>(it) }
+ .filter { it.status == SendStatus.Sending }.forEach { writePending(db, it.copy(status = SendStatus.Failed,
+ error = "Sending was interrupted. Retry uses the same message ID.")) }
+ }
+ @Synchronized fun historyComplete(botId: String): Boolean = readableDatabase.rawQuery(
+ "SELECT 1 FROM history WHERE lane=?", arrayOf(botId)).use { it.moveToFirst() }
+ @Synchronized fun finishHistory(botId: String) = transaction { db ->
+ db.insertWithOnConflict("history", null, ContentValues().apply { put("lane", botId) }, SQLiteDatabase.CONFLICT_IGNORE)
+ }
+
+ private fun writeBot(db: SQLiteDatabase, bot: Bot) {
+ val revision = db.rawQuery("SELECT rev FROM bots WHERE id=?", arrayOf(bot.id)).use { if (it.moveToFirst()) it.getLong(0) else -1 }
+ if (revision > bot.rev) return
+ check(db.insertWithOnConflict("bots", null, ContentValues().apply {
+ put("id", bot.id); put("rev", bot.rev); put("deleted", if (bot.deleted) 1 else 0); put("payload", WireJson.encodeToString(bot))
+ }, SQLiteDatabase.CONFLICT_REPLACE) != -1L) { "Couldn't save the bot update." }
+ if (bot.deleted) {
+ db.delete("entries", "bot_id=?", arrayOf(bot.id))
+ rows(db, "SELECT payload FROM pending") { WireJson.decodeFromString<PendingSend>(it) }
+ .filter { it.botId == bot.id }.forEach { db.delete("pending", "nonce=?", arrayOf(it.nonce)) }
+ db.delete("history", "lane=?", arrayOf(bot.id))
+ }
+ }
+ private fun writeEntry(db: SQLiteDatabase, entry: Entry) {
+ val deleted = db.rawQuery("SELECT deleted FROM bots WHERE id=?", arrayOf(entry.botId)).use { it.moveToFirst() && it.getInt(0) == 1 }
+ if (deleted) return
+ val revision = db.rawQuery("SELECT rev FROM entries WHERE id=?", arrayOf(entry.id)).use { if (it.moveToFirst()) it.getLong(0) else -1 }
+ if (revision > entry.rev) return
+ check(db.insertWithOnConflict("entries", null, ContentValues().apply {
+ put("id", entry.id); put("bot_id", entry.botId); put("thread_id", entry.threadId)
+ put("seq", entry.seq); put("rev", entry.rev); put("payload", WireJson.encodeToString(entry))
+ put("nonce", entry.clientNonce?.takeIf { entry.kind == "user" })
+ }, SQLiteDatabase.CONFLICT_REPLACE) != -1L) { "Couldn't save the conversation update." }
+ entry.clientNonce?.takeIf { entry.kind == "user" && it.isNotEmpty() }?.let { db.delete("pending", "nonce=?", arrayOf(it)) }
+ }
+ private fun reset(db: SQLiteDatabase) {
+ listOf("bots", "entries", "history").forEach { db.delete(it, null, null) }
+ setMeta(db, "rev", "0")
+ db.delete("meta", "k IN ('usage','screen')", null)
+ }
+ private fun bump(db: SQLiteDatabase, rev: Long) = setMeta(db, "rev", maxOf(rev, meta(db, "rev")?.toLong() ?: 0).toString())
+ private fun meta(db: SQLiteDatabase, key: String): String? = db.rawQuery("SELECT v FROM meta WHERE k=?", arrayOf(key)).use {
+ if (it.moveToFirst()) it.getString(0) else null
+ }
+ private fun setMeta(db: SQLiteDatabase, key: String, value: String) {
+ check(db.insertWithOnConflict("meta", null, ContentValues().apply { put("k", key); put("v", value) }, SQLiteDatabase.CONFLICT_REPLACE) != -1L) {
+ "Couldn't save the conversation checkpoint."
+ }
+ }
+ private fun <T> rows(db: SQLiteDatabase, query: String, decode: (String) -> T): List<T> = db.rawQuery(query, null).use {
+ buildList { while (it.moveToNext()) add(decode(it.getString(0))) }
+ }
+ private fun transaction(block: (SQLiteDatabase) -> Unit) {
+ val db = writableDatabase
+ db.beginTransaction()
+ try { block(db); db.setTransactionSuccessful() } finally { db.endTransaction() }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/NativeAccounts.kt b/apps/android/app/src/main/kotlin/com/codync/android/NativeAccounts.kt
new file mode 100644
index 00000000..53e2057e
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/NativeAccounts.kt
@@ -0,0 +1,100 @@
+package com.codync.android
+
+import android.app.Activity
+import com.clerk.api.Clerk
+import com.clerk.api.ClerkConfigurationOptions
+import com.clerk.api.network.serialization.ClerkResult
+import com.clerk.api.network.serialization.errorMessage
+import com.clerk.api.session.Session
+import com.clerk.api.sso.OAuthProvider
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.launch
+import java.io.IOException
+
+data class SavedAccount(val userId: String, val sessionId: String, val email: String, val avatar: String?)
+data class AccountState(val ready: Boolean = false, val configured: Boolean = NativeAccounts.configured,
+ val userId: String? = null, val accounts: List<SavedAccount> = emptyList(),
+ val multiple: Boolean = false, val error: String? = null)
+
+/** Clerk owns browser authentication, encrypted credentials and session restoration. */
+object NativeAccounts {
+ val configured = BuildConfig.CLERK_PUBLISHABLE_KEY.startsWith("pk_test_") || BuildConfig.CLERK_PUBLISHABLE_KEY.startsWith("pk_live_")
+
+ fun initialize(activity: Activity) {
+ if (configured) Clerk.initialize(activity, BuildConfig.CLERK_PUBLISHABLE_KEY,
+ ClerkConfigurationOptions(enableDebugMode = false, telemetryEnabled = false))
+ }
+
+ fun observe(scope: CoroutineScope, update: suspend (AccountState) -> Unit) = scope.launch {
+ if (!configured) { update(AccountState(ready = true)); return@launch }
+ combine(Clerk.isInitialized, Clerk.sessionFlow, Clerk.sessionsFlow,
+ Clerk.multiSessionModeIsEnabledFlow, Clerk.initializationError) { ready, selected, sessions, multiple, error ->
+ val accounts = sessions.filter { it.status == Session.SessionStatus.ACTIVE && it.expireAt > System.currentTimeMillis() }
+ .mapNotNull { session -> session.user?.let { user -> SavedAccount(user.id, session.id,
+ user.primaryEmailAddress?.emailAddress ?: "Codync account", user.imageUrl.takeIf { it.startsWith("https://") }) } }
+ .distinctBy(SavedAccount::userId)
+ val selectedId = selected?.takeIf { it.status == Session.SessionStatus.ACTIVE && it.expireAt > System.currentTimeMillis() }?.user?.id
+ AccountState(ready, true, selectedId, accounts, multiple,
+ if (error != null && !ready) "Couldn't restore sign-in. Check your connection and retry." else null)
+ }.collect { update(it) }
+ }
+
+ suspend fun signIn(apple: Boolean) {
+ require(Clerk.isInitialized.value) { "Wait for sign-in to finish loading." }
+ val result = Clerk.auth.signInWithOAuth(if (apple) OAuthProvider.APPLE else OAuthProvider.GOOGLE)
+ when (result) {
+ is ClerkResult.Failure -> throw IOException(result.errorMessage)
+ is ClerkResult.Success -> {
+ val sessionId = result.value.signIn?.createdSessionId ?: result.value.signUp?.createdSessionId
+ require(sessionId != null) { "Sign-in needs additional verification. Continue using the other sign-in options." }
+ val activated = Clerk.auth.setActive(sessionId)
+ requireSuccess(activated)
+ }
+ }
+ }
+
+ suspend fun hostedSignIn() {
+ val result = Clerk.auth.startHostedAuth()
+ requireSuccess(result)
+ }
+
+ suspend fun switch(account: SavedAccount) {
+ val result = Clerk.auth.setActive(account.sessionId)
+ requireSuccess(result)
+ }
+
+ suspend fun signOut(sessionId: String) {
+ // An explicit session keeps local credentials intact if the server rejects logout.
+ val result = Clerk.auth.signOut(sessionId)
+ requireSuccess(result)
+ }
+
+ suspend fun reset() {
+ if (!configured) return
+ // The all-session API clears the SDK's local credentials even when the network is down.
+ val result = Clerk.auth.signOut()
+ if (result is ClerkResult.Failure) {
+ val error = result.throwable
+ if (error is CancellationException) throw error
+ }
+ }
+
+ fun retry() { if (configured) Clerk.reinitialize() }
+
+ suspend fun token(expectedUser: String): String {
+ require(Clerk.activeSession?.user?.id == expectedUser) { "Sign in again to reach your account." }
+ val result = Clerk.auth.getToken()
+ require(Clerk.activeSession?.user?.id == expectedUser) { "The active account changed." }
+ return when (result) {
+ is ClerkResult.Success -> result.value
+ is ClerkResult.Failure -> throw IOException("Couldn't refresh sign-in. Check your connection and try again.")
+ }
+ }
+
+ private fun requireSuccess(result: ClerkResult<*, com.clerk.api.network.model.error.ClerkErrorResponse>) {
+ if (result is ClerkResult.Failure) throw IOException(result.errorMessage)
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt b/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt
new file mode 100644
index 00000000..dd6309c0
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt
@@ -0,0 +1,277 @@
+package com.codync.android
+
+import android.content.ClipData
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.Crossfade
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.slideInHorizontally
+import androidx.compose.animation.slideOutHorizontally
+import androidx.compose.animation.togetherWith
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.RowScope
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.key
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.ClipEntry
+import androidx.compose.ui.platform.LocalClipboard
+import androidx.compose.ui.platform.LocalUriHandler
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.input.KeyboardCapitalization
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import java.net.Inet4Address
+import java.net.NetworkInterface
+
+private enum class Step { Install, Scan }
+private enum class ComputerOS { Mac, Linux }
+
+/**
+ * Pair with a computer running codync-host, one thing per page: install it, then scan its code
+ * (iOS `PairingView`). In a sheet it has a close button and closes once paired.
+ */
+@Composable internal fun PairingView(state: AppState, store: AppStore, inModal: Boolean = false, onSkip: () -> Unit = {},
+ leading: @Composable RowScope.() -> Unit = {}) {
+ var step by rememberSaveable { mutableStateOf(Step.Install) }
+ var os by rememberSaveable { mutableStateOf(ComputerOS.Mac) }
+ val dismiss = LocalDismissModal.current
+ BackHandler(step == Step.Scan) { step = Step.Install }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ScreenHeader({ if (step == Step.Scan) BackButton { step = Step.Install } else leading() }, {
+ Row(Modifier.semantics(mergeDescendants = true) { contentDescription = if (step == Step.Install) "Step 1 of 2" else "Step 2 of 2" },
+ horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Box(Modifier.size(18.dp, 4.dp).clip(Capsule()).background(Palette.text))
+ Box(Modifier.size(18.dp, 4.dp).clip(Capsule()).background(if (step == Step.Scan) Palette.text else Palette.accentDim))
+ }
+ }) { if (inModal) IconButton("Close", "xmark", action = dismiss) }
+ AnimatedContent(step, Modifier.weight(1f), transitionSpec = {
+ val forward = targetState == Step.Scan
+ (slideInHorizontally(Motion.spring(0.45f)) { if (forward) it else -it } + fadeIn(Motion.spring(0.45f))) togetherWith
+ (slideOutHorizontally(Motion.spring(0.45f)) { if (forward) -it else it } + fadeOut(Motion.spring(0.45f)))
+ }, label = "Pairing step") { shown ->
+ when (shown) {
+ Step.Install -> InstallPage(os, { os = it }) { step = Step.Scan }
+ Step.Scan -> ScanPage(state, store, os) { if (inModal) dismiss() }
+ }
+ }
+ AnimatedVisibility(step == Step.Scan, enter = fadeIn(Motion.fade()), exit = fadeOut(Motion.fade())) {
+ Box(Modifier.padding(horizontal = 24.dp).padding(bottom = 12.dp)) {
+ WideButton("Skip", primary = false) { if (inModal) dismiss() else onSkip() }
+ }
+ }
+ }
+}
+
+// MARK: - Install
+
+@Composable private fun InstallPage(os: ComputerOS, choose: (ComputerOS) -> Unit, next: () -> Unit) {
+ Column(Modifier.fillMaxSize()) {
+ Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).padding(horizontal = 24.dp).padding(bottom = 16.dp),
+ verticalArrangement = Arrangement.spacedBy(24.dp)) {
+ // A bot on the computer's screen: that's where it lives.
+ Box(Modifier.fillMaxWidth().padding(top = 8.dp), contentAlignment = Alignment.Center) {
+ Laptop(Modifier.size(176.dp, 116.dp), Palette.tertiary)
+ Box(Modifier.offset(y = (-8).dp)) { CharacterAvatar("blob", "blue", 52.dp, "working") }
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text("Install Codync\non your computer", style = PAGE_TITLE, color = Palette.text)
+ Text("Your bots run there. This phone is how you talk to them.", style = Type.body, color = Palette.secondary)
+ }
+ SegmentedChoice(os, listOf(ComputerOS.Mac to "Mac", ComputerOS.Linux to "Linux"), choose)
+ // Copied here, pasted on the computer (a message to yourself, a shared clipboard).
+ Crossfade(os, animationSpec = Motion.fade(), label = "Install steps") { shown ->
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ if (shown == ComputerOS.Mac) {
+ Hint("Install with Homebrew")
+ CommandBlock("brew install --cask leepokai/codync/codync")
+ Hint("or download the Mac app")
+ CommandBlock("https://github.com/leepokai/Codync/releases/latest/download/codync-macos.dmg")
+ } else {
+ Hint("Run the installer")
+ CommandBlock("curl -fsSL https://raw.githubusercontent.com/leepokai/Codync/main/packaging/install.sh | sh\ncodync-host install")
+ Hint("or install with Homebrew")
+ CommandBlock("brew install leepokai/codync/codync-host\ncodync-host install")
+ }
+ Text(if (shown == ComputerOS.Mac) "Open Codync and it sets up the host on its own."
+ else "codync-host install keeps it running in the background.", style = Type.subheadline, color = Palette.secondary)
+ Hint("Every install option")
+ CommandBlock("https://www.codync.dev/#install")
+ }
+ }
+ DemoButton()
+ }
+ Box(Modifier.padding(horizontal = 24.dp).padding(bottom = 12.dp)) { WideButton("Continue", action = next) }
+ }
+}
+
+/** SF Symbols' `laptopcomputer` at its ultralight weight: a hairline screen over a thin base. */
+@Composable private fun Laptop(modifier: Modifier, color: Color) {
+ Canvas(modifier) {
+ val line = 2.5.dp.toPx()
+ val base = 7.dp.toPx()
+ val inset = size.width * 0.11f
+ val screen = Size(size.width - 2 * inset, size.height - base - 2.dp.toPx())
+ drawRoundRect(color, Offset(inset + line / 2, line / 2), Size(screen.width - line, screen.height - line),
+ CornerRadius(12.dp.toPx()), style = Stroke(line))
+ val top = size.height - base
+ drawRoundRect(color, Offset(0f, top), Size(size.width, base), CornerRadius(base / 2))
+ }
+}
+
+/** A small label above a `CommandBlock`. */
+@Composable private fun Hint(text: String) = Text(text, style = Type.footnote, color = Palette.secondary)
+
+/** A terminal command with a copy button. */
+@Composable private fun CommandBlock(command: String) {
+ val clipboard = LocalClipboard.current
+ val scope = rememberCoroutineScope()
+ var copied by remember { mutableStateOf(false) }
+ Row(Modifier.fillMaxWidth().clip(RoundedRectangle(12.dp)).background(Palette.codeBackground).padding(start = 14.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
+ verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ SelectionContainer(Modifier.weight(1f).padding(vertical = 6.dp)) {
+ Text(command, style = Type.footnote.monospaced, color = Palette.text)
+ }
+ Crossfade(copied, animationSpec = Motion.morph(), label = "Copy") { done ->
+ IconButton(if (done) "Copied" else "Copy", if (done) "checkmark" else "doc.on.doc") {
+ scope.launch {
+ clipboard.setClipEntry(ClipEntry(ClipData.newPlainText("Command", command)))
+ copied = true; delay(1500); copied = false
+ }
+ }
+ }
+ }
+}
+
+// MARK: - Scan
+
+@Composable private fun ScanPage(state: AppState, store: AppStore, os: ComputerOS, paired: () -> Unit) {
+ val uri = LocalUriHandler.current
+ var pasted by remember { mutableStateOf("") }
+ var error by remember { mutableStateOf<String?>(null) }
+ // Bumped after a failed pair so the scanner starts looking again.
+ var attempt by remember { mutableIntStateOf(0) }
+ var started by remember { mutableStateOf(false) }
+ val tailscale = rememberOnResume { tailscaleConnected() }
+ fun pair(text: String) {
+ if (state.pairing || text.isBlank()) return
+ error = null; started = true
+ store.pair(text.trim())
+ }
+ // The store pairs in the background: its finish (and its error) belong to this page.
+ LaunchedEffect(state.pairing, state.error) {
+ if (!started || state.pairing) return@LaunchedEffect
+ started = false
+ val failure = state.error
+ if (failure == null) {
+ state.computers.firstOrNull()?.let { Analytics.capture(AnalyticsEvent.ComputerPaired, mapOf("via" to "qr", "computer" to Analytics.computerTag(it.id))) }
+ pasted = ""; paired()
+ }
+ else { error = failure; attempt++; store.clearError() }
+ }
+ Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 24.dp).padding(bottom = 24.dp),
+ verticalArrangement = Arrangement.spacedBy(24.dp)) {
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text("Scan the pairing code", style = PAGE_TITLE, color = Palette.text)
+ Text(if (os == ComputerOS.Mac) "On your Mac, click Codync in the menu bar, then Pair iPhone. The same code pairs this phone."
+ else "On your computer, run this in a terminal:", style = Type.body, color = Palette.secondary)
+ if (os == ComputerOS.Linux) CommandBlock("codync-host pair")
+ }
+ // The camera, right on the page: no extra sheet between the instruction and the scan.
+ Box(Modifier.fillMaxWidth().aspectRatio(1f).clip(RoundedRectangle(24.dp))) {
+ key(attempt) { QrViewfinder({ pair(it) }, Modifier.fillMaxSize()) { message -> if (message != null) error = message } }
+ val dim by animateFloatAsState(if (state.pairing) 1f else 0f, Motion.fade(), label = "Pairing")
+ if (dim > 0f) Box(Modifier.fillMaxSize().graphicsLayer { alpha = dim }.background(Palette.background.copy(alpha = 0.7f)),
+ contentAlignment = Alignment.Center) { Spinner(28.dp) }
+ }
+ Row(Modifier.fillMaxWidth().clip(RoundedRectangle(12.dp)).background(Palette.surface).padding(start = 14.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
+ verticalAlignment = Alignment.CenterVertically) {
+ PlainTextField(pasted, { pasted = it }, Modifier.weight(1f), "Or paste a ${BuildConfig.URL_SCHEME}://pair link", singleLine = true,
+ style = Type.callout.monospaced, keyboard = KeyboardOptions(capitalization = KeyboardCapitalization.None, autoCorrectEnabled = false,
+ imeAction = ImeAction.Go), actions = KeyboardActions(onGo = { pair(pasted) }))
+ IconButton("Pair", "arrow.right", enabled = pasted.isNotEmpty() && !state.pairing) { pair(pasted) }
+ }
+ AnimatedVisibility(error != null, enter = fadeIn(Motion.fade()), exit = fadeOut(Motion.fade())) {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(error.orEmpty(), style = Type.footnote, color = Palette.danger)
+ // The usual cause: the phone has no road to the computer yet.
+ IconLabel("Check that this phone and the computer are on the same Wi-Fi or both on Tailscale, or that “Reach from anywhere” is on in Codync on the computer.",
+ "wifi.exclamationmark", Palette.secondary)
+ }
+ }
+ // Signed in, account computers show up and ask for access themselves.
+ if (state.account.configured && state.account.userId == null) SignInButtons(state, store)
+ // How it connects is never a choice here: every paired computer gets every route.
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ IconLabel("Connects on Wi-Fi, over Tailscale, or from anywhere through Cloudflare, on its own. End-to-end encrypted.", "lock.fill")
+ if (tailscale) IconLabel("Tailscale is on: Codync connects over it directly.", "checkmark.circle.fill")
+ else IconLabel("Use Tailscale? Direct and faster away from home.", "arrow.up.right",
+ modifier = Modifier.plainButton { uri.openUri("https://tailscale.com/download") })
+ }
+ }
+}
+
+/** `Label` in footnote type: the icon beside the first line. */
+@Composable internal fun IconLabel(text: String, systemImage: String, color: Color = Palette.tertiary, modifier: Modifier = Modifier,
+ style: TextStyle = Type.footnote) {
+ Row(modifier, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Symbol(systemImage, Modifier.padding(top = 1.dp), size = 16.dp, tint = color)
+ Text(text, style = style, color = color)
+ }
+}
+
+private val PAGE_TITLE = Type.system(30f, FontWeight.SemiBold).copy(letterSpacing = (-0.5).sp)
+
+/** Tailscale gives every device an address in 100.64.0.0/10 on its VPN (`tun`) interface. */
+private fun tailscaleConnected(): Boolean = try {
+ NetworkInterface.getNetworkInterfaces()?.toList().orEmpty().any { network ->
+ network.isUp && network.name.startsWith("tun") && network.inetAddresses.toList().any { address ->
+ val bytes = (address as? Inet4Address)?.address
+ bytes != null && bytes[0].toInt() and 0xFF == 100 && (bytes[1].toInt() and 0xFF) in 64..127
+ }
+ }
+} catch (_: Exception) { false }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/PermissionCard.kt b/apps/android/app/src/main/kotlin/com/codync/android/PermissionCard.kt
new file mode 100644
index 00000000..684169d9
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/PermissionCard.kt
@@ -0,0 +1,135 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Entry
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.intOrNull
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+
+/** Approval card in Grok Bot's choice-card style: what the agent wants, where it runs, and the answers as rows. */
+@Composable internal fun PermissionCard(entry: Entry, hostName: String, answering: Boolean, respond: (String?) -> Unit) {
+ val d = entry.data
+ val pending = d.text("status") == "pending"
+ var expanded by remember { mutableStateOf(false) }
+ var chosen by remember { mutableStateOf<String?>(null) }
+ val headline = when (d.text("toolKind")) {
+ "execute" -> "Wants to run a command"
+ "edit", "delete", "move" -> "Wants to change files"
+ "fetch" -> "Wants to access the web"
+ "read", "search" -> "Wants to read files"
+ else -> "Wants to use a tool"
+ }
+ val diffs = (d["diffs"] as? JsonArray)?.mapNotNull { it as? JsonObject }.orEmpty()
+ val hasDetail = !d.text("command").isNullOrEmpty() || !d.text("detail").isNullOrEmpty() || diffs.isNotEmpty()
+ Column(Modifier.padding(end = 40.dp).clip(RoundedRectangle(22.dp)).background(Palette.bubbleAgent).padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(headline, style = Type.headline, color = Palette.text)
+ if (pending) Box(Modifier.size(7.dp).clip(Capsule()).background(Palette.warning))
+ }
+ Text(d.text("title").orEmpty(), style = Type.subheadline.monospaced, color = Palette.secondary, maxLines = if (expanded) Int.MAX_VALUE else 3)
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Symbol("desktopcomputer", size = 14.dp, tint = Palette.tertiary)
+ Text("Runs on $hostName" + (d.text("cwd")?.let { " · " + it.trimEnd('/').substringAfterLast('/') } ?: ""),
+ style = Type.caption, color = Palette.tertiary)
+ }
+ if (hasDetail) Disclosure(expanded, { expanded = !expanded }, label = {
+ Text("Details", style = Type.caption.medium, color = Palette.secondary)
+ }) {
+ Column(Modifier.padding(top = 6.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ d.text("command")?.takeIf(String::isNotEmpty)?.let { CodeBox(it) }
+ d.text("detail")?.takeIf(String::isNotEmpty)?.let { CodeBox(it.take(2000)) }
+ for (diff in diffs) DiffView(diff)
+ }
+ }
+ if (pending) {
+ val rank = mapOf("allow_once" to 0, "allow_always" to 1, "reject_once" to 2, "reject_always" to 3)
+ val options = (d["options"] as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }
+ .sortedBy { rank[it.text("kind")] ?: 9 }
+ Column(Modifier.padding(top = 4.dp).fillMaxWidth().clip(RoundedRectangle(14.dp)).background(Palette.background)) {
+ for ((index, option) in options.withIndex()) {
+ val id = option.text("optionId") ?: continue
+ val kind = option.text("kind").orEmpty()
+ if (index > 0) Box(Modifier.fillMaxWidth().height(0.5.dp).background(Palette.border))
+ val waiting = answering && chosen != null
+ Row(Modifier.fillMaxWidth().heightIn(min = 46.dp)
+ .clickable(enabled = !answering, role = Role.Button) { chosen = id; respond(id) }
+ .graphicsLayer { alpha = if (!waiting || chosen == id) 1f else 0.4f }
+ .padding(horizontal = 14.dp), verticalAlignment = Alignment.CenterVertically) {
+ Text(when (kind) {
+ "allow_once" -> "Allow once"; "allow_always" -> "Always allow"; "reject_once" -> "Deny"; "reject_always" -> "Never"
+ else -> option.text("name").orEmpty()
+ }, Modifier.weight(1f), style = if (kind == "allow_once") Type.body.semibold else Type.body,
+ color = if (kind.startsWith("allow")) Palette.text else Palette.danger)
+ if (answering && chosen == id) Spinner(14.dp)
+ }
+ }
+ }
+ } else Text(outcome(d), style = Type.caption.medium, color = Palette.secondary)
+ }
+}
+
+private fun outcome(d: JsonObject): String = when (d.text("status")) {
+ "answered" -> {
+ val chosen = (d["options"] as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }.firstOrNull { it.text("optionId") == d.text("selected") }
+ when (chosen?.text("kind")) {
+ "allow_once" -> "Allowed once"; "allow_always" -> "Always allowed"; "reject_once" -> "Denied"; "reject_always" -> "Never allowed"
+ else -> chosen?.text("name") ?: "Answered"
+ }
+ }
+ "cancelled" -> "Cancelled"
+ else -> "Expired — the agent moved on"
+}
+
+/** One file's change: its name and line counts over the colored patch. */
+@Composable internal fun DiffView(diff: JsonObject) {
+ val path = diff.text("path").orEmpty()
+ val isNew = diff["isNew"]?.jsonPrimitive?.booleanOrNull == true
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Symbol(if (isNew) "doc.badge.plus" else "doc.text", size = 14.dp, tint = Palette.secondary)
+ Text(path.substringAfterLast('/'), Modifier.weight(1f), style = Type.caption.monospaced, color = Palette.secondary, maxLines = 1)
+ Text("+" + (diff["added"]?.jsonPrimitive?.intOrNull ?: 0), style = Type.caption.monospaced, color = Palette.added)
+ Text("−" + (diff["removed"]?.jsonPrimitive?.intOrNull ?: 0), style = Type.caption.monospaced, color = Palette.removed)
+ }
+ Box(Modifier.fillMaxWidth().heightIn(max = 260.dp).clip(RoundedRectangle(8.dp)).background(Palette.codeBackground)
+ .horizontalScroll(rememberScrollState())) {
+ Column(Modifier.padding(8.dp)) {
+ for (line in diff.text("patch").orEmpty().split("\n").take(80)) Text(line.ifEmpty { " " }, style = Type.caption2.monospaced,
+ color = if (line.startsWith("+")) Palette.added else if (line.startsWith("-")) Palette.removed else Palette.secondary, softWrap = false)
+ }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt b/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt
new file mode 100644
index 00000000..4d2b51ac
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt
@@ -0,0 +1,274 @@
+package com.codync.android
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import android.os.Build
+import androidx.core.app.NotificationCompat
+import androidx.work.*
+import com.codync.android.core.*
+import com.google.firebase.messaging.FirebaseMessaging
+import com.google.firebase.installations.FirebaseInstallations
+import com.google.firebase.messaging.FirebaseMessagingService
+import com.google.firebase.messaging.RemoteMessage
+import java.util.concurrent.TimeUnit
+import kotlinx.coroutines.*
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.flow.first
+import kotlinx.serialization.json.*
+
+/** App-owned preferences are excluded from backup with the rest of the application. */
+object PushPreferences {
+ private fun prefs(context: Context) = context.getSharedPreferences("codync-push", Context.MODE_PRIVATE)
+ fun activeUser(context: Context): String? = prefs(context).getString("user", null)
+ fun enabled(context: Context) = prefs(context).getBoolean("enabled", true)
+ fun tasks(context: Context) = prefs(context).getBoolean("tasks", true)
+ fun asked(context: Context) = prefs(context).getBoolean("asked", false)
+ fun markAsked(context: Context) { prefs(context).edit().putBoolean("asked", true).apply() }
+ fun fid(context: Context) = prefs(context).getString("fid", null)
+ fun fid(context: Context, token: String) { prefs(context).edit().putString("fid", token).apply() }
+ fun active(context: Context, user: String?) = synchronized(this) { prefs(context).edit().putString("user", user).putBoolean("retired", false).commit() }
+ fun retired(context: Context) = prefs(context).getBoolean("retired", false)
+ fun retire(context: Context) = synchronized(this) { prefs(context).edit().putBoolean("retired", true).commit() }
+ fun enabled(context: Context, enabled: Boolean) { prefs(context).edit().putBoolean("enabled", enabled).commit() }
+ fun tasks(context: Context, enabled: Boolean) { prefs(context).edit().putBoolean("tasks", enabled).commit() }
+ fun reset(context: Context) {
+ val token = fid(context)
+ prefs(context).edit().clear().putString("fid", token).commit()
+ }
+}
+
+object PushDelivery {
+ private val gate = Mutex()
+ @Volatile var foreground = false
+
+ suspend fun retire(context: Context) {
+ PushPreferences.retire(context)
+ WorkManager.getInstance(context).cancelUniqueWork(WORK_NAME)
+ gate.withLock { context.getSystemService(NotificationManager::class.java).cancelAll() }
+ }
+ suspend fun activate(context: Context, user: String?) {
+ WorkManager.getInstance(context).cancelUniqueWork(WORK_NAME)
+ gate.withLock { PushPreferences.active(context, user) }
+ }
+
+ fun schedule(context: Context) {
+ if (!BuildConfig.PUSH_CONFIGURED) return
+ val request = OneTimeWorkRequestBuilder<PushRegistrationWorker>()
+ .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
+ .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 15, TimeUnit.SECONDS).build()
+ WorkManager.getInstance(context).enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.REPLACE, request)
+ }
+
+ suspend fun sync(context: Context, local: LocalStore, computer: Computer, active: EncryptedChannel) = gate.withLock {
+ syncLocked(context, local, computer, active)
+ }
+
+ private suspend fun syncLocked(context: Context, local: LocalStore, computer: Computer, active: EncryptedChannel) {
+ if (!BuildConfig.PUSH_CONFIGURED) return
+ if (PushPreferences.retired(context) || local.contextId != (PushPreferences.activeUser(context) ?: "local")) return
+ val permitted = context.getSystemService(NotificationManager::class.java).areNotificationsEnabled()
+ val feed = TaskFeed(local.directory)
+ if (!PushPreferences.tasks(context) || !permitted) {
+ feed.all().forEach { active.call("unregisterActivity", body("botId" to it.botId)) }
+ feed.clear()
+ }
+ if (!PushPreferences.enabled(context) || !permitted) {
+ active.call("unregisterDevice")
+ if (!permitted || !PushPreferences.tasks(context) || feed.all().none { !it.finished }) return
+ }
+ val token = PushPreferences.fid(context) ?: suspendCancellableCoroutine<String> { continuation ->
+ FirebaseMessaging.getInstance().register().addOnSuccessListener {
+ FirebaseInstallations.getInstance().id.addOnSuccessListener { value ->
+ PushPreferences.fid(context, value)
+ continuation.resumeWith(Result.success(value))
+ }.addOnFailureListener { error -> continuation.resumeWith(Result.failure(error)) }
+ }.addOnFailureListener { error -> continuation.resumeWith(Result.failure(error)) }
+ }
+ val identity = withContext(Dispatchers.IO) { local.identity() }
+ if (PushPreferences.enabled(context)) {
+ val ticket = PushRelay.ticket(BuildConfig.PUSH_RELAY_URL, token, local.referenceId, computer.id)
+ currentCoroutineContext().ensureActive()
+ active.call("registerDevice", buildJsonObject {
+ put("ticket", ticket); put("relay", BuildConfig.PUSH_RELAY_URL); put("name", Build.MODEL.take(100))
+ put("pushKey", identity.pushKey); put("ctx", local.referenceId)
+ })
+ }
+ if (PushPreferences.tasks(context)) for (watch in feed.all().filter { !it.finished }) {
+ val activity = PushRelay.ticket(BuildConfig.PUSH_RELAY_URL, token, local.referenceId, computer.id, watch.botId, watch.taskId)
+ currentCoroutineContext().ensureActive()
+ active.call("registerActivity", body("botId" to watch.botId, "ticket" to activity))
+ }
+ }
+
+ suspend fun background(context: Context) = gate.withLock {
+ if (!BuildConfig.PUSH_CONFIGURED) return@withLock
+ if (PushPreferences.retired(context)) return@withLock
+ val local = LocalStore(context, PushPreferences.activeUser(context) ?: "local")
+ val computers = withContext(Dispatchers.IO) { local.computers() }
+ val computer = computers.firstOrNull() ?: return@withLock
+ if (!local.hasIdentity()) return@withLock
+ var active: EncryptedChannel? = null
+ try {
+ withTimeout(45_000) {
+ val identity = withContext(Dispatchers.IO) { local.identity() }
+ val connected = HostConnector.connect(computer, identity)
+ active = connected
+ connected.state.firstReady()
+ syncLocked(context, local, computer, connected)
+ }
+ } finally { active?.close() }
+ }
+
+ const val WORK_NAME = "codync-push-registration"
+}
+
+class PushRegistrationWorker(context: Context, parameters: WorkerParameters) : CoroutineWorker(context, parameters) {
+ override suspend fun doWork(): Result {
+ if (PushPreferences.retired(applicationContext)) return Result.success()
+ try {
+ PushDelivery.background(applicationContext)
+ return Result.success()
+ } catch (error: CancellationException) {
+ if (error !is TimeoutCancellationException) throw error
+ return if (runAttemptCount < 8) Result.retry() else Result.failure()
+ } catch (error: HostError) {
+ return if (error.status in listOf(403, 426)) Result.failure() else Result.retry()
+ } catch (_: Exception) { return if (runAttemptCount < 8) Result.retry() else Result.failure() }
+ }
+}
+
+private suspend fun kotlinx.coroutines.flow.StateFlow<LinkState>.firstReady() {
+ val result = first { it is LinkState.Ready || it is LinkState.ComputerOffline || it is LinkState.Failed }
+ if (result !is LinkState.Ready) throw java.io.IOException("Computer unavailable")
+}
+
+class PushService : FirebaseMessagingService() {
+ override fun onRegistered(installationId: String) {
+ val changed = PushPreferences.fid(this) != installationId
+ PushPreferences.fid(this, installationId)
+ if (changed) PushDelivery.schedule(this)
+ }
+ override fun onMessageReceived(message: RemoteMessage) { receive(this, message.data) }
+
+ companion object {
+ /** Local, bounded work only: notification text is never fetched from the network. */
+ fun receive(context: Context, data: Map<String, String>) {
+ synchronized(PushPreferences) {
+ try {
+ if (PushPreferences.retired(context)) return
+ val user = PushPreferences.activeUser(context)
+ val scope = LocalStore.referenceId(user ?: "local")
+ if (data["ctx"] != scope || data["kind"] !in setOf("alert", "task")) return
+ val local = LocalStore(context, user ?: "local")
+ val computerId = data["computerId"] ?: return
+ if (local.computers().none { it.id == computerId }) return
+ val botId = data["botId"]?.takeIf { it.matches(Regex("[A-Za-z0-9_-]{1,128}")) } ?: return
+ if (!context.getSystemService(NotificationManager::class.java).areNotificationsEnabled()) return
+ NotificationDisplay.channels(context)
+ if (data["kind"] == "task") {
+ if (!PushPreferences.tasks(context)) return
+ val watch = TaskFeed(local.directory).remote(data, botId) ?: return
+ NotificationDisplay.task(context, scope, computerId, watch)
+ return
+ }
+ if (!PushPreferences.enabled(context) || PushDelivery.foreground) return
+ var title = context.getString(R.string.app_name)
+ var text = "A bot has an update."
+ try {
+ if (local.hasIdentity()) {
+ val sealed = requireNotNull(data["sealed"]).takeIf { it.length <= 8192 } ?: return
+ val plain = local.identity().openPush(sealed, computerId)
+ val alert = Json.parseToJsonElement(plain.toString(Charsets.UTF_8)).jsonObject
+ title = alert.getValue("title").jsonPrimitive.content.take(120)
+ text = alert.getValue("body").jsonPrimitive.content.take(400)
+ }
+ } catch (_: Exception) { /* Locked/unavailable key: show only a generic fallback. */ }
+ NotificationDisplay.alert(context, scope, computerId, botId, title, text)
+ } catch (_: Exception) { /* A malformed push cannot crash the Firebase service. */ }
+ }
+ }
+ }
+}
+
+internal object NotificationDisplay {
+ const val ALERTS = "codync-alerts"
+ const val TASKS = "codync-tasks"
+ fun channels(context: Context) {
+ val manager = context.getSystemService(NotificationManager::class.java)
+ manager.createNotificationChannel(NotificationChannel(ALERTS, "Bot updates", NotificationManager.IMPORTANCE_HIGH))
+ manager.createNotificationChannel(NotificationChannel(TASKS, "Delegated tasks", NotificationManager.IMPORTANCE_LOW))
+ }
+ private fun builder(context: Context, scope: String, computer: String, bot: String, channel: String): NotificationCompat.Builder {
+ val url = Uri.Builder().scheme(BuildConfig.URL_SCHEME).authority("bot").appendPath(bot).appendQueryParameter("scope", scope).appendQueryParameter("computer", computer).build()
+ val intent = Intent(context, MainActivity::class.java).setAction(Intent.ACTION_VIEW).setData(url)
+ val pending = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
+ val generic = NotificationCompat.Builder(context, channel).setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle(context.getString(R.string.app_name)).setContentText("A bot has an update.").build()
+ return NotificationCompat.Builder(context, channel).setSmallIcon(R.drawable.ic_notification).setContentIntent(pending)
+ .setVisibility(NotificationCompat.VISIBILITY_PRIVATE).setPublicVersion(generic).setGroup("$scope/$computer")
+ }
+ fun alert(context: Context, scope: String, computer: String, bot: String, title: String, text: String) {
+ channels(context)
+ val notification = builder(context, scope, computer, bot, ALERTS).setContentTitle(title).setContentText(text)
+ .setStyle(NotificationCompat.BigTextStyle().bigText(text)).setAutoCancel(true).setCategory(NotificationCompat.CATEGORY_MESSAGE).build()
+ try { context.getSystemService(NotificationManager::class.java).notify("$scope/$computer/$bot", 1, notification) } catch (_: SecurityException) { }
+ }
+ /**
+ * A delegated task: on Android 16 a Live update (promoted ongoing notification) with its
+ * progress, running time and a status bar chip; before that, an ongoing notification.
+ */
+ fun task(context: Context, scope: String, computer: String, watch: TaskWatch) {
+ channels(context)
+ val text = when (watch.status) { "working" -> watch.activity.ifEmpty { "Working…" }; "needsInput" -> "Needs your approval"
+ "error" -> "Could not finish"; else -> "Done" }
+ val tag = "$scope/$computer/${watch.botId}"
+ val manager = context.getSystemService(NotificationManager::class.java)
+ if (Build.VERSION.SDK_INT >= 36) {
+ try { manager.notify(tag, 2, liveUpdate(context, scope, computer, watch, text)); return }
+ catch (_: SecurityException) { return }
+ // A system that rejects the Live update still gets the plain ongoing notification below.
+ catch (error: IllegalArgumentException) { android.util.Log.w("Codync", "Live update rejected", error) }
+ }
+ val notification = builder(context, scope, computer, watch.botId, TASKS).setContentTitle(watch.name).setContentText(text)
+ .setOngoing(!watch.finished).setOnlyAlertOnce(true).setAutoCancel(watch.finished)
+ .setCategory(NotificationCompat.CATEGORY_PROGRESS).setTimeoutAfter(if (watch.finished) 60_000 else maxOf(1, watch.deadline - System.currentTimeMillis())).build()
+ try { manager.notify(tag, 2, notification) } catch (_: SecurityException) { }
+ }
+
+ /** The Live update: four segments filling with the task's phase, in its color; the chip counts up. */
+ @androidx.annotation.RequiresApi(36)
+ private fun liveUpdate(context: Context, scope: String, computer: String, watch: TaskWatch, text: String): Notification {
+ val needs = watch.status == "needsInput"
+ // The phase's color, as the iOS Live Activity tints it: ink while working, amber, red, green.
+ val tint = when (watch.status) { "needsInput" -> 0xFFE0A030.toInt(); "error" -> 0xFFD0453A.toInt(); "idle" -> 0xFF3E9B45.toInt()
+ else -> 0xFF5F6368.toInt() }
+ val filled = when (watch.status) { "working" -> 2; "needsInput" -> 3; else -> 4 }
+ // Styled by progress: segments past the point fade on their own, in every theme.
+ val style = Notification.ProgressStyle().setStyledByProgress(true)
+ .setProgressSegments(List(4) { Notification.ProgressStyle.Segment(25).setColor(tint) })
+ .setProgress(filled * 25)
+ val face = com.codync.android.design.characterAvatarBitmap(watch.avatarShape, watch.avatarColor, 128, 0xFF141414.toInt())
+ val open = builder(context, scope, computer, watch.botId, TASKS).build().contentIntent
+ val notification = Notification.Builder(context, TASKS).setSmallIcon(R.drawable.ic_notification).setContentTitle(watch.name).setContentText(text)
+ .setLargeIcon(android.graphics.drawable.Icon.createWithBitmap(face)).setContentIntent(open).setStyle(style)
+ .setOngoing(!watch.finished).setOnlyAlertOnce(true).setAutoCancel(watch.finished).setCategory(Notification.CATEGORY_PROGRESS)
+ .setWhen(watch.startedAt).setShowWhen(true).setUsesChronometer(!watch.finished)
+ .setTimeoutAfter(if (watch.finished) 60_000 else maxOf(1, watch.deadline - System.currentTimeMillis()))
+ .apply { if (needs) addAction(Notification.Action.Builder(null, "Review", open).build()) }
+ // Promotion (the Lock Screen Live update and the status bar chip) arrived in Android 16 QPR1.
+ if (LiveUpdates.supported) notification.setRequestPromotedOngoing(!watch.finished)
+ .setShortCriticalText(when (watch.status) { "needsInput" -> "Needs you"; "error" -> "Failed"; "idle" -> "Done"; else -> null })
+ return notification.build()
+ }
+
+ fun cancel(context: Context, id: Int) {
+ val manager = context.getSystemService(NotificationManager::class.java)
+ manager.activeNotifications.filter { it.id == id }.forEach { manager.cancel(it.tag, it.id) }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/QrViewfinder.kt b/apps/android/app/src/main/kotlin/com/codync/android/QrViewfinder.kt
new file mode 100644
index 00000000..ce6cf6f7
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/QrViewfinder.kt
@@ -0,0 +1,144 @@
+package com.codync.android
+
+import android.Manifest
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.SystemClock
+import android.provider.Settings
+import android.util.Size
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.camera.core.*
+import androidx.camera.core.resolutionselector.ResolutionSelector
+import androidx.camera.core.resolutionselector.ResolutionStrategy
+import androidx.camera.lifecycle.ProcessCameraProvider
+import androidx.camera.view.PreviewView
+import androidx.compose.foundation.layout.*
+import androidx.compose.material3.Text
+import androidx.compose.foundation.background
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.style.TextAlign
+import com.codync.android.design.*
+import androidx.compose.runtime.*
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.viewinterop.AndroidView
+import androidx.core.content.ContextCompat
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.Observer
+import androidx.lifecycle.compose.LocalLifecycleOwner
+import com.codync.android.core.PairingQr
+import com.codync.android.core.PairingScan
+import java.util.concurrent.Executors
+import java.util.concurrent.atomic.AtomicBoolean
+
+/**
+ * The camera, right on the pairing page (iOS `QRScanner` in its viewfinder): asks for the camera
+ * in place, then reads Codync pairing codes. Nothing is saved.
+ */
+@Composable fun QrViewfinder(found: (String) -> Unit, modifier: Modifier = Modifier, error: (String?) -> Unit = {}) {
+ val context = LocalContext.current
+ val hardware = remember { context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY) }
+ var asked by remember { mutableStateOf(false) }
+ var granted by remember { mutableStateOf(false) }
+ val permitted = rememberOnResume { ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED } || granted
+ val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted = it; asked = true }
+ Box(modifier.background(Palette.surface), contentAlignment = Alignment.Center) {
+ if (hardware && permitted) CameraPairingPreview(Modifier.fillMaxSize(), found, error)
+ else Column(Modifier.padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Symbol("qrcode.viewfinder", size = 52.dp, tint = Palette.tertiary)
+ Text(if (!hardware) "Camera not available. Paste the link below." else "Allow the camera to scan the code on your computer.",
+ style = Type.footnote, color = Palette.tertiary, textAlign = TextAlign.Center)
+ if (hardware) {
+ if (!asked) SecondaryButton("Allow camera") { permission.launch(Manifest.permission.CAMERA) }
+ else SecondaryButton("Camera settings") {
+ context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}")))
+ }
+ }
+ }
+ }
+}
+
+/** CameraX owns foreground lifecycle. Every analyzed frame closes; no image or pairing link is saved. */
+@Composable private fun CameraPairingPreview(modifier: Modifier, found: (String) -> Unit, error: (String?) -> Unit) {
+ val context = LocalContext.current
+ val owner = LocalLifecycleOwner.current
+ val onFound by rememberUpdatedState(found)
+ val onError by rememberUpdatedState(error)
+ val view = remember { PreviewView(context).apply { implementationMode = PreviewView.ImplementationMode.COMPATIBLE; scaleType = PreviewView.ScaleType.FILL_CENTER } }
+ var camera by remember { mutableStateOf<Camera?>(null) }
+ var torch by remember { mutableStateOf(false) }
+ DisposableEffect(owner, view) {
+ val closed = AtomicBoolean(false)
+ val accepted = AtomicBoolean(false)
+ val executor = Executors.newSingleThreadExecutor()
+ val main = ContextCompat.getMainExecutor(context)
+ val reader = PairingQr(BuildConfig.URL_SCHEME)
+ val preview = Preview.Builder().build().apply { setSurfaceProvider(view.surfaceProvider) }
+ val analysis = ImageAnalysis.Builder().setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
+ .setResolutionSelector(ResolutionSelector.Builder().setResolutionStrategy(
+ ResolutionStrategy(Size(1280, 720), ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER)).build()).build()
+ var lastFrame = 0L
+ analysis.setAnalyzer(executor) { image ->
+ try {
+ val now = SystemClock.elapsedRealtime()
+ if (!closed.get() && !accepted.get() && now - lastFrame >= 150) {
+ lastFrame = now
+ val plane = image.planes.first()
+ val pixels = PairingQr.luminance(plane.buffer, image.width, image.height, plane.rowStride, plane.pixelStride)
+ val result = try { reader.decode(pixels, image.width, image.height) } finally { pixels.fill(0) }
+ if (result != null) main.execute {
+ if (!closed.get() && owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) when (result) {
+ is PairingScan.Found -> if (accepted.compareAndSet(false, true)) onFound(result.link)
+ is PairingScan.Invalid -> onError(result.message)
+ }
+ }
+ }
+ } catch (_: Exception) { /* A damaged/partial camera frame can be skipped. */ }
+ finally { image.close() }
+ }
+ var provider: ProcessCameraProvider? = null
+ val cameraState = Observer<CameraState> { state ->
+ if (!closed.get() && state.error != null) onError("Couldn't open the camera. Retry or use a pairing link.")
+ }
+ val future = ProcessCameraProvider.getInstance(context)
+ future.addListener({
+ if (!closed.get()) try {
+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
+ onError("Allow camera access or use a pairing link.")
+ return@addListener
+ }
+ val resolved = future.get()
+ provider = resolved
+ val selector = if (resolved.hasCamera(CameraSelector.DEFAULT_BACK_CAMERA)) CameraSelector.DEFAULT_BACK_CAMERA else CameraSelector.DEFAULT_FRONT_CAMERA
+ val bound = resolved.bindToLifecycle(owner, selector, preview, analysis)
+ camera = bound
+ bound.cameraInfo.cameraState.observe(owner, cameraState)
+ } catch (_: Exception) { onError("Couldn't open the camera. Retry or use a pairing link.") }
+ }, main)
+ onDispose {
+ closed.set(true); analysis.clearAnalyzer()
+ camera?.cameraInfo?.cameraState?.removeObserver(cameraState)
+ provider?.unbind(preview, analysis)
+ camera = null
+ executor.shutdownNow()
+ }
+ }
+ Box(modifier) {
+ AndroidView(factory = { view }, modifier = Modifier.fillMaxSize())
+ if (camera?.cameraInfo?.hasFlashUnit() == true) Box(Modifier.align(Alignment.BottomEnd).padding(12.dp)) {
+ IconButton(if (torch) "Turn flashlight off" else "Turn flashlight on", "bolt", tint = Color.White) {
+ val active = camera ?: return@IconButton
+ val next = !torch
+ val result = active.cameraControl.enableTorch(next)
+ result.addListener({
+ if (camera === active) try { result.get(); torch = next }
+ catch (_: Exception) { onError("The flashlight is unavailable. Try again.") }
+ }, ContextCompat.getMainExecutor(context))
+ }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/RelativeTime.kt b/apps/android/app/src/main/kotlin/com/codync/android/RelativeTime.kt
new file mode 100644
index 00000000..60290fbf
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/RelativeTime.kt
@@ -0,0 +1,51 @@
+package com.codync.android
+
+import java.time.Instant
+import java.time.LocalDate
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+import java.time.format.FormatStyle
+import java.util.Locale
+
+/** The iOS app's date stamps (CodyncKit `RelativeTime`), in the phone's locale. */
+internal object RelativeTime {
+ private fun date(milliseconds: Long) = Instant.ofEpochMilli(milliseconds).atZone(ZoneId.systemDefault())
+ private val time get() = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(Locale.getDefault())
+ private val monthDay get() = DateTimeFormatter.ofPattern(android.text.format.DateFormat.getBestDateTimePattern(Locale.getDefault(), "MMMd"))
+
+ /** Grok-style compact age: now · 5m · 3h · 2d · Sep 3. */
+ fun short(milliseconds: Long, now: Long = System.currentTimeMillis()): String {
+ val s = maxOf(0L, (now - milliseconds) / 1000)
+ return when {
+ s < 60 -> "now"
+ s < 3600 -> "${s / 60}m"
+ s < 86_400 -> "${s / 3600}h"
+ s < 86_400 * 7 -> "${s / 86_400}d"
+ else -> date(milliseconds).format(monthDay)
+ }
+ }
+
+ /** Roster stamp: 3:45 AM · Yesterday · Wednesday · Sep 16. */
+ fun day(milliseconds: Long, now: Long = System.currentTimeMillis()): String {
+ val day = date(milliseconds)
+ val today = LocalDate.now(ZoneId.systemDefault())
+ return when {
+ day.toLocalDate() == today -> day.format(time)
+ day.toLocalDate() == today.minusDays(1) -> "Yesterday"
+ now - milliseconds < 6 * 86_400_000L -> day.format(DateTimeFormatter.ofPattern("EEEE", Locale.getDefault()))
+ else -> day.format(monthDay)
+ }
+ }
+
+ /** Chat separator: Today 3:27 AM · Yesterday 5:20 PM · Sep 16 9:02 AM. */
+ fun separator(milliseconds: Long): String {
+ val day = date(milliseconds)
+ val today = LocalDate.now(ZoneId.systemDefault())
+ val name = when (day.toLocalDate()) {
+ today -> "Today"
+ today.minusDays(1) -> "Yesterday"
+ else -> day.format(monthDay)
+ }
+ return name + " " + day.format(time)
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/RoutinesScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/RoutinesScreen.kt
new file mode 100644
index 00000000..23f9d8a1
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/RoutinesScreen.kt
@@ -0,0 +1,308 @@
+package com.codync.android
+
+import android.content.ClipData
+import android.content.ClipDescription
+import android.os.Build
+import android.os.PersistableBundle
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.expandVertically
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.shrinkVertically
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.rotate
+import androidx.compose.ui.platform.ClipEntry
+import androidx.compose.ui.platform.LocalClipboard
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Bot
+import com.codync.android.core.LinkState
+import com.codync.android.core.Routine
+import com.codync.android.core.RoutineDraft
+import com.codync.android.core.RoutineScheduleDraft
+import com.codync.android.core.RoutineSchedulePreview
+import com.codync.android.core.RoutineWebhook
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+import java.text.DateFormat
+import java.util.Date
+import java.util.TimeZone
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+/** A bot's routines, in a sheet over its chat (iOS `RoutinesView`); a row opens its editor. */
+@Composable fun RoutinesScreen(bot: Bot, state: AppState, store: AppStore) {
+ val dismiss = LocalDismissModal.current
+ val online = state.actualConnection is LinkState.Ready
+ val listing = state.routines[bot.id]
+ val busy = "routines:${bot.id}" in state.busy
+ // The open editor: on a routine (its id), or "" setting up a new one.
+ var editing by remember(bot.id) { mutableStateOf<String?>(null) }
+ LaunchedEffect(bot.id, online) { if (online) while (true) { store.loadRoutines(bot.id); delay(3_000) } }
+ Column(Modifier.fillMaxSize().background(Palette.background).verticalScroll(rememberScrollState()).padding(20.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text("Routines", Modifier.weight(1f).padding(start = 2.dp), style = Type.system(13f).semibold, color = Palette.text)
+ IconButton("Ask the bot for a routine", "text.bubble", enabled = online) { store.editDraft(bot.id, null, "I want a routine that "); dismiss() }
+ IconButton("Set up a routine", "plus", enabled = online) { editing = "" }
+ IconButton("Close routines", "xmark", action = dismiss)
+ }
+ val routines = listing?.routines.orEmpty()
+ if (routines.isEmpty()) Text(if (listing != null) "No routines yet. Ask the bot for one, or set it up yourself with +." else "Loading routines…",
+ Modifier.fillMaxWidth().clip(RoundedRectangle(16.dp)).background(Palette.surface).padding(14.dp),
+ style = Type.system(12f).copy(lineHeight = Type.system(12f).lineHeight * 1.25f), color = Palette.secondary)
+ else Column(Modifier.fillMaxWidth().clip(RoundedRectangle(16.dp)).background(Palette.surface).padding(horizontal = 14.dp)) {
+ for ((index, routine) in routines.withIndex()) {
+ if (index > 0) Hairline()
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Column(Modifier.weight(1f).plainButton { editing = routine.id }.padding(vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) {
+ Text(routine.name, style = Type.system(13f), color = Palette.text)
+ Text(listing?.summary(routine).orEmpty(), style = Type.caption, color = if (routine.lastError == null) Palette.secondary else Palette.danger)
+ }
+ CodyncSwitch(routine.enabled, { store.routineAction(bot.id, routine.id, "setRoutineEnabled", it) },
+ Modifier.width(34.dp).semantics { contentDescription = routine.name }, enabled = online && !busy) {}
+ }
+ }
+ }
+ }
+ // Item-based, so the editor always gets the routine it was opened on.
+ CodyncSheet(editing, { editing = null }) { id ->
+ RoutineEditor(bot.id, listing?.routines?.firstOrNull { it.id == id }, state, store) { saved ->
+ // A new webhook routine stays open: its URL and key exist only now.
+ editing = if (id.isEmpty() && saved?.hasWebhook == true) saved.id else null
+ }
+ }
+}
+
+/** Set up or edit one routine (iOS `RoutineEditorView`); `saved` gets the routine, or null once it's deleted. */
+@Composable private fun RoutineEditor(botId: String, routine: Routine?, state: AppState, store: AppStore, saved: (Routine?) -> Unit) {
+ var draft by remember(routine?.id) {
+ mutableStateOf(RoutineDraft(routine?.id, routine?.name.orEmpty(), routine?.instruction.orEmpty(), timeoutSeconds = (routine?.timeoutSeconds ?: 3600).toString()))
+ }
+ var loaded by remember(routine?.id) { mutableStateOf(false) }
+ var loadAttempt by remember { mutableIntStateOf(0) }
+ var checkAttempt by remember { mutableIntStateOf(0) }
+ var preview by remember { mutableStateOf<RoutineSchedulePreview?>(null) }
+ var checked by remember { mutableStateOf<RoutineScheduleDraft?>(null) }
+ var previewError by remember { mutableStateOf<String?>(null) }
+ var error by remember { mutableStateOf<String?>(null) }
+ var advanced by remember { mutableStateOf(false) }
+ var confirmDelete by remember { mutableStateOf(false) }
+ var started by remember { mutableStateOf(false) }
+ val busy = "routines:$botId" in state.busy
+ val online = state.actualConnection is LinkState.Ready
+ LaunchedEffect(routine?.id, loadAttempt) {
+ try {
+ val result = store.routineSchedule(routine?.triggers.orEmpty(), TimeZone.getDefault().id)
+ draft = draft.copy(schedule = result.draft.forMobileEditor())
+ preview = result; checked = draft.schedule; loaded = true; error = null
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Connect to this computer to load the schedule." }
+ }
+ // The host checks the schedule and describes when it runs.
+ LaunchedEffect(draft.schedule, loaded, checkAttempt) {
+ if (!loaded || checked == draft.schedule) return@LaunchedEffect
+ val requested = draft.schedule
+ preview = null; previewError = null; checked = null
+ delay(300)
+ try {
+ val result = store.routineSchedule(requested)
+ if (draft.schedule == requested) { preview = result; checked = requested }
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { if (draft.schedule == requested) previewError = failure.message ?: "Couldn't check this schedule." }
+ }
+ val canSave = draft.name.isNotBlank() && draft.instruction.isNotBlank() && online && !busy && loaded && checked == draft.schedule && previewError == null
+ val options = buildList {
+ if (routine != null && routine.keepsOriginal && routine.triggers.isNotEmpty()) add("keep" to routine.triggerDescriptions.joinToString(" · "))
+ add("cron" to "Schedule"); add("webhook" to "Webhook")
+ }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader(if (routine == null) "Set up a routine" else "Edit routine")
+ Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(24.dp)) {
+ Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
+ Field("Name") { FieldBox(draft.name, { draft = draft.copy(name = it) }, "e.g. Morning summary", fill = Palette.bubbleUser) }
+ Field("Instruction") {
+ FieldBox(draft.instruction, { draft = draft.copy(instruction = it) }, "Describe what this bot should do each time it runs.", 3, 8, fill = Palette.bubbleUser)
+ }
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
+ Field("When to run") {
+ ChoicePicker(draft.schedule.kind, options, { draft = draft.copy(schedule = draft.schedule.copy(kind = it)) }, label = "When to run")
+ }
+ if (!loaded) IconLabel("Loading schedule…", "clock", Palette.secondary, style = Type.body)
+ else when (draft.schedule.kind) {
+ "cron" -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Field("Cron") {
+ FieldBox(draft.schedule.expression, { draft = draft.copy(schedule = draft.schedule.copy(expression = it)) }, "0 9 * * 1-5",
+ style = Type.body.monospaced, fill = Palette.bubbleUser, capitalize = false)
+ }
+ Field("Time zone") {
+ FieldBox(draft.schedule.zone, { draft = draft.copy(schedule = draft.schedule.copy(zone = it)) }, "Asia/Taipei",
+ fill = Palette.bubbleUser, capitalize = false)
+ }
+ SchedulePreview(if (checked == draft.schedule) preview else null, previewError)
+ }
+ "webhook" -> if (routine?.hasWebhook == true) RoutineWebhookPanel(botId, routine.id, online, store)
+ else Note("Runs each time something is posted to its URL. Save to get the URL and key.")
+ else -> Note("Set up by the bot. Pick Schedule or Webhook to replace it.")
+ }
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ val turn by animateFloatAsState(if (advanced) 180f else 0f, Motion.layout(), label = "Chevron")
+ Row(Modifier.fillMaxWidth().plainButton { advanced = !advanced }.padding(start = 4.dp), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text("Run settings", style = Type.subheadline, color = Palette.secondary)
+ Symbol("chevron.down", Modifier.rotate(turn), size = 11.dp, tint = Palette.secondary)
+ Spacer(Modifier.weight(1f))
+ if (!advanced) Text("Timeout ${draft.timeoutSeconds}s", style = Type.subheadline, color = Palette.tertiary)
+ }
+ AnimatedVisibility(advanced, enter = fadeIn(Motion.fade()) + expandVertically(Motion.layoutSize),
+ exit = fadeOut(Motion.fade()) + shrinkVertically(Motion.layoutSize)) {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Field("Timeout (seconds)") { FieldBox(draft.timeoutSeconds, { draft = draft.copy(timeoutSeconds = it) }, "3600", fill = Palette.bubbleUser) }
+ Note("A run is stopped after this long. 1 second to 24 hours.")
+ }
+ }
+ }
+ }
+ // The footer: what keeps it from saving, the routine's own actions, then Save.
+ Column(Modifier.fillMaxWidth().padding(start = 20.dp, end = 20.dp, top = 20.dp, bottom = 36.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ if (previewError != null) LinkButton("Check schedule again", enabled = online) { checkAttempt++ }
+ if (!loaded && error != null) LinkButton("Retry loading schedule") { loadAttempt++ }
+ if (draft.schedule.kind != "cron") previewError?.let { Text(it, style = Type.caption, color = Palette.danger) }
+ error?.let { IconLabel(it, "exclamationmark.circle", Palette.danger, style = Type.callout) }
+ if (!online) IconLabel("Connect to this computer to save your routine.", "wifi.slash", Palette.danger, style = Type.caption)
+ if (loaded && online && (draft.name.isBlank() || draft.instruction.isBlank()))
+ Text("Enter a name and instruction above to save.", style = Type.caption, color = Palette.secondary)
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp)) {
+ if (routine != null) {
+ IconButton("Delete routine", "trash") { confirmDelete = true }
+ IconButton(if (started) "Started" else "Test run", if (started) "checkmark" else "play.circle", enabled = !started && online) {
+ store.routineAction(botId, routine.id, "runRoutine") { started = true }
+ }
+ }
+ PrimaryButton({ store.saveRoutine(botId, draft) { saved(it) } }, Modifier.weight(1f), canSave) {
+ Row(Modifier.heightIn(min = 26.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (busy) Spinner(color = Palette.onAccent)
+ Text(if (busy) "Saving…" else if (routine == null) "Create routine" else "Save changes")
+ }
+ }
+ }
+ }
+ }
+ CodyncDialog("Delete routine?", confirmDelete, { confirmDelete = false }, "This deletes the routine and stops its future runs. This can't be undone.") {
+ listOf(DialogAction("Delete routine", destructive = true) { routine?.let { store.routineAction(botId, it.id, "deleteRoutine") { saved(null) } } })
+ }
+}
+
+/** One quiet line under the cron fields: what the host read, or why it can't. */
+@Composable private fun SchedulePreview(preview: RoutineSchedulePreview?, error: String?) {
+ Column(Modifier.padding(start = 4.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ when {
+ error != null -> Text(error, style = Type.caption, color = Palette.danger)
+ preview != null -> {
+ Text(preview.summary, style = Type.caption.medium, color = Palette.text)
+ preview.nextRunAt?.let { Text("Next ${DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(Date(it))}", style = Type.caption, color = Palette.secondary) }
+ preview.warning?.let { Text(it, style = Type.caption, color = Palette.secondary) }
+ }
+ else -> Text("minute hour day month weekday", style = Type.caption.monospaced, color = Palette.tertiary)
+ }
+ }
+}
+
+@Composable private fun Note(text: String) = Text(text, Modifier.padding(start = 4.dp), style = Type.caption, color = Palette.secondary)
+
+/** A saved webhook routine's address and key: copy either, reveal or replace the key (iOS `RoutineWebhookPanel`). */
+@Composable private fun RoutineWebhookPanel(botId: String, id: String, online: Boolean, store: AppStore) {
+ var webhook by remember(id) { mutableStateOf<RoutineWebhook?>(null) }
+ var showKey by remember(id) { mutableStateOf(false) }
+ var confirm by remember(id) { mutableStateOf(false) }
+ var rotating by remember(id) { mutableStateOf(false) }
+ var error by remember(id) { mutableStateOf<String?>(null) }
+ var copied by remember(id) { mutableStateOf<String?>(null) }
+ val clipboard = LocalClipboard.current
+ val scope = rememberCoroutineScope()
+ suspend fun load(rotate: Boolean) {
+ rotating = rotate
+ try {
+ webhook = store.routineWebhook(botId, id, rotate); error = null
+ if (rotate) { copied = null; showKey = true }
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { error = failure.message ?: "Connect to this computer to see the webhook." }
+ finally { rotating = false }
+ }
+ LaunchedEffect(id) { load(false) }
+ fun copy(field: String, value: RoutineWebhook) = scope.launch {
+ val clip = ClipData.newPlainText("Routine $field", if (field == "key") value.key else value.url ?: value.localUrl)
+ // Keys stay out of the clipboard preview.
+ if (field == "key" && Build.VERSION.SDK_INT >= 33) clip.description.extras = PersistableBundle().apply { putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true) }
+ clipboard.setClipEntry(ClipEntry(clip)); copied = field
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
+ val value = webhook
+ when {
+ value != null -> {
+ Field(if (value.url == null) "Local URL" else "URL") {
+ WebhookValue(value.url ?: value.localUrl) {
+ IconButton(if (copied == "url") "Copied" else "Copy", if (copied == "url") "checkmark" else "doc.on.doc") { copy("url", value) }
+ }
+ }
+ Field("Key") {
+ WebhookValue(if (showKey) value.key else "•".repeat(16)) {
+ IconButton(if (showKey) "Hide key" else "Show key", if (showKey) "eye.slash" else "eye") { showKey = !showKey }
+ IconButton("Replace key", "arrow.triangle.2.circlepath", enabled = !rotating && online) { confirm = true }
+ IconButton(if (copied == "key") "Copied" else "Copy", if (copied == "key") "checkmark" else "doc.on.doc") { copy("key", value) }
+ }
+ }
+ Note(if (value.url == null) "The Codync cloud is off, so only this computer can send to it."
+ else "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.")
+ }
+ error != null -> Text(error.orEmpty(), Modifier.padding(start = 4.dp), style = Type.caption, color = Palette.danger)
+ else -> Note("Loading webhook…")
+ }
+ }
+ CodyncDialog("Replace the key?", confirm, { confirm = false }, "Senders using the current key stop working until they get the new one.") {
+ listOf(DialogAction("Replace key", destructive = true) { scope.launch { load(true) } })
+ }
+}
+
+/** A selectable monospaced value with its buttons. */
+@Composable private fun WebhookValue(text: String, buttons: @Composable () -> Unit) {
+ Row(Modifier.fillMaxWidth().clip(RoundedRectangle(12.dp)).background(Palette.bubbleUser).padding(start = 12.dp, end = 6.dp, top = 8.dp, bottom = 8.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Box(Modifier.weight(1f)) {
+ SelectionContainer { Text(text, style = Type.callout.monospaced, color = Palette.text, maxLines = 2, overflow = TextOverflow.MiddleEllipsis) }
+ }
+ buttons()
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt
new file mode 100644
index 00000000..f7d472ed
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt
@@ -0,0 +1,235 @@
+package com.codync.android
+
+import android.Manifest
+import android.os.Build
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalUriHandler
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Bot
+import com.codync.android.core.CloudComputer
+import com.codync.android.core.ConnectionRoute
+import com.codync.android.core.HostRoute
+import com.codync.android.core.LinkState
+import com.codync.android.design.*
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+
+/**
+ * Every computer this phone can use or ask for, plus settings for the selected account
+ * (iOS `SettingsView`). `pop` is set when it's pushed inside Accounts.
+ */
+@Composable internal fun SettingsView(state: AppState, store: AppStore, pop: (() -> Unit)?, pair: () -> Unit, ask: (CloudComputer) -> Unit,
+ extensions: () -> Unit) {
+ val uri = LocalUriHandler.current
+ val signedIn = state.account.userId != null
+ val paired = state.computers.firstOrNull()
+ var confirmForget by remember { mutableStateOf(false) }
+ var confirmStartOver by remember { mutableStateOf(false) }
+ var voice by remember { mutableStateOf(false) }
+ var aboutAnalytics by remember { mutableStateOf(false) }
+ LaunchedEffect(state.contextId) { store.refreshCloud() }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ PageHeader("Computers & settings", pop)
+ CardForm(Modifier.weight(1f)) {
+ CardSection("Computers", if (signedIn) "Computers in your account need your OK on the computer before this phone can use them."
+ else "Each bot runs on its own computer. Sign in to see the computers in your account.") {
+ if (paired != null) row {
+ ComputerRow(state, store, state.cloudComputers.any { it.computerId == paired.id }, extensions) { confirmForget = true }
+ }
+ for (computer in state.cloudComputers.filter { it.computerId != paired?.id }) row {
+ AccountComputerRow(computer, state.access?.takeIf { it.computerId == computer.computerId }?.code, canAsk = paired == null) { ask(computer) }
+ }
+ row {
+ Row(Modifier.fillMaxWidth().plainButton(action = pair), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Symbol("qrcode.viewfinder", size = 20.dp, tint = Palette.text)
+ Text("Pair a computer", style = Type.body, color = Palette.text)
+ }
+ }
+ }
+ if (state.actualConnection is LinkState.Ready) CardSection("Voice chat", "Android speech on this phone; only the text reaches the computer.") {
+ row {
+ Row(Modifier.fillMaxWidth().plainButton { voice = true }, verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Symbol("waveform", size = 20.dp, tint = Palette.text)
+ Text("Voice chat", Modifier.weight(1f), style = Type.body, color = Palette.text)
+ Symbol("chevron.right", size = 13.dp, tint = Palette.tertiary)
+ }
+ }
+ }
+ NotificationsSection(state, store)
+ CardSection(footer = "Which features you use, never your messages, code or files. Helps us spot bugs sooner and make Codync better for you.") {
+ row {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text("Share usage analytics", style = Type.body, color = Palette.text, maxLines = 1)
+ IconButton("About usage analytics", "info.circle") { aboutAnalytics = true }
+ Box(Modifier.weight(1f))
+ CodyncSwitch(Analytics.enabled, Analytics::setEnabled, Modifier.width(34.dp)
+ .semantics { contentDescription = "Share usage analytics" }) {}
+ }
+ }
+ }
+ val hidden = state.bots.filter { it.hidden && !it.deleted }
+ if (hidden.isNotEmpty()) CardSection("Hidden bots") {
+ for (bot in hidden) row { HiddenBotRow(state, store, bot) }
+ }
+ CardSection {
+ row { ValueRow("App version", BuildConfig.VERSION_NAME) }
+ row { LinkButton("Source code") { uri.openUri("https://github.com/leepokai/Codync") } }
+ }
+ CardSection {
+ row {
+ Row(Modifier.fillMaxWidth().plainButton(enabled = "session" !in state.busy) { confirmStartOver = true },
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Symbol("arrow.counterclockwise", size = 20.dp, tint = Palette.danger)
+ Text("Start over", style = Type.body, color = Palette.danger)
+ }
+ }
+ }
+ }
+ }
+ CodyncSheet(voice, { voice = false }) { VoiceChatSettings(store) }
+ CodyncSheet(aboutAnalytics, { aboutAnalytics = false }) { AnalyticsSheet() }
+ CodyncDialog("Start over?", confirmStartOver, { confirmStartOver = false },
+ "Signs out of every account and forgets every computer on this phone, then shows the welcome again. Your computers keep their bots and chats; pair again to use them.") {
+ listOf(DialogAction("Start over", destructive = true, action = store::startOver))
+ }
+ CodyncDialog("Remove ${paired?.name ?: "computer"}?", confirmForget, { confirmForget = false },
+ "Its bots and conversations stay on that computer. You can pair again any time.") {
+ listOf(DialogAction("Remove", destructive = true, action = store::forgetComputer))
+ }
+}
+
+/** Push on or off for this phone, and whether Android lets Codync show notifications at all. */
+@Composable private fun NotificationsSection(state: AppState, store: AppStore) {
+ val context = LocalContext.current
+ var asked by remember { mutableStateOf(false) }
+ val request = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { asked = true }
+ val allowed = rememberOnResume { notificationsAllowed(context) } || asked && notificationsAllowed(context)
+ CardSection("Notifications", "Get a result summary, a request for input, or a failure notice. Notification previews follow your Android settings.") {
+ if (BuildConfig.PUSH_CONFIGURED) row { SwitchRow("Push notifications", isOn = state.notifications, onChange = store::notifications) }
+ else row { Text("Push isn't set up in this build. Bots and chats still update while Codync is open.", style = Type.subheadline, color = Palette.secondary) }
+ row {
+ ValueRow("Notifications", if (allowed) "On" else if (asked) "Off in Settings" else "Turn on", Modifier.plainButton {
+ if (!allowed && !asked && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) request.launch(Manifest.permission.POST_NOTIFICATIONS)
+ else openNotificationSettings(context)
+ })
+ }
+ }
+}
+
+/** The paired computer: its connection, how it's reached, and whether it's in the account. */
+@Composable private fun ComputerRow(state: AppState, store: AppStore, inAccount: Boolean, extensions: () -> Unit, remove: () -> Unit) {
+ val computer = state.computers.first()
+ val link = state.connection
+ val online = link is LinkState.Ready
+ val detail = if (link is LinkState.Ready) {
+ val count = state.bots.count { !it.deleted && it.kind != "group" }
+ "$count bot${if (count == 1) "" else "s"} · ${if (link.route == HostRoute.Direct) "Wi-Fi/Tailscale" else "Cloudflare"}"
+ } else connectionLabel(link)
+ Row(Modifier.fillMaxWidth().contextActions(items = {
+ listOfNotNull(
+ if (online) MenuItem("Extensions", icon = "square.grid.2x2", action = extensions) else null,
+ MenuItem("Remove", icon = "trash", destructive = true, divider = online, action = remove),
+ )
+ }), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ ComputerBadge(state.hello?.text("device"), 40.dp)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(state.hello?.text("name") ?: computer.name, style = Type.body.semibold, color = Palette.text, maxLines = 1)
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ val ink = if (link is LinkState.ComputerOffline || link is LinkState.Failed) Palette.warning else Palette.secondary
+ Text(detail, style = Type.subheadline, color = ink, maxLines = 1)
+ if (link is LinkState.Ready) Symbol(if (link.route == HostRoute.Direct) "wifi" else "cloud", size = 14.dp, tint = ink,
+ contentDescription = if (link.route == HostRoute.Direct) "Wi-Fi or Tailscale" else "Through Cloudflare")
+ }
+ }
+ if (online) IconButton("Extensions", "square.grid.2x2", action = extensions)
+ // Which route goes first, and whether Cloudflare is a fallback at all.
+ DropdownMenu({ ConnectionRoute.entries.map { route -> MenuItem(route.title, icon = route.icon, selected = route == computer.route) { store.setRoute(route) } } },
+ Modifier.size(36.dp), label = "Connection") {
+ Symbol(computer.route.icon, size = 21.dp, tint = Palette.secondary)
+ }
+ if (inAccount) Symbol("person.crop.circle.badge.checkmark", size = 20.dp, tint = Palette.tertiary, contentDescription = "In your account")
+ }
+}
+
+/** A computer in the account that this phone can't use yet. */
+@Composable private fun AccountComputerRow(computer: CloudComputer, code: String?, canAsk: Boolean, ask: () -> Unit) {
+ val online = if (computer.online == true) "Online" else "Offline"
+ val detail = when {
+ code != null -> "Waiting for your OK on the computer · $code"
+ computer.access == "granted" -> "Approved for an earlier install of Codync. Ask again to use it here."
+ computer.access == "pending" -> "$online · A request is waiting"
+ canAsk -> "$online · In your account"
+ // One computer per phone for now: the paired one goes first.
+ else -> "$online · Remove this phone's computer to use this one"
+ }
+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Box(Modifier.graphicsLayer { alpha = 0.5f }) { ComputerBadge(computer.device, 40.dp) }
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(computer.name, style = Type.body.semibold, color = Palette.text, maxLines = 1)
+ Text(detail, style = Type.subheadline, color = Palette.secondary, maxLines = 2)
+ }
+ SecondaryButton(if (code != null) "Code" else "Ask for access", enabled = code != null || canAsk, action = ask)
+ }
+}
+
+@Composable private fun HiddenBotRow(state: AppState, store: AppStore, bot: Bot) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ BotAvatar(bot, state.bots, 28.dp)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(1.dp)) {
+ Text(bot.name, style = Type.body, color = Palette.text, maxLines = 1)
+ Text(state.hello?.text("name") ?: state.computers.firstOrNull()?.name.orEmpty(), style = Type.caption, color = Palette.tertiary)
+ }
+ IconButton("Unhide", "eye") {
+ store.command("updateBot", buildJsonObject { put("id", bot.id); put("hidden", false) }, "roster:" + bot.id)
+ }
+ }
+}
+
+/** A computer's icon showing what it is (laptop, desktop, Linux), as CodyncUI `ComputerBadge`. */
+@Composable internal fun ComputerBadge(device: String?, size: Dp) {
+ Box(Modifier.size(size), contentAlignment = Alignment.Center) {
+ when (device) {
+ "linux" -> Symbol("computer.linux", size = size * 0.55f, tint = Palette.text)
+ "laptop" -> Symbol("laptopcomputer", size = size * 0.6f, tint = Palette.text)
+ else -> Symbol("desktopcomputer", size = size * 0.6f, tint = Palette.text)
+ }
+ }
+}
+
+private val ConnectionRoute.title get() = when (this) {
+ ConnectionRoute.Automatic -> "Auto: Wi-Fi or Tailscale, then Cloudflare"
+ ConnectionRoute.CloudflareFirst -> "Cloudflare, then Wi-Fi or Tailscale"
+ ConnectionRoute.DirectOnly -> "Wi-Fi or Tailscale only, never Cloudflare"
+}
+
+private val ConnectionRoute.icon get() = when (this) {
+ ConnectionRoute.Automatic -> "arrow.triangle.branch"
+ ConnectionRoute.CloudflareFirst -> "cloud"
+ ConnectionRoute.DirectOnly -> "wifi"
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/SetupTerminal.kt b/apps/android/app/src/main/kotlin/com/codync/android/SetupTerminal.kt
new file mode 100644
index 00000000..01899e3a
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/SetupTerminal.kt
@@ -0,0 +1,117 @@
+package com.codync.android
+
+import android.content.ClipData
+import android.content.ClipDescription
+import android.content.ClipboardManager
+import android.content.Intent
+import android.os.Build
+import android.os.PersistableBundle
+import androidx.activity.compose.BackHandler
+import androidx.activity.compose.LocalActivity
+import androidx.compose.foundation.background
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.AgentAuthMethod
+import com.codync.android.core.AgentBackend
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import java.util.UUID
+
+/**
+ * Installing or signing in to an agent, or adding Node.js, live (iOS `SetupTerminalView`): the
+ * command runs in a terminal on the computer and this screen is that terminal (links open here).
+ * `backend` is null only for the `node` step, which belongs to the computer.
+ */
+@Composable internal fun SetupTerminal(backend: AgentBackend?, step: String, method: AgentAuthMethod?, state: AppState, store: AppStore, back: () -> Unit) {
+ val owner = rememberSaveable { UUID.randomUUID().toString() }
+ val session = remember(owner) { store.setupTerminal(owner, backend?.id.orEmpty(), step, method?.id) }
+ val status by session.state.collectAsState()
+ var renderer by remember { mutableStateOf<TerminalRenderer?>(null) }
+ var renderError by remember { mutableStateOf(false) }
+ val activity = LocalActivity.current
+ val context = LocalContext.current
+ val clipboard = remember(context) { context.getSystemService(ClipboardManager::class.java) }
+ // Leaving the screen ends whatever is still running; rotation keeps it.
+ val leave = { store.closeSetupTerminal(owner); back() }
+ DisposableEffect(session) {
+ onDispose {
+ renderer?.let(session::detach)
+ if (activity?.isChangingConfigurations != true) store.closeSetupTerminal(owner)
+ }
+ }
+ BackHandler(onBack = leave)
+ val name = backend?.name ?: "the agent"
+ val title = when (step) { "node" -> "Add Node.js"; "install" -> "Install $name"; else -> method?.name ?: "Sign in to $name" }
+ val live = status.connected && status.exitCode == null && status.error == null
+ Column(Modifier.fillMaxSize().background(Palette.background).imePadding()) {
+ ScreenHeader({ BackButton(leave) }, { Text(title, style = Type.body.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis) }) {
+ IconButton("Copy selection", "doc.on.doc", enabled = renderer != null) { renderer?.copySelection() }
+ }
+ Box(Modifier.weight(1f).fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 6.dp).clip(RoundedRectangle(12.dp))) {
+ if (!renderError) TerminalSurface(Modifier.fillMaxSize(), { target -> renderer = target; session.attach(target) }, session::type, session::resized,
+ { renderError = true; store.closeSetupTerminal(owner); renderer = null },
+ openLink = { uri -> runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, uri)) } },
+ copy = { text ->
+ val clip = ClipData.newPlainText("Agent setup terminal", text)
+ if (Build.VERSION.SDK_INT >= 33) clip.description.extras = PersistableBundle().apply { putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true) }
+ clipboard.setPrimaryClip(clip)
+ }, created = { renderer = it })
+ }
+ // The keys a phone keyboard lacks.
+ Row(Modifier.horizontalScroll(rememberScrollState()).padding(horizontal = 10.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ for ((label, bytes) in listOf("Ctrl+C" to byteArrayOf(3), "Tab" to byteArrayOf(9), "Esc" to byteArrayOf(27))) {
+ Key(label, live) { session.type(bytes) }
+ }
+ Key("Keyboard", renderer != null) { renderer?.focus(showKeyboard = true) }
+ }
+ Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ val code = status.exitCode
+ val error = status.error
+ when {
+ renderError -> Text("The terminal couldn't load. Update Android System WebView, then try again.", Modifier.weight(1f),
+ style = Type.footnote, color = Palette.danger, maxLines = 2)
+ error != null -> Text(error, Modifier.weight(1f), style = Type.footnote, color = Palette.danger, maxLines = 2)
+ code != null -> {
+ Symbol(if (code == 0) "checkmark.circle.fill" else "exclamationmark.circle.fill", size = 16.dp, tint = if (code == 0) Palette.added else Palette.warning)
+ Text(if (code == 0) "Finished." else "Ended with an error ($code).", Modifier.weight(1f), style = Type.footnote, color = Palette.secondary)
+ }
+ else -> {
+ ThinkingOrb(size = 14.dp, color = Palette.secondary)
+ Text(if (status.starting) "Starting setup on ${state.hostName}…" else if (!status.connected) "Reconnecting to the setup terminal…"
+ else "Running on ${state.hostName}. Links open on this device.", Modifier.weight(1f), style = Type.footnote, color = Palette.secondary, maxLines = 2)
+ }
+ }
+ if (code != null) PrimaryButton("Done", action = leave)
+ }
+ }
+}
+
+@Composable private fun Key(label: String, enabled: Boolean, action: () -> Unit) {
+ Text(label, Modifier.clip(Capsule()).background(Palette.bubbleAgent).plainButton(enabled = enabled, action = action)
+ .padding(horizontal = 12.dp, vertical = 6.dp), style = Type.footnote.medium, color = if (enabled) Palette.text else Palette.tertiary)
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/SlashCommands.kt b/apps/android/app/src/main/kotlin/com/codync/android/SlashCommands.kt
new file mode 100644
index 00000000..d0877c73
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/SlashCommands.kt
@@ -0,0 +1,96 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.AppVersion
+import com.codync.android.core.Bot
+import com.codync.android.core.InstalledSkill
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+
+/** A command in the composer's `/` list (iOS `SlashCommand`): Fast mode, New session, or one of the bot's skills. */
+internal data class SlashCommand(val name: String, val icon: String, val title: String, val detail: String, val warning: Boolean,
+ val skill: String? = null)
+
+/**
+ * The composer's `/` commands, listed while the draft is just `/partial` (iOS `SlashCommands`): Fast mode
+ * and New session run here; a skill fills in `/<id> `, which the host turns into "read this skill first".
+ */
+internal object SlashCommands {
+ /** The first host that understands `/skill` messages; older ones get the text as typed. */
+ private const val MIN_SKILLS_HOST = "2.14.1"
+
+ /** The command name being typed after a leading `/`, before any space. */
+ fun query(draft: String): String? = if (draft.startsWith("/") && draft.none(Char::isWhitespace)) draft.drop(1) else null
+
+ /** Built-in commands, then the bot's skills, whose name or title holds `query` (none in a group). */
+ fun list(bot: Bot, query: String, skills: List<InstalledSkill>, hostVersion: String?): List<SlashCommand> {
+ if (bot.kind == "group") return emptyList()
+ val own = if (hostVersion != null && AppVersion.isBelow(hostVersion, MIN_SKILLS_HOST)) emptyList()
+ else skills.filter { it.id in bot.skills }.map { SlashCommand(it.id, "book.pages", it.name, it.description, false, it.id) }
+ return (builtIn(bot) + own).filter { query.isEmpty() || it.name.contains(query, true) || it.title.contains(query, true) }
+ }
+
+ /** A draft that is just a built-in command (`/fast`, `/new`): sending it runs the command. */
+ fun builtIn(bot: Bot, draft: String): SlashCommand? = query(draft.trim())?.let { name -> builtIn(bot).firstOrNull { it.name == name } }
+
+ private fun builtIn(bot: Bot): List<SlashCommand> = if (bot.kind == "group") emptyList() else buildList {
+ if (bot.fastModeShown) add(SlashCommand("fast", "bolt", "Fast mode", bot.fastModeRefusal
+ ?: if (bot.fastMode) "Turn off and return to standard speed" else "Turn on for faster replies and more usage", bot.fastModeRefusal != null))
+ add(SlashCommand("new", "arrow.counterclockwise", "New session", "Start over with a fresh context; the transcript stays", false))
+ }
+}
+
+/** The `/` list above the box: each command's icon, name and what it does; tapping one runs it (iOS `CommandList`). */
+@Composable internal fun CommandList(commands: List<SlashCommand>, pick: (SlashCommand) -> Unit, modifier: Modifier = Modifier) {
+ Column(modifier.fillMaxWidth().heightIn(max = 280.dp).glass(RoundedRectangle(20.dp)).verticalScroll(rememberScrollState())
+ .padding(vertical = 6.dp)) {
+ for (command in commands) Row(Modifier.fillMaxWidth().plainButton { pick(command) }
+ .semantics(mergeDescendants = true) { contentDescription = command.title }.padding(horizontal = 14.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Box(Modifier.width(20.dp), contentAlignment = Alignment.Center) { Symbol(command.icon, size = 17.dp, tint = Palette.secondary) }
+ Text(command.title, style = Type.subheadline, color = Palette.text, maxLines = 1)
+ Text(command.detail, Modifier.weight(1f), style = Type.subheadline, color = if (command.warning) Palette.warning else Palette.secondary,
+ maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ }
+}
+
+/** The bots to @mention above a group's box: chips with their faces (iOS `SuggestionChip`). */
+@Composable internal fun MentionChips(members: List<Bot>, bots: List<Bot>, mention: (Bot) -> Unit) {
+ Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ for (member in members) Row(Modifier.clip(Capsule()).background(Palette.surface).plainButton { mention(member) }
+ .padding(horizontal = 10.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ BotAvatar(member, bots, 18.dp)
+ Text(member.name, style = Type.subheadline, color = Palette.text, maxLines = 1)
+ }
+ }
+}
+
+/** The `@partial` being typed at the end of a group's draft, if any. */
+internal fun mentionQuery(draft: String): String? {
+ val at = draft.lastIndexOf('@')
+ if (at < 0 || at > 0 && !draft[at - 1].isWhitespace()) return null
+ val query = draft.substring(at + 1)
+ return if (query.contains('\n') || query.length > 24) null else query
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt
new file mode 100644
index 00000000..f3ecf74a
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt
@@ -0,0 +1,233 @@
+package com.codync.android
+
+import android.Manifest
+import android.app.NotificationManager
+import android.appwidget.AppWidgetManager
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.os.Build
+import android.provider.Settings
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.togetherWith
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.heading
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.semantics.stateDescription
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import androidx.core.content.ContextCompat
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import androidx.lifecycle.compose.LocalLifecycleOwner
+import com.codync.android.core.UsageReport
+import com.codync.android.core.WidgetKind
+import com.codync.android.core.teamSlots
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+
+/** The surfaces outside the app, as the iOS State tab has Widget, Live Activity and Dynamic Island. */
+private enum class Surface { Widget, LiveUpdate, StatusBar }
+
+/**
+ * Where your bots show up outside the app, each designed and switched on here: Home Screen
+ * widgets, Live updates (Android's Live Activity) and the status bar chip (its Dynamic Island).
+ * Usage limits open from the header.
+ */
+@Composable internal fun StateScreen(state: AppState, store: AppStore?, usage: () -> Unit, bottomInset: Dp, active: Boolean = true) {
+ var surface by rememberSaveable { mutableStateOf(Surface.Widget) }
+ Column(Modifier.fillMaxSize().background(Palette.background).statusBarsPadding()) {
+ ScreenHeader(title = { Text("State", style = Type.body.semibold, color = Palette.text) },
+ trailing = { IconButton("Usage limits", "chart.bar", action = usage) })
+ SegmentedChoice(surface, listOf(Surface.Widget to "Widget", Surface.LiveUpdate to "Live update", Surface.StatusBar to "Status bar"),
+ { surface = it }, Modifier.padding(horizontal = 16.dp).padding(bottom = 8.dp))
+ AnimatedContent(surface, Modifier.weight(1f), transitionSpec = { fadeIn(Motion.fade()) togetherWith fadeOut(Motion.fade()) },
+ label = "Surface") { shown ->
+ Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(start = 18.dp, end = 18.dp, top = 18.dp, bottom = bottomInset),
+ verticalArrangement = Arrangement.spacedBy(24.dp)) {
+ when (shown) {
+ Surface.Widget -> WidgetGallery(state, store, active) { surface = Surface.LiveUpdate }
+ Surface.LiveUpdate -> LiveUpdateGallery(state, store, chip = false)
+ Surface.StatusBar -> LiveUpdateGallery(state, store, chip = true)
+ }
+ }
+ }
+ }
+}
+
+/** Re-checks a system setting each time Codync comes back to the front (the user may have changed it). */
+@Composable internal fun <T> rememberOnResume(read: () -> T): T {
+ val owner = LocalLifecycleOwner.current
+ var value by remember { mutableStateOf(read()) }
+ DisposableEffect(owner) {
+ val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) value = read() }
+ owner.lifecycle.addObserver(observer)
+ onDispose { owner.lifecycle.removeObserver(observer) }
+ }
+ return value
+}
+
+internal fun notificationsAllowed(context: Context) = context.getSystemService(NotificationManager::class.java).areNotificationsEnabled()
+
+internal fun openNotificationSettings(context: Context) = context.startActivity(Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
+ .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+
+/** The State tab's Widget page: the installed widgets and these previews share their layouts. */
+@Composable private fun WidgetGallery(state: AppState, store: AppStore?, active: Boolean, keepInView: () -> Unit) {
+ val context = LocalContext.current
+ val installed = rememberOnResume { runCatching { CodyncWidgets.installed(context) }.getOrNull() }
+ var asked by remember { mutableIntStateOf(0) }
+ val allowed = rememberOnResume { notificationsAllowed(context) } || asked > 0 && notificationsAllowed(context)
+ val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { asked++; store?.syncPush() }
+ var kind by rememberSaveable { mutableStateOf("usage") }
+ var provider by rememberSaveable { mutableStateOf("claude") }
+ var size by rememberSaveable { mutableStateOf("medium") }
+ var pinFailed by remember { mutableStateOf(false) }
+
+ Row(Modifier.fillMaxWidth().clip(RoundedRectangle(22.dp)).background(Palette.surface).padding(16.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ Box(Modifier.size(58.dp).clip(RoundedRectangle(16.dp)).background(Palette.bubbleUser), contentAlignment = Alignment.Center) {
+ CharacterAvatar("hex", "gray", 42.dp)
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text("Codync, at a glance.", style = Type.title3.semibold, color = Palette.text)
+ Text("Your bots and usage, on every surface.", style = Type.footnote, color = Palette.secondary)
+ }
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(9.dp)) {
+ SectionLabel("Get set up")
+ Column(Modifier.fillMaxWidth().clip(RoundedRectangle(18.dp)).background(Palette.surface)) {
+ SetupRow("Connect a computer", state.computers.isNotEmpty())
+ Hairline(Modifier.padding(start = 42.dp))
+ SetupRow("Add a Codync widget", installed?.let { it > 0 } == true, if (installed == null) "Unable to check" else null)
+ Hairline(Modifier.padding(start = 42.dp))
+ SetupRow(if (!allowed && asked > 0) "Turn on notifications in Settings" else "Turn on notifications", allowed,
+ action = if (allowed) null else ({
+ if (Build.VERSION.SDK_INT >= 33 && asked == 0 &&
+ ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED)
+ permission.launch(Manifest.permission.POST_NOTIFICATIONS)
+ else openNotificationSettings(context)
+ }))
+ }
+ Text(if (installed == null) "Couldn't check your widgets. You can still add one below." else "Steps check themselves as you finish them.",
+ style = Type.caption2, color = Palette.tertiary)
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Box(Modifier.weight(1f)) { SectionLabel("Choose your widget") }
+ Text("Sample data", style = Type.caption2, color = Palette.secondary)
+ }
+ SegmentedChoice(kind, listOf("usage" to "Provider usage", "bots" to "Bots", "team" to "Team"), { kind = it })
+ val report = remember(state.usage) { runCatching { UsageReport.decode(state.usage) }.getOrNull() }
+ val providers = (WidgetPreview.usage.providers + report?.providers.orEmpty()).distinctBy { it.id }
+ if (kind == "usage") {
+ if (providers.size <= 3) SegmentedChoice(provider, providers.map { it.id to it.name }, { provider = it })
+ else ChoicePicker(provider, providers.map { it.id to it.name }, { provider = it })
+ }
+ if (kind != "team") ChoicePicker(size, listOf("small" to "Small", "medium" to "Medium", "large" to "Large"), { size = it })
+ Column(Modifier.fillMaxWidth().clip(RoundedRectangle(26.dp)).background(Palette.bubbleAgent).padding(14.dp),
+ verticalArrangement = Arrangement.spacedBy(18.dp), horizontalAlignment = Alignment.CenterHorizontally) {
+ val small = size == "small" || kind == "team"
+ Box(Modifier.then(if (small) Modifier.width(158.dp) else Modifier.fillMaxWidth())
+ .height(if (size == "large" && kind != "team") 338.dp else 158.dp)
+ .clip(RoundedRectangle(22.dp)).background(Palette.surface).padding(14.dp)
+ .semantics { contentDescription = "${size.replaceFirstChar(Char::uppercase)} widget preview" }) {
+ when (kind) {
+ "usage" -> providers.firstOrNull { it.id == provider }?.let {
+ ProviderWidgetCard(it, if (size == "large") ProviderLayout.Large else if (size == "medium") ProviderLayout.Medium else ProviderLayout.Small)
+ }
+ "team" -> BotsTeamCard(teamSlots(WidgetPreview.bots, emptyList()))
+ else -> BotsWidgetCard(WidgetPreview.bots, WidgetPreview.activities, wide = size != "small", large = size == "large")
+ }
+ }
+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(if (kind == "team") "Small widget" else "${size.replaceFirstChar(Char::uppercase)} widget", style = Type.subheadline.medium, color = Palette.text)
+ Text(when (kind) {
+ "usage" -> "Small shows the tightest limit. Medium shows two windows. Large adds a summary and up to four limits."
+ "team" -> "Four bots as characters with a dot for each one at work; the bots that need you come first."
+ else -> "See who needs you and who's still working. Large shows up to six bots."
+ }, style = Type.caption, color = Palette.secondary)
+ }
+ }
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ SectionLabel("Choose the look")
+ val revision by WidgetStore.changes.collectAsState()
+ val original = remember(revision) { WidgetStore.originalIcons(context) }
+ SegmentedChoice(original, listOf(false to "Character", true to "Original icon"), { WidgetStore.setOriginalIcons(context, it) })
+ Text("Applies to Usage in the app and in widgets.", style = Type.caption, color = Palette.secondary)
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ SectionLabel("Keep tasks in view")
+ Row(Modifier.plainButton(action = keepInView), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol("lock.rectangle", size = 18.dp, tint = Palette.accent)
+ Text("Live updates on your Lock Screen", style = Type.subheadline, color = Palette.accent)
+ }
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ SectionLabel("Add a widget")
+ val kindToPin = when (kind) { "usage" -> WidgetKind.Provider; "team" -> WidgetKind.Team; else -> WidgetKind.Bots }
+ if (AppWidgetManager.getInstance(context).isRequestPinAppWidgetSupported)
+ PrimaryButton("Add to Home Screen") { pinFailed = !CodyncWidgets.pin(context, kindToPin) }
+ if (pinFailed) Text("Your launcher couldn't add it. Add it from the Home Screen instead.", style = Type.footnote, color = Palette.danger)
+ WidgetSetupDemo(active)
+ }
+ Text("Widgets show the latest report. Open Codync for live updates and approvals.", style = Type.caption2, color = Palette.tertiary)
+}
+
+@Composable internal fun SectionLabel(title: String) =
+ Text(title, Modifier.semantics { heading() }, style = Type.caption.medium, color = Palette.secondary)
+
+@Composable private fun SetupRow(title: String, complete: Boolean, status: String? = null, action: (() -> Unit)? = null) {
+ Row(Modifier.fillMaxWidth().then(if (action != null) Modifier.clickable(role = Role.Button, onClick = action) else Modifier)
+ .semantics(mergeDescendants = true) { stateDescription = status ?: if (complete) "Complete" else "Not complete" }
+ .padding(14.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Symbol(if (complete) "checkmark.circle.fill" else "circle", size = 18.dp, tint = if (complete) Palette.added else Palette.tertiary)
+ Text(title, Modifier.weight(1f), style = Type.footnote, color = if (complete) Palette.secondary else Palette.text)
+ if (status != null) Text(status, style = Type.caption2, color = Palette.tertiary)
+ }
+}
+
+@Composable internal fun SettingsLink(title: String, action: () -> Unit) =
+ LinkButton(title, style = Type.footnote.medium, color = Palette.accent, action = action)
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/TaskFeed.kt b/apps/android/app/src/main/kotlin/com/codync/android/TaskFeed.kt
new file mode 100644
index 00000000..eaece763
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/TaskFeed.kt
@@ -0,0 +1,58 @@
+package com.codync.android
+
+import android.util.AtomicFile
+import com.codync.android.core.Bot
+import com.codync.android.core.WireJson
+import java.io.File
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.encodeToString
+
+@Serializable
+data class TaskWatch(val taskId: String = java.util.UUID.randomUUID().toString(), val botId: String, val name: String, val status: String = "working", val finished: Boolean = false,
+ val seenRunning: Boolean = false, val timestamp: Long = 0, val lastRev: Long = 0, val deadline: Long = System.currentTimeMillis() + 900_000,
+ val startedAt: Long = System.currentTimeMillis(), val avatarShape: String = "blob", val avatarColor: String = "blue", val activity: String = "")
+
+/** Bounded delegation markers; inactive contexts never render or accept these updates. */
+class TaskFeed(directory: File) {
+ private val file = AtomicFile(File(directory, "tasks.json"))
+ fun all(): List<TaskWatch> = synchronized(lock) {
+ if (!file.baseFile.exists()) emptyList() else WireJson.decodeFromString<List<TaskWatch>>(file.readFully().toString(Charsets.UTF_8))
+ }
+ fun clear() = synchronized(lock) { file.delete() }
+ fun start(bot: Bot): TaskWatch = synchronized(lock) {
+ val running = bot.status in setOf("working", "needsInput")
+ val watch = TaskWatch(botId = bot.id, name = bot.name, lastRev = bot.rev, seenRunning = running,
+ status = if (running) bot.status else "working", avatarShape = bot.avatarShape, avatarColor = bot.avatarColor)
+ save((all().filter { it.botId != bot.id } + watch).takeLast(16))
+ watch
+ }
+ fun local(bot: Bot): TaskWatch? = synchronized(lock) {
+ val watch = all().firstOrNull { it.botId == bot.id && !it.finished } ?: return@synchronized null
+ if (bot.rev <= watch.lastRev) return@synchronized null
+ if (bot.status !in setOf("working", "needsInput", "idle", "error") || bot.status == "idle" && !watch.seenRunning) return@synchronized null
+ val updated = watch.copy(name = bot.name, status = bot.status, finished = bot.status in setOf("idle", "error"), activity = bot.activity,
+ seenRunning = true, lastRev = bot.rev, deadline = System.currentTimeMillis() + 900_000)
+ save(all().map { if (it.botId == bot.id) updated else it })
+ updated
+ }
+ fun remote(data: Map<String, String>, botId: String): TaskWatch? = synchronized(lock) {
+ val watch = all().firstOrNull { it.botId == botId && it.taskId == data["taskId"] && !it.finished } ?: return@synchronized null
+ val status = data["status"]?.takeIf { it in setOf("working", "needsInput", "idle", "error") } ?: return@synchronized null
+ val timestamp = data["timestamp"]?.toLongOrNull() ?: return@synchronized null
+ val stale = data["staleDate"]?.toLongOrNull() ?: return@synchronized null
+ val now = System.currentTimeMillis() / 1000
+ if (timestamp < 0 || timestamp > now + 60 || stale < timestamp || stale > timestamp + 3600 || stale <= now ||
+ timestamp < watch.timestamp || watch.finished && timestamp <= watch.timestamp) return@synchronized null
+ val event = data["event"] ?: return@synchronized null
+ if (event !in setOf("update", "end") || (event == "end") != (status in setOf("idle", "error"))) return@synchronized null
+ val updated = watch.copy(status = status, finished = event == "end", seenRunning = true, timestamp = timestamp, deadline = stale * 1000)
+ save(all().map { if (it.botId == botId) updated else it })
+ updated
+ }
+ private fun save(watches: List<TaskWatch>) {
+ val output = file.startWrite()
+ try { output.write(WireJson.encodeToString(watches).toByteArray()); file.finishWrite(output) }
+ catch (error: Throwable) { file.failWrite(output); throw error }
+ }
+ companion object { private val lock = Any() }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/TerminalSurface.kt b/apps/android/app/src/main/kotlin/com/codync/android/TerminalSurface.kt
new file mode 100644
index 00000000..af7f0e53
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/TerminalSurface.kt
@@ -0,0 +1,178 @@
+package com.codync.android
+
+import android.annotation.SuppressLint
+import android.net.Uri
+import android.view.accessibility.AccessibilityManager
+import android.view.inputmethod.EditorInfo
+import android.view.inputmethod.InputConnection
+import com.codync.android.core.TerminalSink
+import android.webkit.JavascriptInterface
+import android.webkit.RenderProcessGoneDetail
+import android.webkit.WebResourceRequest
+import android.webkit.WebResourceResponse
+import android.webkit.WebView
+import android.webkit.WebViewClient
+import androidx.compose.runtime.*
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.viewinterop.AndroidView
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import androidx.lifecycle.compose.LocalLifecycleOwner
+import java.io.ByteArrayInputStream
+import java.util.Base64
+import java.util.concurrent.atomic.AtomicBoolean
+import kotlinx.coroutines.CompletableDeferred
+import com.codync.android.core.deadline
+
+/** Only bundled terminal assets run here. Terminal output is bytes; it never becomes HTML or JavaScript. */
+internal class TerminalRenderer internal constructor(internal val view: WebView) : TerminalSink {
+ private var nextWrite = 0
+ private val writes = mutableMapOf<Int, CompletableDeferred<Unit>>()
+ var disposed = false
+ private set
+ override suspend fun write(bytes: ByteArray) {
+ check(!disposed && bytes.size <= 256 * 1024)
+ val id = ++nextWrite
+ val done = CompletableDeferred<Unit>()
+ writes[id] = done
+ val encoded = Base64.getEncoder().encodeToString(bytes)
+ view.evaluateJavascript("codyncTerminal.write($id, '$encoded')", null)
+ try { deadline(10_000, "The terminal stopped responding.") { done.await() } } finally { writes.remove(id) }
+ }
+ override fun reset() { if (!disposed) view.evaluateJavascript("codyncTerminal.reset()", null) }
+ override fun input(enabled: Boolean) { if (!disposed) view.evaluateJavascript("codyncTerminal.input($enabled)", null) }
+ fun focus(showKeyboard: Boolean = false) {
+ if (disposed) return
+ view.requestFocus()
+ view.evaluateJavascript("codyncTerminal.focus()") {
+ if (showKeyboard && !disposed) view.context.getSystemService(android.view.inputmethod.InputMethodManager::class.java)
+ .showSoftInput(view, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
+ }
+ }
+ fun copySelection() { if (!disposed) view.evaluateJavascript("codyncTerminal.copySelection()", null) }
+ fun screenReader(enabled: Boolean) {
+ if (!disposed) view.evaluateJavascript("window.codyncTerminal?.screenReader($enabled)", null)
+ }
+ fun written(id: Int) { writes.remove(id)?.complete(Unit) }
+ fun dispose() { disposed = true; writes.values.forEach { it.cancel() }; writes.clear() }
+}
+
+/** A terminal edits a remote command line; the IME must not rewrite earlier commands. */
+private class TerminalWebView(context: android.content.Context) : WebView(context) {
+ override fun onCreateInputConnection(info: EditorInfo): InputConnection? {
+ val connection = super.onCreateInputConnection(info)
+ if (connection != null && info.inputType and android.text.InputType.TYPE_MASK_CLASS == android.text.InputType.TYPE_CLASS_TEXT) {
+ info.inputType = info.inputType or android.text.InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
+ info.imeOptions = info.imeOptions or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING or EditorInfo.IME_FLAG_NO_EXTRACT_UI
+ }
+ return connection
+ }
+}
+
+@SuppressLint("SetJavaScriptEnabled")
+@Composable internal fun TerminalSurface(modifier: Modifier, ready: (TerminalRenderer) -> Unit,
+ input: (ByteArray) -> Unit, resized: (Int, Int) -> Unit, failure: () -> Unit,
+ openLink: (Uri) -> Unit = {}, copy: (String) -> Unit = {}, created: (TerminalRenderer) -> Unit = {}) {
+ val context = LocalContext.current
+ val accessibility = context.getSystemService(AccessibilityManager::class.java)
+ val lifecycle = LocalLifecycleOwner.current.lifecycle
+ val onReady by rememberUpdatedState(ready); val onInput by rememberUpdatedState(input)
+ val onResize by rememberUpdatedState(resized); val onFailure by rememberUpdatedState(failure)
+ val onOpen by rememberUpdatedState(openLink); val onCopy by rememberUpdatedState(copy)
+ val view = remember {
+ TerminalWebView(context).apply {
+ layoutParams = android.view.ViewGroup.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT)
+ settings.javaScriptEnabled = true
+ settings.useWideViewPort = true
+ settings.allowFileAccess = false; settings.allowContentAccess = false
+ settings.blockNetworkLoads = true; settings.domStorageEnabled = false
+ settings.javaScriptCanOpenWindowsAutomatically = false
+ settings.setSupportMultipleWindows(false)
+ settings.cacheMode = android.webkit.WebSettings.LOAD_NO_CACHE
+ setBackgroundColor(android.graphics.Color.rgb(17, 17, 17))
+ importantForAutofill = android.view.View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS
+ isFocusableInTouchMode = true
+ }
+ }
+ DisposableEffect(view, lifecycle) {
+ val closed = AtomicBoolean(false)
+ var destroyed = false
+ // Xterm's accessibility path intentionally suppresses ordinary insertText events.
+ // Use it for a screen reader rather than suppressing Android IME commits for everyone.
+ val screenReader = AtomicBoolean(accessibility.isTouchExplorationEnabled)
+ val renderer = TerminalRenderer(view)
+ created(renderer)
+ fun main(block: () -> Unit) { view.post { if (!closed.get()) block() } }
+ val bridge = object {
+ @JavascriptInterface fun screenReaderEnabled(): Boolean = screenReader.get()
+ @JavascriptInterface fun ready() = main { renderer.focus(); onReady(renderer) }
+ @JavascriptInterface fun failed() = main { onFailure() }
+ @JavascriptInterface fun resized(cols: Int, rows: Int) = main { if (cols in 20..500 && rows in 4..500) onResize(cols, rows) }
+ @JavascriptInterface fun written(id: Int) = main { renderer.written(id) }
+ @JavascriptInterface fun input(encoded: String) {
+ if (encoded.length > 90_000) { main { renderer.input(false); onFailure() }; return }
+ val bytes = try { Base64.getDecoder().decode(encoded) } catch (_: Exception) { main { onFailure() }; return }
+ main { onInput(bytes) }
+ }
+ @JavascriptInterface fun openLink(text: String) = main {
+ if (text.length > 8_192 || text.any { it.isISOControl() }) return@main
+ val uri = Uri.parse(text)
+ if (uri.scheme in listOf("http", "https") && !uri.host.isNullOrBlank() && uri.userInfo == null) onOpen(uri)
+ }
+ @JavascriptInterface fun copy(text: String) = main { if (text.isNotEmpty() && text.length <= 256 * 1024) onCopy(text) }
+ }
+ view.addJavascriptInterface(bridge, "CodyncTerminal")
+ val accessibilityListener = AccessibilityManager.TouchExplorationStateChangeListener { enabled ->
+ screenReader.set(enabled)
+ main { renderer.screenReader(enabled) }
+ }
+ accessibility.addTouchExplorationStateChangeListener(accessibilityListener)
+ val observer = LifecycleEventObserver { _, event ->
+ if (event == Lifecycle.Event.ON_RESUME) view.onResume()
+ if (event == Lifecycle.Event.ON_PAUSE) view.onPause()
+ }
+ lifecycle.addObserver(observer)
+ view.webViewClient = object : WebViewClient() {
+ override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
+ if (!closed.getAndSet(true)) {
+ renderer.dispose()
+ (view.parent as? android.view.ViewGroup)?.removeView(view)
+ view.destroy(); destroyed = true
+ onFailure()
+ }
+ return true
+ }
+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean = true
+ override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse {
+ val uri = request.url
+ val name = uri.path?.removePrefix("/")
+ val files = mapOf("index.html" to "text/html", "xterm.js" to "text/javascript", "addon-fit.js" to "text/javascript", "addon-web-links.js" to "text/javascript",
+ "bridge.js" to "text/javascript", "guard.js" to "text/javascript", "xterm.css" to "text/css", "terminal.css" to "text/css")
+ if (uri.scheme == "https" && uri.host == "terminal.codync.invalid" && uri.port == -1 && uri.query == null && name in files)
+ return WebResourceResponse(files.getValue(requireNotNull(name)), "UTF-8", context.assets.open("terminal/$name"))
+ return WebResourceResponse("text/plain", "UTF-8", 403, "Blocked", emptyMap(), ByteArrayInputStream(byteArrayOf()))
+ }
+ }
+ // Loading before AndroidView's first layout gives WebView a zero-height CSS viewport.
+ var loaded = false
+ val layout = android.view.View.OnLayoutChangeListener { _, left, top, right, bottom, _, _, _, _ ->
+ if (!loaded && right > left && bottom > top) {
+ loaded = true
+ view.loadUrl("https://terminal.codync.invalid/index.html")
+ }
+ }
+ view.addOnLayoutChangeListener(layout)
+ onDispose {
+ accessibility.removeTouchExplorationStateChangeListener(accessibilityListener)
+ view.removeOnLayoutChangeListener(layout)
+ lifecycle.removeObserver(observer)
+ closed.set(true); renderer.dispose()
+ if (!destroyed) {
+ view.stopLoading(); view.removeJavascriptInterface("CodyncTerminal")
+ view.loadUrl("about:blank"); view.destroy(); destroyed = true
+ }
+ }
+ }
+ AndroidView(factory = { view }, modifier = modifier)
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/TraceView.kt b/apps/android/app/src/main/kotlin/com/codync/android/TraceView.kt
new file mode 100644
index 00000000..e661544d
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/TraceView.kt
@@ -0,0 +1,125 @@
+package com.codync.android
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.style.TextDecoration
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Bot
+import com.codync.android.core.Entry
+import com.codync.android.design.*
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.jsonPrimitive
+
+/** "Full conversation": everything the agent did, grouped by turn (iOS `TraceView`). */
+@Composable internal fun TraceView(bot: Bot, thread: String?, state: AppState) {
+ val turns = state.entries.filter { it.botId == bot.id && it.threadId == thread }.groupBy { it.turn }.toSortedMap().toList()
+ val list = rememberLazyListState()
+ LaunchedEffect(Unit) { if (turns.isNotEmpty()) list.scrollToItem(turns.lastIndex, Int.MAX_VALUE) }
+ Column(Modifier.fillMaxSize()) {
+ ModalHeader("Full conversation")
+ LazyColumn(state = list, contentPadding = PaddingValues(20.dp), verticalArrangement = Arrangement.spacedBy(22.dp)) {
+ if (turns.isEmpty()) item { Text("Nothing yet.", style = Type.body, color = Palette.tertiary) }
+ items(turns, key = { it.first }) { (turn, entries) ->
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(entries.firstOrNull { it.kind == "user" }?.text ?: "Turn $turn", Modifier.padding(start = 4.dp),
+ style = Type.subheadline.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ CardSection { for (entry in entries) row { TraceRow(entry) } }
+ }
+ }
+ }
+ }
+}
+
+@Composable private fun TraceRow(entry: Entry) {
+ val d = entry.data
+ var expanded by remember { mutableStateOf(false) }
+ when (entry.kind) {
+ "user" -> Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol("person.fill", size = 16.dp, tint = Palette.secondary)
+ Text(entry.text, style = Type.subheadline, color = Palette.text)
+ }
+ "agent" -> Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(if (d["final"]?.jsonPrimitive?.booleanOrNull == true) "Reply" else "Said", style = Type.caption2.bold, color = Palette.tertiary)
+ MarkdownText(entry.text)
+ }
+ "thought" -> Disclosure(expanded, { expanded = !expanded }, label = {
+ ThinkingOrb(size = 16.dp, color = Palette.secondary, animated = false)
+ Text("Thinking", Modifier.padding(start = 8.dp), style = Type.subheadline, color = Palette.secondary)
+ }) { SelectionContainer { Text(entry.text, style = Type.footnote, color = Palette.secondary) } }
+ "tool" -> ToolRow(d)
+ "plan" -> Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol("checklist", size = 16.dp, tint = Palette.text)
+ Text("Plan", style = Type.subheadline.bold, color = Palette.text)
+ }
+ for (item in (d["entries"] as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }) {
+ val status = item.text("status")
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol(when (status) { "completed" -> "checkmark.circle.fill"; "in_progress" -> "circle.dotted"; else -> "circle" }, size = 15.dp,
+ tint = if (status == "completed") Palette.accent else Palette.tertiary)
+ Text(item.text("content").orEmpty(), style = Type.footnote.copy(textDecoration = if (status == "completed") TextDecoration.LineThrough else null),
+ color = Palette.text)
+ }
+ }
+ }
+ "permission" -> Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol("hand.raised", size = 16.dp, tint = Palette.secondary)
+ Text(d.text("title") ?: "Approval", style = Type.subheadline, color = Palette.secondary)
+ }
+ else -> Text(entry.text, style = Type.footnote, color = Palette.tertiary)
+ }
+}
+
+/** A tool call: its kind's symbol, title and outcome; output and diffs unfold. */
+@Composable private fun ToolRow(d: JsonObject) {
+ var expanded by remember { mutableStateOf(false) }
+ val icon = when (d.text("toolKind")) {
+ "read" -> "doc.text"; "edit" -> "pencil"; "delete" -> "trash"; "move" -> "arrow.right.doc.on.clipboard"
+ "search" -> "magnifyingglass"; "execute" -> "terminal"; "think" -> "brain"; "fetch" -> "globe"
+ else -> "wrench.and.screwdriver"
+ }
+ val orb = when (d.text("toolKind")) { "search" -> ThinkingOrbState.Searching; "fetch" -> ThinkingOrbState.Connecting
+ "edit" -> ThinkingOrbState.Shaping; else -> ThinkingOrbState.Working }
+ val diffs = (d["diffs"] as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }
+ val output = d.text("output").orEmpty()
+ val label: @Composable () -> Unit = {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Box(Modifier.width(18.dp), contentAlignment = Alignment.Center) { Symbol(icon, size = 15.dp, tint = Palette.secondary) }
+ Text(d.text("title") ?: "Tool", Modifier.weight(1f), style = Type.subheadline, color = Palette.text, maxLines = 2)
+ when (d.text("status")) {
+ "completed" -> Symbol("checkmark", size = 14.dp, tint = Palette.accent)
+ "failed" -> Symbol("xmark", size = 14.dp, tint = Palette.danger)
+ else -> ThinkingOrb(orb, 16.dp, Palette.secondary)
+ }
+ }
+ }
+ if (output.isEmpty() && diffs.isEmpty()) label()
+ else Disclosure(expanded, { expanded = !expanded }, label = { label() }) {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ for (diff in diffs) DiffView(diff)
+ if (output.isNotEmpty()) CodeBox(output)
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/UpdateNeededCard.kt b/apps/android/app/src/main/kotlin/com/codync/android/UpdateNeededCard.kt
new file mode 100644
index 00000000..660ef265
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/UpdateNeededCard.kt
@@ -0,0 +1,50 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.AppVersion
+import com.codync.android.core.VersionMismatch
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+
+/** Which side must update before this app and the computer can work together (iOS `BotStore.mismatch`), from the host's `hello`. */
+internal val AppState.mismatch: VersionMismatch? get() {
+ val host = hello?.text("version")
+ return VersionMismatch.check(BuildConfig.VERSION_NAME, host, hello?.text("minApp"))
+ // Data this app can't read from a newer host: this app is behind, whatever `minApp` says.
+ ?: if (unreadable && host != null && AppVersion.isBelow(BuildConfig.VERSION_NAME, host)) VersionMismatch.UpdateApp(host) else null
+}
+
+/** Says which side has to update, shown instead of the composer and above the computer's bots. */
+@Composable internal fun UpdateNeededCard(state: AppState, mismatch: VersionMismatch, modifier: Modifier = Modifier) {
+ val host = state.hello?.text("name") ?: state.computers.firstOrNull()?.name ?: "your computer"
+ Row(modifier.fillMaxWidth().clip(RoundedRectangle(16.dp)).background(Palette.surface).padding(14.dp),
+ verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Symbol("arrow.down.circle", size = 22.dp, tint = Palette.warning)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(when (mismatch) {
+ is VersionMismatch.UpdateApp -> "Update this app"
+ is VersionMismatch.UpdateHost -> "Update Codync on $host"
+ }, style = Type.subheadline.semibold, color = Palette.text)
+ Text(when (mismatch) {
+ is VersionMismatch.UpdateApp -> "${state.hello?.text("version")?.let { "$host runs Codync $it and" } ?: host} needs this app to be " +
+ "${mismatch.minimum} or newer. Your chats are safe on the computer."
+ is VersionMismatch.UpdateHost -> "$host runs Codync ${mismatch.version}; this app needs ${mismatch.minimum} or newer. " + when (state.hello?.text("os")) {
+ "macos" -> "Open Codync on that Mac and choose Check for Updates."
+ "linux" -> "Run codync-host update there."
+ else -> "Update Codync on that computer."
+ }
+ }, style = Type.footnote, color = Palette.secondary)
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt
new file mode 100644
index 00000000..bc574191
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt
@@ -0,0 +1,141 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.expandVertically
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.shrinkVertically
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Text
+import androidx.compose.material3.pulltorefresh.PullToRefreshBox
+import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.key
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.rotate
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.LinkState
+import com.codync.android.core.UsageProvider
+import com.codync.android.core.UsageReport
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+import java.time.Instant
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+import java.time.format.FormatStyle
+import kotlin.math.roundToInt
+
+/**
+ * Usage limits, opened from the State tab (iOS `UsageSheet` + `UsageView`): one card per
+ * provider, the tightest limit as a big bar, every limit listed below. Pull down to refresh.
+ */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable fun UsageScreen(state: AppState, refresh: (force: Boolean) -> Unit) {
+ val dismiss = LocalDismissModal.current
+ val report = remember(state.usage) { runCatching { UsageReport.decode(state.usage) }.getOrNull() ?: UsageReport() }
+ val online = state.actualConnection is LinkState.Ready
+ // Opening Usage asks the computer for a current report (it answers from cache when it can).
+ LaunchedEffect(online) { if (online) refresh(false) }
+ Column(Modifier.fillMaxSize()) {
+ ScreenHeader(leading = { IconButton("Close", "xmark", action = dismiss) },
+ title = { Text("Usage", style = Type.body.semibold, color = Palette.text) })
+ if (state.computers.isEmpty()) {
+ EmptyUsage("No computer yet", "Usage shows up once a computer is connected.")
+ return@Column
+ }
+ val pull = rememberPullToRefreshState()
+ PullToRefreshBox("usage" in state.busy, { if (online) refresh(true) }, Modifier.weight(1f), state = pull,
+ indicator = { Box(Modifier.align(Alignment.TopCenter).padding(top = 12.dp).graphicsLayer {
+ alpha = if ("usage" in state.busy) 1f else pull.distanceFraction.coerceIn(0f, 1f) }) { Spinner(18.dp) } }) {
+ Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
+ for (provider in report.providers) key(provider.id) { ProviderCard(provider) }
+ if (report.providers.isEmpty()) EmptyUsage("No usage yet", "Your computer reads the limits from Claude Code and Codex.")
+ }
+ }
+ }
+}
+
+@Composable private fun EmptyUsage(title: String, message: String) {
+ Column(Modifier.fillMaxWidth().padding(top = 60.dp, start = 24.dp, end = 24.dp), horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol("chart.bar", size = 48.dp, tint = Palette.tertiary)
+ Text(title, style = Type.title3.semibold, color = Palette.text, textAlign = TextAlign.Center)
+ Text(message, style = Type.subheadline, color = Palette.secondary, textAlign = TextAlign.Center)
+ }
+}
+
+@Composable private fun ProviderCard(provider: UsageProvider) {
+ var collapsed by rememberSaveable(provider.id) { mutableStateOf(false) }
+ val turn by animateFloatAsState(if (collapsed) 180f else 0f, Motion.layout(), label = "Collapse")
+ val tint = provider.widgetTint()
+ Column(Modifier.fillMaxWidth().clip(RoundedRectangle(20.dp)).background(Palette.surface).padding(14.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Box(Modifier.size(34.dp).clip(RoundedRectangle(10.dp)).background(provider.tint().copy(alpha = 0.12f)), contentAlignment = Alignment.Center) {
+ ProviderMascot(provider, 22.dp)
+ }
+ Text(provider.name, Modifier.weight(1f), style = Type.subheadline.semibold, color = Palette.text)
+ IconButton(if (collapsed) "Expand" else "Collapse", "chevron.up", Modifier.rotate(turn)) { collapsed = !collapsed }
+ }
+ provider.tightest?.let { top ->
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Row {
+ Text(top.label, Modifier.weight(1f), style = Type.subheadline, color = Palette.text)
+ Text(percent(top.percent), style = Type.subheadline.monospacedDigit, color = Palette.text)
+ }
+ UsageTicks(top.percent ?: 0.0, tint, 15.dp)
+ top.resetsShort()?.let { Text(it, Modifier.fillMaxWidth(), style = Type.caption.monospacedDigit, color = Palette.tertiary, textAlign = TextAlign.End) }
+ }
+ }
+ AnimatedVisibility(!collapsed, enter = fadeIn(Motion.fade()) + expandVertically(Motion.layoutSize),
+ exit = fadeOut(Motion.fade()) + shrinkVertically(Motion.layoutSize)) {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ for (window in provider.windows) {
+ DetailRow(window.label, percent(window.percent))
+ window.resetsShort()?.let { DetailRow("${window.label} reset", it.removePrefix("resets ")) }
+ }
+ DetailRow("Source", provider.sourceLabel)
+ DetailRow("Updated", provider.updatedAt?.takeIf { it > 0 }?.let(::updatedAt) ?: "Not reported")
+ }
+ }
+ }
+}
+
+private fun percent(value: Double?) = value?.takeIf { it.isFinite() }?.let { "${it.roundToInt()}%" } ?: "—"
+
+/** "Oct 17, 2026 at 10:20 PM", as iOS formats an abbreviated date with a short time. */
+private fun updatedAt(milliseconds: Long): String {
+ val at = Instant.ofEpochMilli(milliseconds).atZone(ZoneId.systemDefault())
+ val date = at.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM))
+ val time = at.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT))
+ return if (java.util.Locale.getDefault().language == "en") "$date at $time" else "$date $time"
+}
+
+@Composable private fun DetailRow(label: String, value: String) {
+ Row {
+ Text(label, Modifier.weight(1f), style = Type.footnote, color = Palette.secondary)
+ Text(value, style = Type.footnote.monospacedDigit, color = Palette.text)
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/VoiceControls.kt b/apps/android/app/src/main/kotlin/com/codync/android/VoiceControls.kt
new file mode 100644
index 00000000..9ba34606
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/VoiceControls.kt
@@ -0,0 +1,173 @@
+package com.codync.android
+
+import android.Manifest
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.provider.Settings
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.animation.core.RepeatMode
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.infiniteRepeatable
+import androidx.compose.animation.core.rememberInfiniteTransition
+import androidx.compose.animation.core.tween
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.*
+import androidx.compose.material3.Text
+import androidx.compose.runtime.*
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import com.kyant.shapes.Capsule
+import kotlin.math.sin
+import androidx.core.content.ContextCompat
+import com.codync.android.core.*
+import com.codync.android.design.*
+
+/** Starts a call with `botId`, asking for the microphone first; `denied` reports a refusal. */
+@Composable internal fun rememberStartVoice(botId: String, state: AppState, store: AppStore, denied: () -> Unit): () -> Unit {
+ val context = LocalContext.current
+ var requested by remember { mutableStateOf<Pair<String, Int>?>(null) }
+ val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
+ val owner = requested; requested = null
+ if (owner != null && store.state.value.generation == owner.second && store.state.value.selectedBot == owner.first) {
+ if (granted) store.startVoice(owner.first, owner.second) else denied()
+ }
+ }
+ return {
+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) store.startVoice(botId, state.generation)
+ else { requested = botId to state.generation; permission.launch(Manifest.permission.RECORD_AUDIO) }
+ }
+}
+
+/** Opens this app's settings, where the microphone can be allowed. */
+internal fun openAppSettings(context: android.content.Context) =
+ context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}")))
+
+/**
+ * A voice call with a bot (iOS `CallView`): a floating glass bar over the chat, which stays readable
+ * underneath. What you say goes out as ordinary messages; its final replies are read aloud.
+ */
+@Composable internal fun CallBar(call: VoiceCallViewState, state: AppState, store: AppStore) {
+ val voice = call.state
+ val bot = state.bots.firstOrNull { it.id == call.botId }
+ val color = bot?.let { AvatarPalette.tint(it.avatarColor) } ?: Palette.accent
+ var settings by remember { mutableStateOf(false) }
+ val speaking = voice.phase == VoicePhase.Speaking
+ LaunchedEffect(call.id) { Analytics.capture(AnalyticsEvent.VoiceCallStarted) }
+ Column(Modifier.padding(horizontal = 12.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Row(Modifier.fillMaxWidth().glass(Capsule()).padding(start = 14.dp, end = 7.dp, top = 7.dp, bottom = 7.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ // The bot; tapping it while it talks cuts the reply short, otherwise it opens the call's chat.
+ val pulse by rememberInfiniteTransition(label = "Speaking").animateFloat(1f, 1.1f,
+ infiniteRepeatable(tween(600), RepeatMode.Reverse), label = "Pulse")
+ Box(Modifier.graphicsLayer { val s = if (speaking) pulse else 1f; scaleX = s; scaleY = s }
+ .plainButton { if (speaking) store.interruptVoice() else if (state.selectedBot != call.botId) store.openBot(call.botId) }
+ .semantics { contentDescription = if (speaking) "Interrupt" else bot?.name.orEmpty() }) {
+ if (bot != null) BotAvatar(bot, state.bots, 34.dp)
+ }
+ CallLevelDots(voice.level, speaking, bot?.status == "working", color,
+ Modifier.weight(1f).height(20.dp).semantics { contentDescription = statusText(voice, bot?.status == "working") })
+ RoundButton("Call settings", "gearshape") { settings = true }
+ RoundButton(if (voice.muted) "Unmute" else "Mute", if (voice.muted) "mic.slash" else "mic", on = voice.muted, action = store::muteVoice)
+ Box(Modifier.size(46.dp).clip(Capsule()).background(Palette.danger).plainButton { store.endVoice() }
+ .semantics { contentDescription = "End call" }, contentAlignment = Alignment.Center) {
+ Symbol("xmark", size = 18.dp, tint = Color.White)
+ }
+ }
+ val failure = voice.error ?: if (voice.phase == VoicePhase.Failed) "Voice audio unavailable" else null
+ when {
+ failure != null -> CallLine(failure, Palette.danger)
+ voice.phase == VoicePhase.Interrupted -> CallLine("Audio paused by another app. Tap to resume.", Palette.secondary, store::resumeVoice)
+ }
+ }
+ CodyncSheet(settings, { settings = false }) { VoiceChatSettings(store) }
+}
+
+@Composable private fun CallLine(text: String, color: Color, action: (() -> Unit)? = null) {
+ Text(text, Modifier.glass(Capsule()).then(if (action != null) Modifier.plainButton(action = action) else Modifier)
+ .padding(horizontal = 12.dp, vertical = 8.dp), style = Type.footnote, color = color, textAlign = TextAlign.Center)
+}
+
+@Composable private fun RoundButton(label: String, systemImage: String, on: Boolean = false, action: () -> Unit) {
+ Box(Modifier.size(46.dp).clip(Capsule()).background(if (on) Palette.accentFill else Palette.background).plainButton(action = action)
+ .semantics { contentDescription = label }, contentAlignment = Alignment.Center) {
+ Symbol(systemImage, size = 20.dp, tint = if (on) Palette.onAccent else Palette.text)
+ }
+}
+
+private fun statusText(voice: VoiceState, working: Boolean) = when (voice.phase) {
+ VoicePhase.Starting -> "Connecting"
+ VoicePhase.Speaking -> "Speaking"
+ VoicePhase.Failed -> "Can't listen"
+ VoicePhase.Interrupted -> "Paused"
+ VoicePhase.Ended -> "Ending"
+ VoicePhase.Listening -> if (voice.muted) "Muted" else if (working) "Working, listening" else "Listening"
+}
+
+/**
+ * The dotted line in the call bar: it follows your voice while listening, ripples while the bot
+ * talks, breathes while it works, and rests as faint dots otherwise.
+ */
+@Composable private fun CallLevelDots(level: Float, speaking: Boolean, working: Boolean, color: Color, modifier: Modifier) {
+ val still = reduceMotion()
+ var time by remember { mutableFloatStateOf(0f) }
+ if (!still) LaunchedEffect(Unit) { while (true) withFrameNanos { time = it / 1e9f } }
+ val accent = Palette.accent
+ Canvas(modifier) {
+ val spacing = 8.dp.toPx()
+ val width = 2.5.dp.toPx()
+ val count = maxOf(1, (size.width / spacing).toInt())
+ for (i in 0 until count) {
+ val wave = (sin(i * 0.55f - time * 6f) + 1) / 2
+ val amount = when {
+ speaking -> 0.5f + 0.5f * wave
+ level > 0.05f -> maxOf(0.2f, level) * (0.45f + 0.55f * wave)
+ working -> 0.25f * ((sin(time * 2.4f) + 1) / 2)
+ else -> 0.08f
+ }
+ val height = 4.dp.toPx() + amount * (size.height - 4.dp.toPx())
+ drawRoundRect((if (speaking) accent else color).copy(alpha = 0.5f + 0.5f * amount),
+ Offset(i * spacing + spacing / 2 - width / 2, (size.height - height) / 2), Size(width, height), CornerRadius(width / 2))
+ }
+ }
+}
+
+/** Voice chat settings (iOS `VoiceChatSettingsView`): Android speech on this phone, its pause and reading speed. */
+@Composable internal fun VoiceChatSettings(store: AppStore) {
+ val context = LocalContext.current
+ var settings by remember { mutableStateOf(VoicePreferences.load(context)) }
+ fun change(next: VoiceSettings) { settings = next; store.voiceSettings(next) }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader("Voice chat")
+ CardForm {
+ CardSection("Voice", footer = "Android speech, on this phone. Only the text reaches the computer.") {
+ row { ValueRow("Engine", "On device") }
+ row {
+ ValueRow("Reading speed") {
+ ChoicePicker(settings.rate, listOf(.84f to "Slower", 1f to "Normal", 1.12f to "Faster"), { change(settings.copy(rate = it)) },
+ label = "Reading speed")
+ }
+ }
+ row {
+ ValueRow("Send after a pause of", detail = "Longer leaves time to think mid-sentence.") {
+ ChoicePicker(settings.pauseMillis, listOf(1_000L to "1 s", 1_500L to "1.5 s", 2_500L to "2.5 s"),
+ { change(settings.copy(pauseMillis = it)) }, label = "Send after a pause of")
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/VoiceService.kt b/apps/android/app/src/main/kotlin/com/codync/android/VoiceService.kt
new file mode 100644
index 00000000..210931d8
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/VoiceService.kt
@@ -0,0 +1,205 @@
+package com.codync.android
+
+import android.Manifest
+import android.app.*
+import android.content.*
+import android.content.pm.PackageManager
+import android.content.pm.ServiceInfo
+import android.media.*
+import android.net.Uri
+import android.os.*
+import androidx.core.app.NotificationCompat
+import androidx.core.content.ContextCompat
+import com.codync.android.core.*
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.collectLatest
+
+data class VoiceCallViewState(val id: String, val botId: String, val state: VoiceState = VoiceState())
+
+/** Started only by the visible call UI. Audio is retained in background, never restarted by Android. */
+class VoiceService : Service() {
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+ private var store: AppStore? = null
+ private var session: VoiceSession? = null
+ private var audio: LocalVoiceAudio? = null
+ private var callId: String? = null
+ private var focus: AudioFocusRequest? = null
+ private lateinit var manager: AudioManager
+ private var previousMode: Int? = null
+ private var previousDevice: AudioDeviceInfo? = null
+ private var selectedDevice: AudioDeviceInfo? = null
+ private var previousSpeaker = false
+ private var startedSco = false
+ private var receivers = false
+ private var ending = false
+ private val noisy = object : BroadcastReceiver() {
+ override fun onReceive(context: Context?, intent: Intent?) { session?.focus(false) }
+ }
+ private val devices = object : AudioDeviceCallback() {
+ override fun onAudioDevicesAdded(addedDevices: Array<out AudioDeviceInfo>) { chooseRoute() }
+ override fun onAudioDevicesRemoved(removedDevices: Array<out AudioDeviceInfo>) {
+ if (removedDevices.any { it.id == selectedDevice?.id && it.type != AudioDeviceInfo.TYPE_BUILTIN_SPEAKER }) session?.focus(false)
+ chooseRoute()
+ }
+ }
+ private val recording = object : AudioManager.AudioRecordingCallback() {
+ override fun onRecordingConfigChanged(configs: MutableList<AudioRecordingConfiguration>?) {
+ val id = audio?.recordingSessionId ?: return
+ if (configs.orEmpty().any { it.clientAudioSessionId == id && it.isClientSilenced }) session?.focus(false)
+ }
+ }
+ override fun onCreate() {
+ super.onCreate(); manager = getSystemService(AudioManager::class.java)
+ getSystemService(NotificationManager::class.java).createNotificationChannel(
+ NotificationChannel(CHANNEL, "Voice chat", NotificationManager.IMPORTANCE_LOW))
+ }
+ override fun onBind(intent: Intent?): IBinder? = null
+ @Suppress("DEPRECATION") override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ val id = intent?.getStringExtra(ID)
+ if (intent?.action == START) {
+ val request = pending?.takeIf { it.id == id }
+ if (request == null || session != null) { if (session == null) stopSelf(startId); return START_NOT_STICKY }
+ pending = null; store = request.store; callId = request.id; currentId = request.id
+ if (request.store.state.value.voice?.id != request.id ||
+ ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
+ end("Allow microphone access before starting voice chat."); return START_NOT_STICKY
+ }
+ try {
+ startForeground(NOTIFICATION, notification(request.store.state.value.voice!!.state),
+ ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE or ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK)
+ val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
+ .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build()
+ val ownedFocus = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN).setAudioAttributes(attributes)
+ .setOnAudioFocusChangeListener({ change ->
+ when (change) {
+ AudioManager.AUDIOFOCUS_GAIN -> session?.focus(true)
+ AudioManager.AUDIOFOCUS_LOSS -> end("Voice chat ended because another app took audio focus.")
+ else -> session?.focus(false)
+ }
+ }, Handler(Looper.getMainLooper())).build()
+ focus = ownedFocus
+ check(manager.requestAudioFocus(ownedFocus) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
+ previousMode = manager.mode
+ previousSpeaker = manager.isSpeakerphoneOn
+ if (Build.VERSION.SDK_INT >= 31) previousDevice = manager.communicationDevice
+ manager.mode = AudioManager.MODE_IN_COMMUNICATION
+ chooseRoute()
+ manager.registerAudioDeviceCallback(devices, Handler(Looper.getMainLooper()))
+ manager.registerAudioRecordingCallback(recording, Handler(Looper.getMainLooper()))
+ ContextCompat.registerReceiver(this, noisy, IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY), ContextCompat.RECEIVER_NOT_EXPORTED)
+ receivers = true
+ val engine = LocalVoiceAudio(applicationContext); audio = engine
+ val call = request.store.attachVoice(request.id, request.botId, engine) ?: throw IllegalStateException("The active account changed")
+ session = call
+ scope.launch { call.state.collectLatest { state ->
+ if (state.phase in listOf(VoicePhase.Failed, VoicePhase.Ended)) end(state.error)
+ else getSystemService(NotificationManager::class.java).notify(NOTIFICATION, notification(state))
+ } }
+ } catch (_: Exception) { end("Couldn't start voice chat. Check microphone access and Android's audio settings.") }
+ } else if (id == callId) {
+ when (intent?.action) { MUTE -> session?.let { it.mute(!it.state.value.muted) }; END -> end(null) }
+ } else if (session == null) stopSelf(startId)
+ return START_NOT_STICKY
+ }
+ @Suppress("DEPRECATION") private fun chooseRoute() {
+ if (previousMode == null || store?.state?.value?.voice?.id != callId) return
+ if (Build.VERSION.SDK_INT >= 31) {
+ val available = manager.availableCommunicationDevices
+ val headset = available.firstOrNull { it.type in listOf(AudioDeviceInfo.TYPE_BLUETOOTH_SCO, AudioDeviceInfo.TYPE_BLE_HEADSET) }
+ ?: available.firstOrNull { it.type in listOf(AudioDeviceInfo.TYPE_WIRED_HEADSET, AudioDeviceInfo.TYPE_USB_HEADSET) }
+ val chosen = headset ?: available.firstOrNull { it.type == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER }
+ if (chosen != null && manager.setCommunicationDevice(chosen)) selectedDevice = chosen
+ } else {
+ val available = manager.getDevices(AudioManager.GET_DEVICES_INPUTS)
+ val bluetooth = available.any { it.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO }
+ if (!bluetooth && startedSco) { manager.stopBluetoothSco(); manager.isBluetoothScoOn = false; startedSco = false }
+ if (bluetooth && !startedSco && manager.isBluetoothScoAvailableOffCall) {
+ manager.startBluetoothSco(); manager.isBluetoothScoOn = true; startedSco = true
+ }
+ manager.isSpeakerphoneOn = !bluetooth && available.none { it.type in listOf(AudioDeviceInfo.TYPE_WIRED_HEADSET, AudioDeviceInfo.TYPE_USB_HEADSET) }
+ }
+ }
+ private fun notification(state: VoiceState): Notification {
+ val snapshot = store?.state?.value
+ val call = snapshot?.voice
+ val bot = snapshot?.bots?.firstOrNull { it.id == call?.botId }
+ val url = Uri.Builder().scheme(BuildConfig.URL_SCHEME).authority("bot").appendPath(call?.botId.orEmpty())
+ .appendQueryParameter("scope", snapshot?.contextId).appendQueryParameter("computer", snapshot?.computers?.firstOrNull()?.id).build()
+ val content = PendingIntent.getActivity(this, NOTIFICATION, Intent(this, MainActivity::class.java)
+ .setAction(Intent.ACTION_VIEW).setData(url), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
+ fun action(kind: String) = PendingIntent.getService(this, kind.hashCode(), Intent(this, VoiceService::class.java)
+ .setAction(kind).putExtra(ID, callId), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
+ return NotificationCompat.Builder(this, CHANNEL).setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle("Voice chat · ${bot?.name ?: "Codync"}")
+ .setContentText(if (state.muted) "Microphone muted" else when (state.phase) {
+ VoicePhase.Starting -> "Starting offline speech…"; VoicePhase.Speaking -> "Reading a reply"
+ VoicePhase.Interrupted -> "Audio interrupted · return to resume"; else -> "Listening · offline English"
+ }).setContentIntent(content).setOngoing(true).setCategory(NotificationCompat.CATEGORY_CALL)
+ .setVisibility(NotificationCompat.VISIBILITY_PRIVATE).setOnlyAlertOnce(true)
+ .addAction(0, if (state.muted) "Unmute" else "Mute", action(MUTE)).addAction(0, "End call", action(END)).build()
+ }
+ private fun end(error: String?) {
+ if (ending) return
+ ending = true
+ val id = callId
+ if (id != null) store?.finishVoice(id, error)
+ val call = session
+ call?.end()
+ scope.launch { try { call?.awaitEnd() } finally { stopSelf() } }
+ }
+ override fun onTaskRemoved(rootIntent: Intent?) { end(null); super.onTaskRemoved(rootIntent) }
+ override fun onDestroy() {
+ val id = callId
+ if (id != null) store?.finishVoice(id)
+ val call = session
+ call?.end(); session = null; audio = null
+ if (receivers) unregisterReceiver(noisy)
+ runCatching { manager.unregisterAudioDeviceCallback(devices) }
+ runCatching { manager.unregisterAudioRecordingCallback(recording) }
+ // A UI end or account retirement can destroy this service first. Keep
+ // the route and audio focus until its recorder worker has joined.
+ scope.launch {
+ try { call?.awaitEnd() }
+ finally {
+ runCatching { releaseRoute() }
+ if (currentId == id) currentId = null
+ scope.cancel()
+ }
+ }
+ stopForeground(STOP_FOREGROUND_REMOVE); super.onDestroy()
+ }
+ @Suppress("DEPRECATION") private fun releaseRoute() {
+ focus?.let { manager.abandonAudioFocusRequest(it) }; focus = null
+ if (previousMode != null && manager.mode == AudioManager.MODE_IN_COMMUNICATION) {
+ if (Build.VERSION.SDK_INT >= 31) {
+ if (manager.communicationDevice?.id == selectedDevice?.id) {
+ val previous = previousDevice
+ if (previous != null && manager.availableCommunicationDevices.any { it.id == previous.id }) manager.setCommunicationDevice(previous)
+ else manager.clearCommunicationDevice()
+ }
+ } else { if (startedSco) { manager.stopBluetoothSco(); manager.isBluetoothScoOn = false }; manager.isSpeakerphoneOn = previousSpeaker }
+ manager.mode = requireNotNull(previousMode)
+ }
+ }
+ companion object {
+ private data class Request(val id: String, val botId: String, val store: AppStore)
+ private var pending: Request? = null
+ private var currentId: String? = null
+ private const val ID = "codync:voice"
+ private const val START = "com.codync.android.voice.START"
+ private const val MUTE = "com.codync.android.voice.MUTE"
+ private const val END = "com.codync.android.voice.END"
+ private const val CHANNEL = "codync-voice"
+ private const val NOTIFICATION = 308
+ internal fun start(context: Context, store: AppStore, id: String, botId: String) {
+ check(pending == null && currentId == null); pending = Request(id, botId, store)
+ try { ContextCompat.startForegroundService(context, Intent(context, VoiceService::class.java).setAction(START).putExtra(ID, id)) }
+ catch (error: Exception) { pending = null; throw error }
+ }
+ internal fun stop(context: Context, id: String) {
+ if (pending?.id != id && currentId != id) return
+ if (pending?.id == id) pending = null
+ context.stopService(Intent(context, VoiceService::class.java))
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt b/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt
new file mode 100644
index 00000000..026160c7
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt
@@ -0,0 +1,203 @@
+package com.codync.android
+
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.core.Animatable
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.scaleIn
+import androidx.compose.animation.togetherWith
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.safeDrawingPadding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.withFrameNanos
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.TransformOrigin
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.LocalUriHandler
+import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.coroutines.delay
+import kotlin.math.sin
+
+/** First launch, before any setup: who the bots are, a glimpse of talking to one, one way forward (iOS `WelcomeView`). */
+@Composable internal fun WelcomeView(state: AppState, store: AppStore, start: () -> Unit) {
+ val still = reduceMotion()
+ // 0 = nothing yet … 4 = everything shown. Each beat enters in turn.
+ var beat by remember { mutableIntStateOf(if (still) 4 else 0) }
+ LaunchedEffect(Unit) {
+ for (next in beat + 1..4) { delay(if (next == 1) 150 else 280); beat = next }
+ }
+ BoxWithConstraints(Modifier.fillMaxSize().background(Palette.background).safeDrawingPadding()) {
+ val height = maxHeight
+ Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {
+ // Three flexible gaps as the iOS spacers: above the crew, under it, and over the buttons.
+ Column(Modifier.fillMaxWidth().heightIn(min = height).padding(horizontal = 24.dp).padding(bottom = 12.dp),
+ verticalArrangement = Arrangement.SpaceBetween) {
+ Spacer(Modifier.height(0.dp))
+ Crew(beat >= 1, Modifier.padding(top = 24.dp))
+ Column(Modifier.padding(top = 24.dp)) {
+ ChatGlimpse(beat >= 2, Modifier.padding(bottom = 24.dp))
+ Column(Modifier.rise(beat >= 3), verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text("Your coding agents,\nas teammates.", style = Type.system(34f, FontWeight.SemiBold).copy(letterSpacing = (-0.6).sp),
+ color = Palette.text)
+ Text("Give each one a name and a project. They work on your computer while you're away.", style = Type.body, color = Palette.secondary)
+ DemoButton(Modifier.padding(top = 4.dp))
+ }
+ }
+ Column(Modifier.padding(top = 32.dp).rise(beat >= 4), verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ WideButton("Get started", action = start)
+ // Signed in, the computers on the account show up without scanning a code.
+ if (state.account.configured) SignInButtons(state, store)
+ state.account.error?.let { Text(it, style = Type.footnote, color = Palette.danger) }
+ }
+ }
+ }
+ }
+}
+
+/** Five bots bobbing out of step: the "persistent, named" part of the pitch, without words. */
+@Composable private fun Crew(shown: Boolean, modifier: Modifier = Modifier) {
+ val still = reduceMotion()
+ var time by remember { mutableFloatStateOf(0f) }
+ if (shown && !still) LaunchedEffect(Unit) { while (true) withFrameNanos { time = it / 1e9f } }
+ val density = LocalDensity.current
+ Box(modifier.fillMaxWidth().height(170.dp), contentAlignment = Alignment.Center) {
+ for ((index, member) in CREW.withIndex()) {
+ val entry = remember { Animatable(if (still) 1f else 0f) }
+ LaunchedEffect(shown) {
+ if (shown) { delay(index * 70L); entry.animateTo(1f, Motion.spring(0.7f, 0.4f)) } else entry.snapTo(0f)
+ }
+ Box(Modifier.graphicsLayer {
+ val bob = if (still) 0f else sin(time * 1.3f + index * 1.7f) * 5f
+ translationX = with(density) { member.x.dp.toPx() }
+ translationY = with(density) { (member.y + bob).dp.toPx() }
+ val scale = 0.3f + 0.7f * entry.value
+ scaleX = scale; scaleY = scale; alpha = entry.value.coerceIn(0f, 1f)
+ }) { CharacterAvatar(member.shape, member.color, member.size.dp, member.mood) }
+ }
+ }
+}
+
+private class CrewMember(val shape: String, val color: String, val size: Int, val x: Float, val y: Float, val mood: String)
+
+private val CREW = listOf(
+ CrewMember("blob", "blue", 92, 0f, 0f, "working"),
+ CrewMember("squircle", "orange", 64, -104f, -34f, "idle"),
+ CrewMember("teardrop", "violet", 58, 100f, -46f, "working"),
+ CrewMember("hex", "green", 48, -76f, 64f, "idle"),
+ CrewMember("cloud", "magenta", 52, 84f, 58f, "needsInput"),
+)
+
+/** One exchange, played once: you ask, a bot works, a bot answers. */
+@Composable private fun ChatGlimpse(shown: Boolean, modifier: Modifier = Modifier) {
+ val still = reduceMotion()
+ var replied by remember { mutableStateOf(false) }
+ LaunchedEffect(shown) { if (shown) { delay(if (still) 0 else 1600); replied = true } }
+ Column(modifier.fillMaxWidth().semantics(mergeDescendants = true) {}, verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Box(Modifier.fillMaxWidth().rise(shown), contentAlignment = Alignment.CenterEnd) { Bubble("Fix the flaky login test", Palette.bubbleUser) }
+ Row(Modifier.rise(shown), verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ CharacterAvatar("blob", "blue", 28.dp, if (replied) "idle" else "working")
+ AnimatedContent(replied, transitionSpec = {
+ (fadeIn(Motion.spring(0.45f, 0.2f)) + scaleIn(Motion.spring(0.45f, 0.2f), 0.92f, TransformOrigin(0f, 1f))) togetherWith
+ fadeOut(Motion.fade())
+ }, label = "Reply") { done ->
+ if (done) Bubble("Done. It raced the session refresh; tests pass on fix/login.", Palette.bubbleAgent)
+ else Text("Working…", style = Type.subheadline, color = Palette.tertiary)
+ }
+ }
+ }
+}
+
+@Composable private fun Bubble(text: String, fill: Color) =
+ Text(text, Modifier.clip(RoundedRectangle(18.dp)).background(fill).padding(horizontal = 14.dp, vertical = 9.dp),
+ style = Type.subheadline, color = Palette.text)
+
+/** Opens a short recording of the app in use on YouTube, for anyone who can't pair a computer yet. */
+@Composable internal fun DemoButton(modifier: Modifier = Modifier) {
+ val uri = LocalUriHandler.current
+ Row(modifier.plainButton { uri.openUri("https://youtube.com/shorts/xtZ5WeyOewU") }, verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Symbol("play.circle.fill", size = 17.dp, tint = Palette.text)
+ Text("Watch the demo", style = Type.subheadline.medium, color = Palette.text)
+ }
+}
+
+/** Equal access to both account providers at every sign-in entry point (iOS `SignInButtons`). */
+@Composable internal fun SignInButtons(state: AppState, store: AppStore) {
+ val busy = "session" in state.busy
+ val enabled = state.account.ready && !busy
+ Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ WideButton(enabled = enabled, busy = busy, action = { store.signIn(apple = true) }) {
+ Symbol("apple.logo", size = 20.dp, tint = Palette.onAccent)
+ Text("Continue with Apple")
+ }
+ WideButton(primary = false, enabled = enabled, busy = busy, action = { store.signIn(apple = false) }) {
+ Image(painterResource(R.drawable.google_logo), null, Modifier.size(20.dp))
+ Text("Continue with Google")
+ }
+ // Clerk's own page covers the sign-ins that need another step (email codes, verification).
+ LinkButton("Other sign-in options", enabled = enabled, color = Palette.secondary, style = Type.footnote) { store.signIn(hosted = true) }
+ }
+}
+
+/** The full-width 50-point button of the onboarding pages: headline label, a spinner while busy. */
+@Composable internal fun WideButton(title: String, primary: Boolean = true, enabled: Boolean = true, action: () -> Unit) =
+ WideButton(primary, enabled, action = action) { Text(title) }
+
+@Composable internal fun WideButton(primary: Boolean = true, enabled: Boolean = true, busy: Boolean = false, action: () -> Unit,
+ label: @Composable () -> Unit) {
+ val content: @Composable () -> Unit = {
+ Box(Modifier.fillMaxWidth().heightIn(min = WIDE_HEIGHT), contentAlignment = Alignment.Center) {
+ Row(Modifier.graphicsLayer { alpha = if (busy) 0f else 1f }, verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ androidx.compose.runtime.CompositionLocalProvider(androidx.compose.material3.LocalTextStyle provides Type.headline) { label() }
+ }
+ if (busy) Spinner(18.dp)
+ }
+ }
+ if (primary) PrimaryButton(action, Modifier.fillMaxWidth(), enabled, content) else SecondaryButton(action, Modifier.fillMaxWidth(), enabled, content)
+}
+
+// The label's own 50-point frame, inside the style's 11-point vertical padding (72 in all, as on iOS).
+private val WIDE_HEIGHT: Dp = 50.dp
+
+/** Fades up into place once `shown`. */
+@Composable private fun Modifier.rise(shown: Boolean): Modifier {
+ val progress by animateFloatAsState(if (shown) 1f else 0f, Motion.spring(0.6f, 0.25f), label = "Rise")
+ val lift = with(LocalDensity.current) { 14.dp.toPx() }
+ return graphicsLayer { alpha = progress.coerceIn(0f, 1f); translationY = (1f - progress) * lift }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt b/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt
new file mode 100644
index 00000000..7aa6dd8c
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt
@@ -0,0 +1,262 @@
+package com.codync.android
+
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.UsageProvider
+import com.codync.android.core.UsageReport
+import com.codync.android.core.UsageWindow
+import com.codync.android.core.WidgetBot
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import kotlin.math.roundToInt
+
+// The iOS widget cards (CodyncKit `WidgetCards.swift`), for the State gallery's previews.
+// The Home Screen widgets draw the same layouts with Glance.
+
+enum class ProviderLayout { Small, Medium, Large }
+
+/** Claude keeps its orange; everyone else is ink, like the rest of the app. */
+/** ACP registry id of the provider's agent, for its logo: Claude and Codex run through ACP adapters. */
+internal val UsageProvider.registry: String get() = if (id in listOf("claude", "codex")) "$id-acp" else id
+
+@Composable internal fun UsageProvider.tint(): Color = if (id == "claude") Color(0xFFD97757) else Palette.accent
+
+/** Gauges add Codex's blue so two providers' bars tell apart (CodyncKit `widgetTint`). */
+@Composable internal fun UsageProvider.widgetTint(): Color =
+ if (id == "codex") (if (LocalDark.current) Color(0xFF70ACDC) else Color(0xFF326FAD)) else tint()
+
+/** "Session" for the 5-hour window, "Opus" for "Weekly · Opus", else the label. */
+internal val UsageWindow.title: String get() = when {
+ label == "5-hour" -> "Session"
+ " · " in label -> label.substringAfter(" · ")
+ else -> label
+}
+
+/** "resets 3h 20m" / "resets Sep 26 at 12pm", compact for widgets and cards (CodyncKit `resetsShort`). */
+internal fun UsageWindow.resetsShort(now: Long = System.currentTimeMillis()): String? {
+ resetDate(now)?.let { at -> return if (at > now) "resets " + until(at, now) else null }
+ return resetsText?.takeIf(String::isNotBlank)?.let { "resets " + it.replace(Regex(" \\(.*\\)$"), "") }
+}
+
+/** Time left: 2d · 3h 20m · 45m (CodyncKit `RelativeTime.until`). */
+internal fun until(at: Long, now: Long): String {
+ val minutes = maxOf(0L, at - now) / 60_000
+ val hours = minutes / 60
+ return when { hours >= 48 -> "${hours / 24}d"; hours > 0 -> "${hours}h ${minutes % 60}m"; else -> "${minutes}m" }
+}
+
+/** A provider's character, with a red "!" once any of its limits is nearly used up. */
+@Composable internal fun ProviderMascot(provider: UsageProvider, size: Dp) {
+ val full = (provider.tightest?.percent ?: 0.0) >= 90
+ val context = androidx.compose.ui.platform.LocalContext.current
+ val revision by WidgetStore.changes.collectAsState()
+ val original = remember(revision) { WidgetStore.originalIcons(context) }
+ val logo = agentIconRes(provider.registry)
+ Box(Modifier.size(size)) {
+ if (original && logo != null) androidx.compose.foundation.Image(androidx.compose.ui.res.painterResource(logo), null,
+ Modifier.fillMaxSize().padding(size * 0.08f), colorFilter = androidx.compose.ui.graphics.ColorFilter.tint(provider.tint()))
+ else CharacterAvatar(if (provider.id == "codex") "hex" else "blob", "gray", size, if (full) "needsInput" else "idle", highlight = provider.tint())
+ if (full) Box(Modifier.align(Alignment.TopEnd).offset(x = size * 0.12f, y = -size * 0.12f).size(size * 0.34f).clip(Capsule())
+ .background(Palette.danger), contentAlignment = Alignment.Center) {
+ Text("!", style = Type.system(size.value * 0.24f, FontWeight.Black), color = Color.White)
+ }
+ }
+}
+
+/** Fine, separated ticks keep low and high usage legible without a heavy gauge. */
+@Composable internal fun UsageTicks(percent: Double, tint: Color, height: Dp) {
+ val value = if (percent.isFinite()) percent.coerceIn(0.0, 100.0) else 0.0
+ val color = if (value >= 90) Palette.danger else tint
+ Canvas(Modifier.fillMaxWidth().height(height)) {
+ val gap = 1.5.dp.toPx()
+ val count = maxOf(1, (size.width / 4.dp.toPx()).toInt())
+ val filled = (count * value / 100).roundToInt()
+ val width = (size.width - gap * (count - 1)) / count
+ for (i in 0 until count) drawRoundRect(if (i < filled) color else color.copy(alpha = 0.16f), Offset(i * (width + gap), 0f),
+ Size(width, size.height), CornerRadius(1.dp.toPx()))
+ }
+}
+
+/** One provider's limits: the tightest in a small widget, two windows in medium, four and a summary in large. */
+@Composable internal fun ProviderWidgetCard(provider: UsageProvider, layout: ProviderLayout) {
+ val tint = provider.widgetTint()
+ Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(if (layout == ProviderLayout.Small) 6.dp else 8.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) {
+ ProviderMascot(provider, 22.dp)
+ Text(provider.name, Modifier.weight(1f), style = Type.system(13f).semibold, color = Palette.text, maxLines = 1)
+ if (layout != ProviderLayout.Small) Text("Usage", style = Type.system(10f).medium, color = Palette.secondary)
+ }
+ val top = provider.tightest
+ if (layout == ProviderLayout.Small && top != null) {
+ Spacer(Modifier.weight(1f))
+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(top.title, style = Type.system(11f), color = Palette.secondary, maxLines = 1)
+ Row(verticalAlignment = Alignment.Bottom) {
+ val ink = if ((top.percent ?: 0.0) >= 90) Palette.danger else Palette.text
+ Text("${(top.percent ?: 0.0).roundToInt()}", style = Type.system(32f).semibold.monospacedDigit, color = ink)
+ Text("%", Modifier.padding(bottom = 4.dp), style = Type.system(17f).medium, color = ink)
+ }
+ }
+ UsageTicks(top.percent ?: 0.0, tint, 13.dp)
+ Text(top.resetsShort() ?: "Usage reported by your computer", style = Type.system(9f), color = Palette.secondary, maxLines = 1)
+ } else {
+ if (layout == ProviderLayout.Large && top != null) Row(Modifier.padding(vertical = 4.dp), verticalAlignment = Alignment.Bottom,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text("${(top.percent ?: 0.0).roundToInt()}%", style = Type.system(36f).semibold.monospacedDigit,
+ color = if ((top.percent ?: 0.0) >= 90) Palette.danger else Palette.text)
+ Text("${top.title} · highest usage", Modifier.padding(bottom = 6.dp), style = Type.system(11f), color = Palette.secondary, maxLines = 2)
+ }
+ for (window in provider.windows.take(if (layout == ProviderLayout.Large) 4 else 2)) {
+ Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(window.title, Modifier.weight(1f), style = Type.system(11f).medium, color = Palette.secondary, maxLines = 1)
+ Text("${(window.percent ?: 0.0).roundToInt()}%", style = Type.system(13f).semibold.monospacedDigit,
+ color = if ((window.percent ?: 0.0) >= 90) Palette.danger else Palette.text)
+ }
+ UsageTicks(window.percent ?: 0.0, tint, 12.dp)
+ window.resetsShort()?.let { Text(it, Modifier.fillMaxWidth(), style = Type.system(9f), color = Palette.secondary,
+ maxLines = 1, textAlign = TextAlign.End) }
+ }
+ }
+ }
+ }
+}
+
+/** The state word the widgets show and its color: only what needs you (or failed) stands out. */
+@Composable internal fun widgetState(status: String): Pair<String, Color> = when (status) {
+ "needsInput" -> "Needs you" to Palette.attention
+ "error" -> "Failed" to Palette.danger
+ "working" -> "Working" to Palette.text
+ else -> "Ready" to Palette.secondary
+}
+
+private fun rank(bot: WidgetBot) = when (bot.status) { "needsInput" -> 0; "working" -> 1; else -> 2 }
+
+/** Who needs you and who's still working: a count, then the bots in that order. */
+@Composable internal fun BotsWidgetCard(bots: List<WidgetBot>, activities: Map<String, String>, wide: Boolean, large: Boolean) {
+ val ordered = bots.sortedBy(::rank)
+ val needs = bots.count { it.status == "needsInput" }
+ val working = bots.count { it.status == "working" }
+ val count = if (needs > 0) needs else if (working > 0) working else bots.size
+ val label = if (needs > 0) (if (needs == 1) "Needs you" else "Need you") else if (working > 0) "Working" else if (bots.isEmpty()) "No bots yet" else "All quiet"
+ val summary: @Composable () -> Unit = {
+ Column(verticalArrangement = Arrangement.spacedBy(1.dp)) {
+ Text("$count", style = Type.system(36f).semibold.monospacedDigit, color = if (needs > 0) Palette.attention else Palette.text)
+ Text(label, style = Type.system(12f).medium, color = Palette.secondary)
+ }
+ }
+ Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text("Bots", Modifier.weight(1f), style = Type.system(13f).semibold, color = Palette.text)
+ Symbol("bubble.left.and.bubble.right", size = 15.dp, tint = Palette.secondary)
+ }
+ when {
+ large -> {
+ Row(verticalAlignment = Alignment.Bottom) {
+ Box(Modifier.weight(1f)) { summary() }
+ Text("${bots.size} total · $working working", style = Type.system(11f), color = Palette.secondary)
+ }
+ Hairline()
+ BotRows(ordered.take(6), activities)
+ }
+ wide -> Row(Modifier.fillMaxHeight(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp)) {
+ Box(Modifier.width(76.dp)) { summary() }
+ Box(Modifier.width(1.dp).fillMaxHeight().background(Palette.border))
+ Box(Modifier.weight(1f)) { BotRows(ordered.take(3), activities) }
+ }
+ else -> {
+ Spacer(Modifier.weight(1f))
+ summary()
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Row(horizontalArrangement = Arrangement.spacedBy((-4).dp)) {
+ for (bot in ordered.take(3)) CharacterAvatar(bot.avatarShape, bot.avatarColor, 23.dp)
+ }
+ Spacer(Modifier.weight(1f))
+ if (working > 0 && needs > 0) Text("$working working", style = Type.system(9f), color = Palette.secondary)
+ }
+ }
+ }
+ }
+}
+
+@Composable private fun BotRows(bots: List<WidgetBot>, activities: Map<String, String>) {
+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ for (bot in bots) {
+ val (label, tint) = widgetState(bot.status)
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) {
+ CharacterAvatar(bot.avatarShape, bot.avatarColor, 24.dp)
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(1.dp)) {
+ Text(bot.name, style = Type.system(11f).semibold, color = Palette.text, maxLines = 1)
+ activities[bot.id]?.takeIf { bot.status == "working" || bot.status == "needsInput" }?.let {
+ Text(it, style = Type.system(10f), color = Palette.secondary, maxLines = 1)
+ }
+ }
+ Text(label, style = Type.system(10f, if (bot.status == "needsInput") FontWeight.SemiBold else FontWeight.Normal), color = tint, maxLines = 1)
+ }
+ }
+ if (bots.isEmpty()) Text("Create your first bot in Codync.", style = Type.system(12f), color = Palette.secondary)
+ }
+}
+
+/** Four bots in a 2×2 grid, each in its mood with a dot for its state; empty spots sleep. */
+@Composable internal fun BotsTeamCard(slots: List<WidgetBot?>) {
+ Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ for (row in slots.chunked(2)) Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ for (bot in row) Box(Modifier.weight(1f).fillMaxHeight().clip(RoundedRectangle(16.dp))
+ .background(if (bot == null) Palette.bubbleAgent.copy(alpha = 0.5f) else Palette.bubbleAgent), contentAlignment = Alignment.Center) {
+ if (bot == null) Box(Modifier.size(26.dp)) { CharacterAvatar("blob", "gray", 26.dp, monochrome = Palette.text.copy(alpha = 0.18f)) }
+ else {
+ Column(Modifier.padding(horizontal = 4.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ CharacterAvatar(bot.avatarShape, bot.avatarColor, 30.dp, bot.status)
+ Text(bot.name, style = Type.system(9f).semibold, color = Palette.text, maxLines = 1)
+ }
+ if (bot.status == "working" || bot.status == "error") Box(Modifier.align(Alignment.TopEnd).padding(7.dp).size(7.dp)
+ .clip(Capsule()).background(widgetState(bot.status).second))
+ }
+ }
+ }
+ }
+}
+
+/** Illustrative data only, for previews labelled as samples (the iOS gallery's). */
+internal object WidgetPreview {
+ val bots = listOf(WidgetBot("preview-review", "Reviewer", "needsInput", avatarColor = "green", avatarShape = "blob"),
+ WidgetBot("preview-build", "Builder", "working", avatarColor = "orange", avatarShape = "squircle"),
+ WidgetBot("preview-docs", "Docs", "idle", avatarColor = "gray", avatarShape = "hex"))
+ val activities = mapOf("preview-review" to "Review changes", "preview-build" to "Running tests")
+ val usage = UsageReport(listOf(
+ UsageProvider("claude", "Claude", listOf(UsageWindow("five_hour", "5-hour", 16.0, resetsText = "3h 20m"),
+ UsageWindow("seven_day", "Weekly", 59.0, resetsText = "2d 6h")), source = "claude"),
+ UsageProvider("codex", "Codex", listOf(UsageWindow("primary", "5-hour", 8.0, resetsText = "2h 10m"),
+ UsageWindow("secondary", "Weekly", 27.0, resetsText = "4d 2h")), source = "sessions")))
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WidgetConfigurationActivity.kt b/apps/android/app/src/main/kotlin/com/codync/android/WidgetConfigurationActivity.kt
new file mode 100644
index 00000000..cd427807
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetConfigurationActivity.kt
@@ -0,0 +1,114 @@
+package com.codync.android
+
+import android.appwidget.AppWidgetManager
+import android.content.ComponentName
+import android.content.Intent
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.activity.enableEdgeToEdge
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.safeDrawingPadding
+import androidx.compose.foundation.layout.width
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.unit.dp
+import androidx.glance.appwidget.GlanceAppWidget
+import androidx.glance.appwidget.GlanceAppWidgetManager
+import androidx.lifecycle.lifecycleScope
+import com.codync.android.core.WidgetFeed
+import com.codync.android.core.WidgetKind
+import com.codync.android.core.teamSlots
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.coroutines.launch
+
+/**
+ * The launcher's Edit widget page (iOS Edit Widget): the provider a usage widget follows, or who
+ * sits in each spot of the Team widget. It follows the account selected in Codync.
+ */
+class WidgetConfigurationActivity : ComponentActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ val id = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)
+ val result = Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
+ setResult(RESULT_CANCELED, result)
+ val kind = when (AppWidgetManager.getInstance(this).getAppWidgetInfo(id)?.provider) {
+ ComponentName(this, ProviderWidgetReceiver::class.java) -> WidgetKind.Provider
+ ComponentName(this, TeamWidgetReceiver::class.java) -> WidgetKind.Team
+ else -> { finish(); return }
+ }
+ enableEdgeToEdge()
+ setContent {
+ CodyncTheme {
+ OverlayRoot {
+ val revision by WidgetStore.changes.collectAsState()
+ val feed = remember(revision) { WidgetStore.feed(this) }
+ var busy by remember { mutableStateOf(false) }
+ var error by remember { mutableStateOf<String?>(null) }
+ var provider by rememberSaveable { mutableStateOf(WidgetStore.provider(this, id)) }
+ var team by rememberSaveable { mutableStateOf(WidgetStore.team(this, id)) }
+ Column(Modifier.fillMaxSize().background(Palette.background).safeDrawingPadding()) {
+ ScreenHeader({ IconButton("Cancel", "xmark") { finish() } },
+ { Text(if (kind == WidgetKind.Team) "Team" else "Provider usage", style = Type.body.semibold, color = Palette.text) })
+ CardForm(Modifier.weight(1f)) {
+ Preview(feed, kind, provider, team)
+ CardSection(footer = if (kind == WidgetKind.Team) "Empty spots show the bots that need you first." else "Follows the account selected in Codync.") {
+ row { ValueRow("Computer", feed.computerName.ifBlank { "No computer yet" }) }
+ if (kind == WidgetKind.Provider) row {
+ val choices = (feed.usage.providers.map { it.id to it.name } + listOf("claude" to "Claude", "codex" to "Codex")).distinctBy { it.first }
+ ValueRow("Provider") { ChoicePicker(provider, choices, { provider = it }, label = "Provider") }
+ } else for ((spot, label) in listOf("Top left", "Top right", "Bottom left", "Bottom right").withIndex()) row {
+ val choices = listOf("" to "Automatic") + feed.bots.map { it.id to it.name }
+ ValueRow(label) {
+ ChoicePicker(team[spot].orEmpty(), choices, { pick -> team = team.toMutableList().also { it[spot] = pick.ifEmpty { null } } },
+ label = label)
+ }
+ }
+ }
+ error?.let { Text(it, style = Type.footnote, color = Palette.danger) }
+ PrimaryButton(if (busy) "Saving…" else "Save widget", Modifier.fillMaxWidth(), enabled = !busy) {
+ busy = true
+ lifecycleScope.launch {
+ try {
+ if (kind == WidgetKind.Team) WidgetStore.selectTeam(this@WidgetConfigurationActivity, id, team)
+ else WidgetStore.selectProvider(this@WidgetConfigurationActivity, id, provider)
+ val glance: GlanceAppWidget = if (kind == WidgetKind.Team) TeamWidget() else ProviderWidget()
+ glance.update(this@WidgetConfigurationActivity, GlanceAppWidgetManager(this@WidgetConfigurationActivity).getGlanceIdBy(id))
+ setResult(RESULT_OK, result); finish()
+ } catch (_: Exception) { error = "Couldn't update the widget. Try again."; busy = false }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/** The widget as it will look, on the latest report. */
+@Composable private fun Preview(feed: WidgetFeed, kind: WidgetKind, provider: String, team: List<String?>) {
+ Box(Modifier.fillMaxWidth().clip(RoundedRectangle(26.dp)).background(Palette.bubbleAgent).padding(14.dp), contentAlignment = Alignment.Center) {
+ Box(Modifier.width(if (kind == WidgetKind.Team) 158.dp else 320.dp).height(158.dp).clip(RoundedRectangle(22.dp)).background(Palette.surface).padding(14.dp)) {
+ if (kind == WidgetKind.Team) BotsTeamCard(teamSlots(feed.bots, team))
+ else feed.usage.providers.firstOrNull { it.id == provider }?.let { ProviderWidgetCard(it, ProviderLayout.Medium) }
+ ?: Text("No usage yet. Open Codync to refresh.", style = Type.footnote, color = Palette.secondary)
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WidgetRefreshWorker.kt b/apps/android/app/src/main/kotlin/com/codync/android/WidgetRefreshWorker.kt
new file mode 100644
index 00000000..06a4daee
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetRefreshWorker.kt
@@ -0,0 +1,62 @@
+package com.codync.android
+
+import android.content.Context
+import androidx.work.*
+import com.codync.android.core.*
+import java.util.concurrent.TimeUnit
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.withTimeout
+import kotlinx.coroutines.TimeoutCancellationException
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.serialization.json.*
+
+/** Bounded, short-lived host queries. System scheduling can delay every refresh. */
+class WidgetRefreshWorker(context: Context, parameters: WorkerParameters) : CoroutineWorker(context, parameters) {
+ override suspend fun doWork(): Result {
+ try {
+ refresh(applicationContext)
+ CodyncWidgets.update(applicationContext)
+ return Result.success()
+ } catch (_: TimeoutCancellationException) { return if (runAttemptCount < 2) Result.retry() else Result.failure() }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) { return if (runAttemptCount < 2) Result.retry() else Result.failure() }
+ }
+ companion object {
+ private const val NAME = "codync-widget-refresh"
+ private val gate = Mutex()
+ internal suspend fun refresh(context: Context): Boolean = gate.withLock {
+ val owner = WidgetStore.owner(context) ?: return@withLock false
+ val revision = WidgetStore.changes.value
+ withTimeout(30_000) {
+ val local = LocalStore(context, owner.context)
+ val computer = withContext(Dispatchers.IO) { local.computers().firstOrNull() } ?: return@withTimeout false
+ val identity = withContext(Dispatchers.IO) { local.identity() }
+ val channel = HostConnector.connect(computer, identity)
+ try {
+ val current = HostClient.hello(channel, computer)
+ val bots = HostClient.bots(channel)
+ val response = channel.call("usage", buildJsonObject { put("refresh", false) })
+ val usage = UsageReport.decode(response)
+ withContext(Dispatchers.IO) { WidgetStore.publish(context, owner, current, bots, usage, true, true, expectedRevision = revision) }
+ } finally { channel.close() }
+ }
+ }
+ suspend fun stop(context: Context) {
+ WorkManager.getInstance(context).cancelUniqueWork(NAME)
+ // Join every reader before account erasure can remove its storage.
+ gate.withLock { }
+ }
+ fun schedule(context: Context, paired: Boolean) {
+ val work = WorkManager.getInstance(context)
+ if (!paired || CodyncWidgets.installed(context) == 0) { work.cancelUniqueWork(NAME); return }
+ val request = PeriodicWorkRequestBuilder<WidgetRefreshWorker>(30, TimeUnit.MINUTES)
+ .setInitialDelay(30, TimeUnit.MINUTES)
+ .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
+ .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS).build()
+ work.enqueueUniquePeriodicWork(NAME, ExistingPeriodicWorkPolicy.UPDATE, request)
+ }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WidgetSetupDemo.kt b/apps/android/app/src/main/kotlin/com/codync/android/WidgetSetupDemo.kt
new file mode 100644
index 00000000..d0531250
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetSetupDemo.kt
@@ -0,0 +1,375 @@
+package com.codync.android
+
+import androidx.compose.animation.Crossfade
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.gestures.awaitEachGesture
+import androidx.compose.foundation.gestures.awaitFirstDown
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.requiredSize
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.withFrameNanos
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.TransformOrigin
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.semantics.CustomAccessibilityAction
+import androidx.compose.ui.semantics.clearAndSetSemantics
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.customActions
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.semantics.stateDescription
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import com.kyant.shapes.UnevenRoundedRectangle
+import kotlin.math.abs
+import kotlin.math.pow
+
+/**
+ * "Add a widget", acted out on a drawn Android phone (iOS `WidgetSetupDemo`): hold the Home Screen,
+ * Widgets, find Codync, pick a widget, Add. Every frame is a pure function of one clock, so it
+ * loops, pauses and scrubs. `active` stops the clock while the State tab is hidden.
+ */
+@Composable internal fun WidgetSetupDemo(active: Boolean) {
+ val still = reduceMotion()
+ var playing by remember { mutableStateOf(!still) }
+ var scrubbing by remember { mutableStateOf(false) }
+ var t by remember { mutableFloatStateOf(if (still) 6.6f else 0f) }
+ val running = playing && !scrubbing && active
+ LaunchedEffect(running) {
+ if (!running) return@LaunchedEffect
+ var last = 0L
+ while (true) withFrameNanos { now ->
+ if (last != 0L) t = (t + (now - last) / 1e9f) % DURATION
+ last = now
+ }
+ }
+ val step = step(t)
+ Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.dp)) {
+ Box(Modifier.semantics(mergeDescendants = true) { contentDescription = "How to add the Codync widget"; stateDescription = step.text }) {
+ DemoPhone(t)
+ }
+ Crossfade(step.index, animationSpec = Motion.fade(), label = "Step") { index ->
+ Text(STEPS[index].text, Modifier.fillMaxWidth().clearAndSetSemantics {}, style = Type.footnote.medium, color = Palette.text,
+ textAlign = TextAlign.Center)
+ }
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ IconButton(if (playing) "Pause" else "Play", if (playing) "pause.fill" else "play.fill") { playing = !playing }
+ Scrubber(t, scrubbing, Modifier.weight(1f), { scrubbing = it }, { t = it }) { index -> playing = false; t = STEPS[index].start + 0.05f }
+ }
+ }
+}
+
+/** The timeline: drag anywhere on it to scrub; TalkBack steps through the script instead. */
+@Composable private fun Scrubber(t: Float, scrubbing: Boolean, modifier: Modifier, scrub: (Boolean) -> Unit, seek: (Float) -> Unit,
+ jump: (Int) -> Unit) {
+ val index = step(t).index
+ BoxWithConstraints(modifier.height(32.dp)
+ .pointerInput(Unit) {
+ awaitEachGesture {
+ val down = awaitFirstDown()
+ scrub(true)
+ seek((down.position.x / size.width).coerceIn(0f, 0.999f) * DURATION)
+ while (true) {
+ val change = awaitPointerEvent().changes.firstOrNull() ?: break
+ if (!change.pressed) break
+ seek((change.position.x / size.width).coerceIn(0f, 0.999f) * DURATION)
+ change.consume()
+ }
+ scrub(false)
+ }
+ }
+ .semantics {
+ contentDescription = "Step"; stateDescription = STEPS[index].text
+ customActions = listOfNotNull(
+ if (index < STEPS.lastIndex) CustomAccessibilityAction("Next step") { jump(index + 1); true } else null,
+ if (index > 0) CustomAccessibilityAction("Previous step") { jump(index - 1); true } else null,
+ )
+ }, contentAlignment = Alignment.CenterStart) {
+ val x = maxWidth * (t / DURATION)
+ val knob = if (scrubbing) 18.dp else 14.dp
+ Box(Modifier.fillMaxWidth().height(4.dp).clip(Capsule()).background(Palette.accentDim))
+ Box(Modifier.width(x).height(4.dp).clip(Capsule()).background(Palette.accent))
+ Box(Modifier.offset(x = x - knob / 2).size(knob).clip(Capsule()).background(Palette.accent))
+ }
+}
+
+// MARK: - script
+
+private class DemoStep(val index: Int, val start: Float, val text: String)
+
+private const val DURATION = 9.5f
+
+private val STEPS = listOf(
+ DemoStep(0, 0f, "Touch and hold an empty spot on your Home Screen"),
+ DemoStep(1, 1.8f, "Tap Widgets"),
+ DemoStep(2, 2.6f, "Find Codync in the list"),
+ DemoStep(3, 4.5f, "Tap a widget, then Add"),
+ DemoStep(4, 6.0f, "It's on your Home Screen. Touch and hold it to move it."),
+)
+
+private fun step(t: Float) = STEPS.last { t >= it.start }
+
+/** 0 before `a`, 1 after `b`, smooth in between. */
+private fun ramp(t: Float, a: Float, b: Float): Float {
+ val x = ((t - a) / (b - a)).coerceIn(0f, 1f)
+ return x * x * (3 - 2 * x)
+}
+
+/** Ease-out for things that arrive (sheets, pages). */
+private fun arrive(t: Float, a: Float, b: Float): Float = 1 - (1 - ((t - a) / (b - a)).coerceIn(0f, 1f)).pow(3)
+
+// MARK: - the phone
+
+private val PHONE_W = 184.dp
+private val PHONE_H = 384.dp
+private const val SHEET_TOP = 40f
+
+// Where the finger goes (screen points) and when it taps.
+private val PATH = listOf(
+ 0.2f to Offset(150f, 300f), 0.9f to Offset(128f, 250f), 1.8f to Offset(128f, 250f),
+ 2.2f to Offset(104f, 212f), 2.5f to Offset(104f, 212f), 3.4f to Offset(92f, 193f),
+ 4.1f to Offset(92f, 193f), 4.6f to Offset(92f, 258f), 5.0f to Offset(92f, 258f),
+ 5.45f to Offset(92f, 318f), 6.3f to Offset(92f, 318f),
+)
+private val TAPS = listOf(2.35f, 4.0f, 4.85f, 5.75f)
+
+private fun pressed(t: Float, tap: Float) = abs(t - tap) < 0.12f
+
+@Composable private fun DemoPhone(t: Float) {
+ val menu = ramp(t, 1.65f, 1.85f) * (1 - ramp(t, 2.4f, 2.6f))
+ val sheet = arrive(t, 2.5f, 3.0f) * (1 - ramp(t, 5.8f, 6.2f))
+ val placed = arrive(t, 5.95f, 6.4f)
+ // The demo is a dark phone in both modes, as the iOS one.
+ CompositionLocalProvider(LocalDark provides true) {
+ Box(Modifier.clip(RoundedRectangle(35.dp)).background(Color.Black).padding(5.dp)) {
+ Box(Modifier.size(PHONE_W, PHONE_H).clip(RoundedRectangle(30.dp))) {
+ Wallpaper(sheet)
+ HomeScreen(t, sheet, placed)
+ LongPressMenu(t, menu)
+ WidgetPicker(t, sheet)
+ Finger(t)
+ StatusBar()
+ }
+ }
+ }
+}
+
+@Composable private fun Wallpaper(sheet: Float) {
+ Box(Modifier.fillMaxSize().background(Brush.verticalGradient(listOf(Color(0xFF243B6B), Color(0xFF5B4A8B), Color(0xFF2A2340)))))
+ Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.35f * sheet)))
+}
+
+@Composable private fun StatusBar() {
+ Box(Modifier.fillMaxWidth().height(24.dp).padding(horizontal = 16.dp), contentAlignment = Alignment.Center) {
+ // The punch-hole camera.
+ Box(Modifier.size(9.dp).clip(Capsule()).background(Color.Black))
+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
+ Text("9:41", style = Type.system(9f, FontWeight.SemiBold), color = Color.White)
+ Spacer(Modifier.weight(1f))
+ Symbol("wifi", size = 10.dp, tint = Color.White)
+ Symbol("battery.75percent", size = 11.dp, tint = Color.White)
+ }
+ }
+}
+
+private val APPS = listOf("calendar" to 0xFFE5534B, "photo" to 0xFFF0A030, "clock" to 0xFF4A4F57, "cloud" to 0xFF3D8BFD,
+ "music.note" to 0xFFE0558C, "folder" to 0xFF2E9E6A, "globe" to 0xFF2D7FF9, "gearshape" to 0xFF6B7280,
+ "bell" to 0xFFF2B33D, "terminal" to 0xFF222831, "doc.text" to 0xFF3E7BD6, "key" to 0xFF8A63D2)
+private val DOCK = listOf("text.bubble" to 0xFF2E9E6A, "safari" to 0xFF2D7FF9, "mic" to 0xFFE5534B, "photo.on.rectangle" to 0xFFF0A030)
+private const val WIDGET_H = 84f
+
+@Composable private fun HomeScreen(t: Float, sheet: Float, placed: Float) {
+ val press = ramp(t, 1.0f, 1.6f) * (1 - ramp(t, 1.75f, 1.95f))
+ Column(Modifier.fillMaxSize().graphicsLayer { val s = 1 - 0.04f * sheet - 0.02f * press; scaleX = s; scaleY = s }
+ .padding(top = 30.dp, start = 14.dp, end = 14.dp, bottom = 10.dp)) {
+ Text("Sat, Oct 17", style = Type.system(11f, FontWeight.Medium), color = Color.White.copy(alpha = 0.92f))
+ Spacer(Modifier.height(6.dp))
+ // The icons below slide down as the widget takes its row.
+ Box(Modifier.fillMaxWidth().height(((WIDGET_H + 8f) * placed).dp), contentAlignment = Alignment.TopCenter) {
+ Box(Modifier.graphicsLayer { alpha = placed; val s = 0.9f + 0.1f * placed; scaleX = s; scaleY = s; transformOrigin = TransformOrigin(0.5f, 0f) }) {
+ WidgetThumb(156.dp, WIDGET_H.dp, Color(0xFF1B1B1F))
+ }
+ }
+ for (row in APPS.chunked(4)) {
+ Row(Modifier.fillMaxWidth().padding(bottom = 9.dp), horizontalArrangement = Arrangement.SpaceBetween) {
+ for ((symbol, tint) in row) AppIcon(symbol, tint, label = true)
+ }
+ }
+ Spacer(Modifier.weight(1f))
+ Row(Modifier.fillMaxWidth().padding(bottom = 10.dp), horizontalArrangement = Arrangement.SpaceBetween) {
+ for ((symbol, tint) in DOCK) AppIcon(symbol, tint, label = false)
+ }
+ Row(Modifier.fillMaxWidth().height(24.dp).clip(Capsule()).background(Color.White.copy(alpha = 0.2f)).padding(horizontal = 10.dp),
+ verticalAlignment = Alignment.CenterVertically) {
+ Symbol("magnifyingglass", size = 11.dp, tint = Color.White.copy(alpha = 0.8f))
+ Spacer(Modifier.weight(1f))
+ Symbol("mic", size = 11.dp, tint = Color.White.copy(alpha = 0.8f))
+ }
+ // The gesture bar.
+ Box(Modifier.fillMaxWidth().padding(top = 9.dp), contentAlignment = Alignment.Center) {
+ Box(Modifier.size(56.dp, 3.dp).clip(Capsule()).background(Color.White.copy(alpha = 0.8f)))
+ }
+ }
+}
+
+@Composable private fun AppIcon(symbol: String, tint: Long, label: Boolean) {
+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(3.dp)) {
+ Box(Modifier.size(32.dp).clip(Capsule()).background(Color(tint)), contentAlignment = Alignment.Center) {
+ Symbol(symbol, size = 16.dp, tint = Color.White)
+ }
+ if (label) Box(Modifier.size(20.dp, 3.dp).clip(Capsule()).background(Color.White.copy(alpha = 0.55f)))
+ }
+}
+
+/** The Bots widget at a small scale: the same card the Home Screen gets. */
+@Composable private fun WidgetThumb(width: Dp, height: Dp, fill: Color) {
+ val scale = 0.6f
+ Box(Modifier.size(width, height), contentAlignment = Alignment.Center) {
+ Box(Modifier.requiredSize(width / scale, height / scale).graphicsLayer { scaleX = scale; scaleY = scale }
+ .clip(RoundedRectangle(22.dp)).background(fill).padding(12.dp)) {
+ BotsWidgetCard(WidgetPreview.bots, WidgetPreview.activities, wide = true, large = false)
+ }
+ }
+}
+
+/** The launcher's long-press menu, growing from the finger. */
+@Composable private fun LongPressMenu(t: Float, shown: Float) {
+ if (shown <= 0f) return
+ Column(Modifier.offset(56.dp, 176.dp).width(112.dp)
+ .graphicsLayer { alpha = shown; val s = 0.7f + 0.3f * shown; scaleX = s; scaleY = s; transformOrigin = TransformOrigin(0.65f, 1f) }
+ .clip(RoundedRectangle(14.dp)).background(Color(0xFF2B2930))) {
+ MenuRow("Wallpaper & style", "paintbrush", false)
+ MenuRow("Widgets", "square.grid.2x2", pressed(t, 2.35f))
+ MenuRow("Home settings", "gearshape", false)
+ }
+}
+
+@Composable private fun MenuRow(title: String, symbol: String, highlighted: Boolean) {
+ Row(Modifier.fillMaxWidth().height(24.dp).background(Color.White.copy(alpha = if (highlighted) 0.14f else 0f)).padding(horizontal = 9.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) {
+ Symbol(symbol, size = 11.dp, tint = Color.White)
+ Text(title, style = Type.system(9f, FontWeight.Medium), color = Color.White, maxLines = 1)
+ }
+}
+
+/** The system widget picker: a sheet of apps, Codync opening to its widgets, then Add. */
+@Composable private fun WidgetPicker(t: Float, sheet: Float) {
+ if (sheet <= 0f) return
+ val open = arrive(t, 3.95f, 4.35f)
+ val chosen = arrive(t, 4.85f, 5.1f)
+ val height = PHONE_H - SHEET_TOP.dp
+ Column(Modifier.offset(y = SHEET_TOP.dp + height * (1 - sheet)).size(PHONE_W, height)
+ .clip(UnevenRoundedRectangle(topStart = 20.dp, topEnd = 20.dp)).background(Color(0xFF1F1E24))) {
+ Box(Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 6.dp), contentAlignment = Alignment.Center) {
+ Box(Modifier.size(28.dp, 3.dp).clip(Capsule()).background(Color.White.copy(alpha = 0.3f)))
+ }
+ Text("Widgets", Modifier.fillMaxWidth(), style = Type.system(12f, FontWeight.SemiBold), color = Color.White, textAlign = TextAlign.Center)
+ Row(Modifier.padding(horizontal = 12.dp, vertical = 8.dp).fillMaxWidth().height(22.dp).clip(Capsule()).background(Color.White.copy(alpha = 0.1f))
+ .padding(horizontal = 9.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) {
+ Symbol("magnifyingglass", size = 10.dp, tint = Color.White.copy(alpha = 0.5f))
+ Text("Search widgets", style = Type.system(9f), color = Color.White.copy(alpha = 0.5f))
+ }
+ PickerRow("Calendar", "calendar", 0xFFE5534B, "2 widgets")
+ PickerRow("Clock", "clock", 0xFF4A4F57, "4 widgets")
+ PickerRow("Codync", null, 0, "3 widgets", highlighted = pressed(t, 4.0f), open = open)
+ // Codync's widgets, unfolded under its row.
+ Column(Modifier.fillMaxWidth().height((96f * open + 40f * open * chosen).dp).graphicsLayer { alpha = open },
+ horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ // The picked widget lifts a little; Add appears under it.
+ Box(Modifier.graphicsLayer { val s = (if (pressed(t, 4.85f)) 0.96f else 1f) + 0.04f * chosen; scaleX = s; scaleY = s }) {
+ WidgetThumb(150.dp, 78.dp, Color(0xFF2C2B32))
+ }
+ if (chosen > 0f) Box(Modifier.graphicsLayer { alpha = chosen; val s = if (pressed(t, 5.75f)) 0.94f else 1f; scaleX = s; scaleY = s }
+ .size(84.dp, 26.dp).clip(Capsule()).background(Color(0xFFD0BCFF)), contentAlignment = Alignment.Center) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ Symbol("plus", size = 11.dp, tint = Color(0xFF381E72))
+ Text("Add", style = Type.system(10f, FontWeight.SemiBold), color = Color(0xFF381E72))
+ }
+ }
+ }
+ PickerRow("Files", "folder", 0xFF2E9E6A, "1 widget")
+ PickerRow("Weather", "cloud", 0xFF3D8BFD, "3 widgets")
+ }
+}
+
+@Composable private fun PickerRow(title: String, symbol: String?, tint: Long, count: String, highlighted: Boolean = false, open: Float = 0f) {
+ Row(Modifier.fillMaxWidth().height(30.dp).background(Color.White.copy(alpha = if (highlighted) 0.1f else 0f)).padding(horizontal = 12.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (symbol != null) Box(Modifier.size(20.dp).clip(Capsule()).background(Color(tint)), contentAlignment = Alignment.Center) {
+ Symbol(symbol, size = 11.dp, tint = Color.White)
+ } else Box(Modifier.size(20.dp).clip(Capsule()).background(Color(0xFF2C2B32)), contentAlignment = Alignment.Center) {
+ CharacterAvatar("hex", "gray", 16.dp)
+ }
+ Column(Modifier.weight(1f)) {
+ Text(title, style = Type.system(10f, FontWeight.Medium), color = Color.White, maxLines = 1)
+ Text(count, style = Type.system(8f), color = Color.White.copy(alpha = 0.5f), maxLines = 1)
+ }
+ Symbol("chevron.down", Modifier.graphicsLayer { rotationZ = 180f * open }, size = 10.dp, tint = Color.White.copy(alpha = 0.5f))
+ }
+}
+
+// MARK: - finger
+
+@Composable private fun Finger(t: Float) {
+ val visible = ramp(t, 0.15f, 0.4f) * (1 - ramp(t, 6.3f, 6.6f))
+ if (visible <= 0f) return
+ val tapDepth = TAPS.maxOf { maxOf(0f, 1 - abs(t - it) / 0.14f) }
+ val holding = ramp(t, 0.95f, 1.05f) * (1 - ramp(t, 1.65f, 1.75f))
+ val hold = ramp(t, 1.0f, 1.6f)
+ val p = fingerPoint(t)
+ Box(Modifier.offset((p.x - 17f).dp, (p.y - 17f).dp).size(34.dp).graphicsLayer { alpha = visible }, contentAlignment = Alignment.Center) {
+ // The long press fills a ring before the menu opens.
+ Canvas(Modifier.fillMaxSize()) {
+ val line = 2.dp.toPx()
+ drawArc(Color.White.copy(alpha = 0.8f), -90f, 360f * hold * holding, false, style = Stroke(line, cap = StrokeCap.Round),
+ topLeft = Offset(line / 2, line / 2), size = androidx.compose.ui.geometry.Size(size.width - line, size.height - line))
+ }
+ Box(Modifier.size(24.dp).graphicsLayer { val s = 1 - 0.2f * maxOf(tapDepth, holding); scaleX = s; scaleY = s }
+ .clip(Capsule()).background(Color.White.copy(alpha = 0.35f + 0.25f * maxOf(tapDepth, holding)))
+ .border(1.5.dp, Color.White.copy(alpha = 0.85f), Capsule()))
+ }
+}
+
+private fun fingerPoint(t: Float): Offset {
+ val next = PATH.indexOfFirst { it.first > t }
+ if (next == -1) return PATH.last().second
+ if (next == 0) return PATH.first().second
+ val (ta, a) = PATH[next - 1]
+ val (tb, b) = PATH[next]
+ val k = ramp(t, ta, tb)
+ return Offset(a.x + (b.x - a.x) * k, a.y + (b.y - a.y) * k)
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WidgetStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/WidgetStore.kt
new file mode 100644
index 00000000..52d3de36
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetStore.kt
@@ -0,0 +1,99 @@
+package com.codync.android
+
+import android.content.Context
+import android.util.AtomicFile
+import com.codync.android.core.*
+import java.io.File
+import java.util.UUID
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.serialization.Serializable
+
+@Serializable internal data class WidgetOwner(val context: String, val scope: String, val epoch: String)
+
+/** Every write checks the original account activation, including background responses. */
+internal object WidgetStore {
+ val changes = MutableStateFlow(0L)
+ private fun activeFile(context: Context) = AtomicFile(File(context.noBackupFilesDir, "widget-owner.json"))
+ private fun feedFile(context: Context, owner: WidgetOwner) = AtomicFile(File(LocalStore(context, owner.context).directory, "widget-feed.json"))
+
+ @Synchronized fun owner(context: Context): WidgetOwner? = read<WidgetOwner>(activeFile(context))
+
+ @Synchronized fun activate(context: Context, account: String): WidgetOwner {
+ val owner = WidgetOwner(account, LocalStore.referenceId(account), UUID.randomUUID().toString())
+ write(activeFile(context), owner)
+ changed()
+ return owner
+ }
+
+ @Synchronized fun retire(context: Context, expected: WidgetOwner?) {
+ if (expected != null && owner(context) == expected) { activeFile(context).delete(); changed() }
+ }
+
+ @Synchronized fun feed(context: Context): WidgetFeed {
+ val active = owner(context) ?: return WidgetFeed()
+ val saved = read<WidgetFeed>(feedFile(context, active))
+ val paired = runCatching { LocalStore(context, active.context).computers().firstOrNull()?.id }.getOrNull()
+ return saved?.takeIf { it.scope == active.scope && it.computerId == paired } ?: WidgetFeed(scope = active.scope)
+ }
+
+ @Synchronized fun publish(context: Context, expected: WidgetOwner, computer: Computer?, bots: List<Bot>,
+ usage: UsageReport, freshBots: Boolean, freshUsage: Boolean, now: Long = System.currentTimeMillis(),
+ expectedRevision: Long? = null): Boolean {
+ if (owner(context) != expected || expectedRevision != null && changes.value != expectedRevision) return false
+ val file = feedFile(context, expected)
+ val previous = read<WidgetFeed>(file)?.takeIf { it.computerId == computer?.id } ?: WidgetFeed(scope = expected.scope)
+ val next = WidgetFeed(expected.scope, computer?.id, computer?.name.orEmpty().take(256), widgetBots(bots),
+ if (freshBots) now else previous.botsAt, usage, if (freshUsage) now else
+ if (usage != previous.usage) usage.providers.mapNotNull { it.updatedAt?.takeIf { time -> time > 0 } }.minOrNull() ?: 0
+ else previous.usageAt)
+ if (previous == next) return true
+ write(file, next)
+ changed()
+ return true
+ }
+
+ @Synchronized fun selectProvider(context: Context, widget: Int, provider: String) {
+ require(provider.isNotBlank() && provider.length <= 128 && provider.none(Char::isISOControl))
+ check(context.getSharedPreferences("codync-widgets", Context.MODE_PRIVATE).edit().putString("provider:$widget", provider).commit())
+ changed()
+ }
+ fun provider(context: Context, widget: Int): String = context.getSharedPreferences("codync-widgets", Context.MODE_PRIVATE)
+ .getString("provider:$widget", "claude") ?: "claude"
+ /** Usage shows each provider as a character, or as its own logo ("Choose the look"), in the app and its widgets. */
+ fun originalIcons(context: Context): Boolean = context.getSharedPreferences("codync-widgets", Context.MODE_PRIVATE).getBoolean("originalIcons", false)
+ @Synchronized fun setOriginalIcons(context: Context, on: Boolean) {
+ check(context.getSharedPreferences("codync-widgets", Context.MODE_PRIVATE).edit().putBoolean("originalIcons", on).commit())
+ changed()
+ }
+
+ /** The Team widget's chosen bot per spot; empty spots fill themselves. */
+ @Synchronized fun selectTeam(context: Context, widget: Int, picks: List<String?>) {
+ require(picks.size == 4 && picks.all { it == null || it.length <= 128 && it.none(Char::isISOControl) })
+ check(context.getSharedPreferences("codync-widgets", Context.MODE_PRIVATE).edit()
+ .putString("team:$widget", picks.joinToString("\n") { it.orEmpty() }).commit())
+ changed()
+ }
+ fun team(context: Context, widget: Int): List<String?> = context.getSharedPreferences("codync-widgets", Context.MODE_PRIVATE)
+ .getString("team:$widget", null)?.split("\n")?.map { it.ifEmpty { null } }?.takeIf { it.size == 4 } ?: List(4) { null }
+ @Synchronized fun remove(context: Context, ids: IntArray) {
+ val editor = context.getSharedPreferences("codync-widgets", Context.MODE_PRIVATE).edit()
+ ids.forEach { editor.remove("provider:$it"); editor.remove("team:$it") }; check(editor.commit()); changed()
+ }
+ @Synchronized fun reset(context: Context) {
+ activeFile(context).delete()
+ check(context.getSharedPreferences("codync-widgets", Context.MODE_PRIVATE).edit().clear().commit())
+ changed()
+ }
+ private fun changed() { changes.value++ }
+ private inline fun <reified T> read(file: AtomicFile): T? = try {
+ if (!file.baseFile.exists() || file.baseFile.length() > 512 * 1024) null
+ else WireJson.decodeFromString<T>(file.readFully().toString(Charsets.UTF_8))
+ } catch (_: Exception) { null }
+ private inline fun <reified T> write(file: AtomicFile, value: T) {
+ val bytes = WireJson.encodeToString(value).toByteArray()
+ require(bytes.size <= 512 * 1024) { "The widget report is too large." }
+ val output = file.startWrite()
+ try { output.write(bytes); file.finishWrite(output) }
+ catch (error: Throwable) { file.failWrite(output); throw error }
+ }
+}
diff --git a/apps/android/app/src/main/res/drawable/agent_amp_acp.xml b/apps/android/app/src/main/res/drawable/agent_amp_acp.xml
new file mode 100644
index 00000000..b0fd4ec5
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_amp_acp.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- amp-acp.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="28" android:viewportHeight="28">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M13.92 13.61L17.38 26.57L14.24 27.4L11.26 16.26L0.12 13.29L0.96 10.15L13.92 13.61Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M13.74 16.09L4.88 24.91L2.59 22.6L11.45 13.79L13.74 16.09Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M18.94 8.58L22.4 21.54L19.26 22.38L16.28 11.24L5.14 8.26L5.98 5.12L18.94 8.58Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M23.98 3.56L27.44 16.51L24.3 17.35L21.32 6.21L10.18 3.24L11.02 0.1L23.98 3.56Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_antigravity_acp.xml b/apps/android/app/src/main/res/drawable/agent_antigravity_acp.xml
new file mode 100644
index 00000000..91996f0b
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_antigravity_acp.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- antigravity-acp.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M14.15 14.68C14.99 15.32 16.27 14.89 15.1 13.73C11.6 10.33 12.34 1 7.99 1C3.65 1 4.39 10.33 0.89 13.73C-0.39 15 0.99 15.32 1.84 14.68C5.13 12.45 4.92 8.53 7.99 8.53C11.07 8.53 10.86 12.45 14.15 14.68Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_auggie.xml b/apps/android/app/src/main/res/drawable/agent_auggie.xml
new file mode 100644
index 00000000..33919f7e
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_auggie.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- auggie.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M9.97 13.19h2.58q0.19 0 0.28-0.09t0.09-0.29V10.47q0-0.320.13-0.590.14-0.270.36-0.42a1 1 0 0 1 0.1-0.06 1 1 0 0 1-0.1-0.06 1.1 1.1 0 0 1-0.36-0.42 1.3 1.3 0 0 1-0.13-0.59v-2.33q0-0.2-0.09-0.29t-0.28-0.09H9.97a0.380.38 0 0 1-0.29-0.120.40.4 0 0 1-0.11-0.28q0-0.180.13-0.29a0.460.46 0 0 1 0.31-0.11h2.77c0.36 0 0.640.10.840.29q0.290.290.290.83V8.24q0 0.390.150.560.150.170.560.18a0.40.4 0 0 1 0.270.130.410.41 0 0 1 0.10.290.440.44 0 0 1-0.10.280.340.34 0 0 1-0.280.13c-0.270.01-0.450.07-0.550.18q-0.150.17-0.150.57v2.32c0 0.23-0.040.44-0.130.61a0.850.85 0 0 1-0.390.39 1.3 1.3 0 0 1-0.530.12V14h-2.85a0.450.45 0 0 1-0.32-0.120.380.38 0 0 1-0.13-0.29q0-0.160.11-0.28a0.380.38 0 0 1 0.29-0.12zM1.1 9.11a0.40.4 0 0 1 0.28-0.13q0.4-0.010.55-0.180.15-0.170.15-0.56V5.92q0-0.540.29-0.83c0.2-0.190.48-0.290.84-0.29h2.77q0.19 0 0.310.11a0.370.37 0 0 1 0.130.290.40.4 0 0 1-0.110.280.380.38 0 0 1-0.290.12H3.45q-0.19 0-0.280.09t-0.090.29v2.33c0 0.21-0.040.41-0.130.59a1.1 1.1 0 0 1-0.360.42 1 1 0 0 1-0.10.06 1 1 0 0 1 0.10.06q0.230.160.360.42t0.130.59v2.34q0 0.20.090.290.090.090.280.09h2.58a0.380.38 0 0 1 0.290.12q0.110.120.110.28a0.380.38 0 0 1-0.130.290.450.45 0 0 1-0.310.12l-2.77-0a1.4 1.4 0 0 1-0.61-0.130.870.87 0 0 1-0.39-0.39 1.34 1.34 0 0 1-0.13-0.61v-2.32q0-0.4-0.15-0.57-0.15-0.17-0.55-0.18a0.350.35 0 0 1-0.28-0.130.420.42 0 0 1-0.1-0.28q0-0.170.1-0.29" android:fillColor="#FF000000"/>
+ <path android:pathData="M5.44 10.36a0.990.99 0 0 1-0.99-0.97c0-0.540.45-0.980.99-0.98s0.990.440.990.98a0.990.99 0 0 1-0.990.98M10.56 8.41c0.55 0 0.990.440.990.97a0.990.99 0 0 1-0.990.980.990.99 0 0 1-0.99-0.98c0-0.540.45-0.980.99-0.98M8.74 2c0.37 0 0.450.150.450.28v0.03q0 0.03-0.010.2-0.010.16-0.020.55-0.020.38-0.04 1.06c0 0.11-0.070.23-0.380.23-0.31 0-0.38-0.13-0.38-0.23l-0.07-1.83v-0c0-0.130.08-0.280.45-0.28M7.26 2c0.37 0 0.450.150.450.28v0.03q0 0.03-0.010.2-0.010.16-0.020.55-0.020.38-0.04 1.06c0 0.11-0.070.23-0.380.23-0.31 0-0.38-0.13-0.38-0.23l-0.07-1.83v-0C6.81 2.15 6.89 2 7.26 2" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_autohand.xml b/apps/android/app/src/main/res/drawable/agent_autohand.xml
new file mode 100644
index 00000000..7b7abbcf
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_autohand.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- autohand.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M4.67 9.57C4.67 8.92 4.13 8.4 3.47 8.4C2.81 8.4 2.27 8.92 2.27 9.57C2.27 10.21 2.81 10.73 3.47 10.73V11C2.66 11 2 10.36 2 9.57C2 8.77 2.66 8.13 3.47 8.13C4.28 8.13 4.94 8.77 4.94 9.57C4.94 10.36 4.28 11 3.47 11V10.73C4.13 10.73 4.67 10.21 4.67 9.57Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M3.91 9.59C3.91 9.81 3.72 9.99 3.5 9.99C3.27 9.99 3.09 9.81 3.09 9.59C3.09 9.37 3.27 9.19 3.5 9.19C3.72 9.19 3.91 9.37 3.91 9.59Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M3.85 9.59C3.85 9.4 3.69 9.25 3.5 9.25C3.3 9.25 3.14 9.4 3.14 9.59C3.14 9.78 3.3 9.94 3.5 9.94V9.99C3.27 9.99 3.09 9.81 3.09 9.59C3.09 9.37 3.27 9.19 3.5 9.19C3.72 9.19 3.91 9.37 3.91 9.59C3.91 9.81 3.72 9.99 3.5 9.99V9.94C3.69 9.94 3.85 9.78 3.85 9.59Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M4.67 6.43C4.67 5.79 4.13 5.27 3.47 5.27C2.81 5.27 2.27 5.79 2.27 6.43C2.27 7.08 2.81 7.6 3.47 7.6V7.87C2.66 7.87 2 7.23 2 6.43C2 5.64 2.66 5 3.47 5C4.28 5 4.94 5.64 4.94 6.43C4.94 7.23 4.28 7.87 3.47 7.87V7.6C4.13 7.6 4.67 7.08 4.67 6.43Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M3.91 6.46C3.91 6.68 3.72 6.86 3.5 6.86C3.27 6.86 3.09 6.68 3.09 6.46C3.09 6.24 3.27 6.06 3.5 6.06C3.72 6.06 3.91 6.24 3.91 6.46Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M3.85 6.46C3.85 6.27 3.69 6.12 3.5 6.12C3.3 6.12 3.14 6.27 3.14 6.46C3.14 6.65 3.3 6.81 3.5 6.81V6.86C3.27 6.86 3.09 6.68 3.09 6.46C3.09 6.24 3.27 6.06 3.5 6.06C3.72 6.06 3.91 6.24 3.91 6.46C3.91 6.68 3.72 6.86 3.5 6.86V6.81C3.69 6.81 3.85 6.65 3.85 6.46Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M8.05 9.57C8.05 8.92 7.51 8.4 6.85 8.4C6.19 8.4 5.65 8.92 5.65 9.57C5.65 10.21 6.19 10.73 6.85 10.73V11C6.04 11 5.38 10.36 5.38 9.57C5.38 8.77 6.04 8.13 6.85 8.13C7.66 8.13 8.32 8.77 8.32 9.57C8.32 10.36 7.66 11 6.85 11V10.73C7.51 10.73 8.05 10.21 8.05 9.57Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M7.28 9.59C7.28 9.81 7.1 9.99 6.88 9.99C6.65 9.99 6.47 9.81 6.47 9.59C6.47 9.37 6.65 9.19 6.88 9.19C7.1 9.19 7.28 9.37 7.28 9.59Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M7.23 9.59C7.23 9.4 7.07 9.25 6.88 9.25C6.68 9.25 6.52 9.4 6.52 9.59C6.52 9.78 6.68 9.94 6.88 9.94V9.99C6.65 9.99 6.47 9.81 6.47 9.59C6.47 9.37 6.65 9.19 6.88 9.19C7.1 9.19 7.28 9.37 7.28 9.59C7.28 9.81 7.1 9.99 6.88 9.99V9.94C7.07 9.94 7.23 9.78 7.23 9.59Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M8.05 6.43C8.05 5.79 7.51 5.27 6.85 5.27C6.19 5.27 5.65 5.79 5.65 6.43C5.65 7.08 6.19 7.6 6.85 7.6V7.87C6.04 7.87 5.38 7.23 5.38 6.43C5.38 5.64 6.04 5 6.85 5C7.66 5 8.32 5.64 8.32 6.43C8.32 7.23 7.66 7.87 6.85 7.87V7.6C7.51 7.6 8.05 7.08 8.05 6.43Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M7.28 6.46C7.28 6.68 7.1 6.86 6.88 6.86C6.65 6.86 6.47 6.68 6.47 6.46C6.47 6.24 6.65 6.06 6.88 6.06C7.1 6.06 7.28 6.24 7.28 6.46Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M7.23 6.46C7.23 6.27 7.07 6.12 6.88 6.12C6.68 6.12 6.52 6.27 6.52 6.46C6.52 6.65 6.68 6.81 6.88 6.81V6.86C6.65 6.86 6.47 6.68 6.47 6.46C6.47 6.24 6.65 6.06 6.88 6.06C7.1 6.06 7.28 6.24 7.28 6.46C7.28 6.68 7.1 6.86 6.88 6.86V6.81C7.07 6.81 7.23 6.65 7.23 6.46Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M11.21 9.57C11.21 8.92 10.67 8.4 10.01 8.4C9.35 8.4 8.81 8.92 8.81 9.57C8.81 10.21 9.35 10.73 10.01 10.73V11C9.2 11 8.54 10.36 8.54 9.57C8.54 8.77 9.2 8.13 10.01 8.13C10.82 8.13 11.48 8.77 11.48 9.57C11.48 10.36 10.82 11 10.01 11V10.73C10.67 10.73 11.21 10.21 11.21 9.57Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M10.44 9.59C10.44 9.81 10.26 9.99 10.04 9.99C9.81 9.99 9.63 9.81 9.63 9.59C9.63 9.37 9.81 9.19 10.04 9.19C10.26 9.19 10.44 9.37 10.44 9.59Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M10.39 9.59C10.39 9.4 10.23 9.25 10.04 9.25C9.84 9.25 9.68 9.4 9.68 9.59C9.68 9.78 9.84 9.94 10.04 9.94V9.99C9.81 9.99 9.63 9.81 9.63 9.59C9.63 9.37 9.81 9.19 10.04 9.19C10.26 9.19 10.44 9.37 10.44 9.59C10.44 9.81 10.26 9.99 10.04 9.99V9.94C10.23 9.94 10.39 9.78 10.39 9.59Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M11.21 6.43C11.21 5.79 10.67 5.27 10.01 5.27C9.35 5.27 8.81 5.79 8.81 6.43C8.81 7.08 9.35 7.6 10.01 7.6V7.87C9.2 7.87 8.54 7.23 8.54 6.43C8.54 5.64 9.2 5 10.01 5C10.82 5 11.48 5.64 11.48 6.43C11.48 7.23 10.82 7.87 10.01 7.87V7.6C10.67 7.6 11.21 7.08 11.21 6.43Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M10.44 6.46C10.44 6.68 10.26 6.86 10.04 6.86C9.81 6.86 9.63 6.68 9.63 6.46C9.63 6.24 9.81 6.06 10.04 6.06C10.26 6.06 10.44 6.24 10.44 6.46Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M10.39 6.46C10.39 6.27 10.23 6.12 10.04 6.12C9.84 6.12 9.68 6.27 9.68 6.46C9.68 6.65 9.84 6.81 10.04 6.81V6.86C9.81 6.86 9.63 6.68 9.63 6.46C9.63 6.24 9.81 6.06 10.04 6.06C10.26 6.06 10.44 6.24 10.44 6.46C10.44 6.68 10.26 6.86 10.04 6.86V6.81C10.23 6.81 10.39 6.65 10.39 6.46Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M14.58 9.57C14.58 8.92 14.05 8.4 13.39 8.4C12.72 8.4 12.19 8.92 12.19 9.57C12.19 10.21 12.72 10.73 13.39 10.73V11C12.57 11 11.92 10.36 11.92 9.57C11.92 8.77 12.57 8.13 13.39 8.13C14.2 8.13 14.86 8.77 14.86 9.57C14.86 10.36 14.2 11 13.39 11V10.73C14.05 10.73 14.58 10.21 14.58 9.57Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M13.82 9.59C13.82 9.81 13.64 9.99 13.41 9.99C13.19 9.99 13 9.81 13 9.59C13 9.37 13.19 9.19 13.41 9.19C13.64 9.19 13.82 9.37 13.82 9.59Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M13.77 9.59C13.77 9.4 13.61 9.25 13.41 9.25C13.22 9.25 13.06 9.4 13.06 9.59C13.06 9.78 13.22 9.94 13.41 9.94V9.99C13.19 9.99 13 9.81 13 9.59C13 9.37 13.19 9.19 13.41 9.19C13.64 9.19 13.82 9.37 13.82 9.59C13.82 9.81 13.64 9.99 13.41 9.99V9.94C13.61 9.94 13.77 9.78 13.77 9.59Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M14.58 6.43C14.58 5.79 14.05 5.27 13.39 5.27C12.72 5.27 12.19 5.79 12.19 6.43C12.19 7.08 12.72 7.6 13.39 7.6V7.87C12.57 7.87 11.92 7.23 11.92 6.43C11.92 5.64 12.57 5 13.39 5C14.2 5 14.86 5.64 14.86 6.43C14.86 7.23 14.2 7.87 13.39 7.87V7.6C14.05 7.6 14.58 7.08 14.58 6.43Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M13.82 6.46C13.82 6.68 13.64 6.86 13.41 6.86C13.19 6.86 13 6.68 13 6.46C13 6.24 13.19 6.06 13.41 6.06C13.64 6.06 13.82 6.24 13.82 6.46Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M13.77 6.46C13.77 6.27 13.61 6.12 13.41 6.12C13.22 6.12 13.06 6.27 13.06 6.46C13.06 6.65 13.22 6.81 13.41 6.81V6.86C13.19 6.86 13 6.68 13 6.46C13 6.24 13.19 6.06 13.41 6.06C13.64 6.06 13.82 6.24 13.82 6.46C13.82 6.68 13.64 6.86 13.41 6.86V6.81C13.61 6.81 13.77 6.65 13.77 6.46Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_claude_acp.xml b/apps/android/app/src/main/res/drawable/agent_claude_acp.xml
new file mode 100644
index 00000000..fc9109bb
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_claude_acp.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- claude-acp.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="1200" android:viewportHeight="1200">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M 234 800.2 L 468.6 668.5 L 472.6 657.1 L 468.6 650.7 L 457.2 650.7 L 418 648.3 L 283.9 644.7 L 167.6 639.9 L 54.9 633.8 L 26.6 627.8 L 3.3e-05 592.8 L 2.7 575.3 L 26.6 559.2 L 60.7 562.2 L 136.2 567.4 L 249.4 575.2 L 331.6 580 L 453.3 592.7 L 472.6 592.7 L 475.3 584.9 L 468.7 580 L 463.6 575.2 L 346.4 495.8 L 219.5 411.9 L 153.1 363.5 L 117.2 339.1 L 99.1 316.1 L 91.2 266 L 123.9 230.1 L 167.7 233.1 L 178.9 236.1 L 223.2 270.2 L 318 343.6 L 441.8 434.7 L 459.9 449.8 L 467.2 444.6 L 468.1 441 L 459.9 427.4 L 392.6 305.7 L 320.8 181.9 L 288.8 130.6 L 280.3 99.9 C 277.4 87.2 275.2 76.6 275.2 63.6 L 312.3 13.2 L 332.9 6.6 L 382.4 13.2 L 403.2 31.3 L 434 101.7 L 483.9 212.5 L 561.2 363.2 L 583.8 407.9 L 595.9 449.3 L 600.4 462 L 608.2 462 L 608.2 454.7 L 614.6 369.8 L 626.3 265.6 L 637.8 131.5 L 641.7 93.7 L 660.4 48.5 L 697.5 24 L 726.5 37.9 L 750.4 72 L 747.1 94.1 L 732.9 186.2 L 705.1 330.5 L 687 427.2 L 697.5 427.2 L 709.6 415.1 L 758.5 350.2 L 840.6 247.5 L 876.9 206.7 L 919.2 161.7 L 946.3 140.3 L 997.6 140.3 L 1035.4 196.4 L 1018.5 254.4 L 965.6 321.4 L 921.8 378.2 L 859 462.8 L 819.8 530.4 L 823.4 535.8 L 832.8 534.9 L 974.7 504.7 L 1051.3 490.9 L 1142.8 475.2 L 1184.2 494.5 L 1188.7 514.1 L 1172.5 554.3 L 1074.6 578.5 L 959.8 601.4 L 788.9 641.9 L 786.8 643.4 L 789.3 646.4 L 866.3 653.6 L 899.2 655.4 L 979.8 655.4 L 1129.9 666.6 L 1169.2 692.5 L 1192.7 724.3 L 1188.7 748.4 L 1128.3 779.2 L 1046.8 759.9 L 856.6 714.6 L 791.4 698.3 L 782.3 698.3 L 782.3 703.7 L 836.7 756.9 L 936.3 846.8 L 1061.1 962.8 L 1067.4 991.5 L 1051.4 1014.1 L 1034.5 1011.7 L 924.9 929.2 L 882.6 892.1 L 786.8 811.5 L 780.5 811.5 L 780.5 819.9 L 802.6 852.2 L 919.1 1027.4 L 925.1 1081.1 L 916.7 1098.6 L 886.5 1109.2 L 853.3 1103.1 L 785.1 1007.4 L 714.7 899.5 L 657.9 802.9 L 651 806.8 L 617.5 1167.7 L 601.8 1186.1 L 565.5 1200 L 535.3 1177 L 519.3 1139.9 L 535.3 1066.6 L 554.7 970.8 L 570.4 894.7 L 584.5 800.1 L 593 768.7 L 592.4 766.6 L 585.5 767.5 L 514.2 865.4 L 405.8 1011.9 L 320.1 1103.7 L 299.5 1111.8 L 263.9 1093.4 L 267.2 1060.4 L 287.1 1031.1 L 405.8 880.1 L 477.4 786.5 L 523.7 732.5 L 523.3 724.7 L 520.6 724.7 L 205.3 929.4 L 149.2 936.6 L 125 914 L 128 876.9 L 139.4 864.8 L 234.2 799.6 L 233.9 799.9 Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_codebuddy_code.xml b/apps/android/app/src/main/res/drawable/agent_codebuddy_code.xml
new file mode 100644
index 00000000..bdb15ace
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_codebuddy_code.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- codebuddy-code.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M12.13 1.25c0.15-0.140.16-0.140.28-0.150.18 0 0.360.080.640.340.680.62 1.61 1.89 2.2 2.97l0.220.420.320.16c0.30.160.810.48 1.020.650.090.080.110.080.210.040.45-0.18 1.090.05 1.650.60.510.49 1 1.33 1.18 2.030.030.110.060.360.070.540.040.64-0.16 1.14-0.55 1.37-0.080.04-0.080.06-0.080.260.020.95-0.23 1.89-0.74 2.82-0.58 1.04-1.6 2.11-2.98 3.12-0.740.55-2.5 1.58-3.3 1.95-1.90.86-3.43 1.2-4.76 1.03-0.79-0.09-1.69-0.41-2.22-0.77-0.14-0.1-0.16-0.1-0.27-0.07-0.570.16-1.31-0.18-1.94-0.88-0.25-0.28-0.66-0.98-0.79-1.35-0.3-0.87-0.25-1.650.16-2.120.11-0.120.09-0.330.09-0.33-0.04-0.33-0.05-0.82-0.04-1.14v-0.3l-0.43-0.79c-0.68-1.23-1.12-2.25-1.28-3.04-0.09-0.43-0.09-0.620.02-0.770.07-0.090.28-0.180.54-0.220.66-0.12 2.09-0.01 3.690.27l0.160.030.36-0.32c0.61-0.54 1.01-0.84 1.75-1.310.77-0.48 1.64-0.89 2.62-1.2l0.32-0.10.17-0.46c0.62-1.65 1.25-2.86 1.71-3.27h0Zm-5.19 8.45c-0.70.41-1.050.61-1.30.84-1.040.93-1.43 2.39-0.99 3.710.110.330.310.680.71 1.390.410.710.61 1.060.83 1.320.92 1.05 2.37 1.45 3.68 1 0.32-0.110.68-0.31 1.38-0.72l4.02-2.34c0.7-0.41 1.05-0.61 1.3-0.84 1.04-0.93 1.43-2.390.99-3.71-0.11-0.33-0.31-0.68-0.71-1.39s-0.61-1.06-0.83-1.32c-0.92-1.05-2.37-1.45-3.68-1-0.320.11-0.670.31-1.380.72l-4.02 2.34Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M8.02 12.13c0.38-0.220.87-0.09 1.090.29l0.86 1.5c0.220.380.090.88-0.29 1.09-0.380.22-0.860.09-1.09-0.29l-0.86-1.5c-0.22-0.38-0.09-0.870.29-1.09Z" android:fillColor="#FF000000" android:fillAlpha="0.4"/>
+ <path android:pathData="M12.31 9.64c0.38-0.220.87-0.09 1.090.29l0.86 1.5c0.220.380.090.87-0.29 1.09s-0.870.09-1.09-0.29l-0.86-1.5c-0.22-0.38-0.09-0.880.29-1.09Z" android:fillColor="#FF000000" android:fillAlpha="0.4"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_codex_acp.xml b/apps/android/app/src/main/res/drawable/agent_codex_acp.xml
new file mode 100644
index 00000000..00f094c9
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_codex_acp.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- codex-acp.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M22.28 9.82a5.99 5.99 0 0 0-0.52-4.91 6.05 6.05 0 0 0-6.51-2.9A6.07 6.07 0 0 0 4.98 4.18a5.99 5.99 0 0 0-4 2.9 6.05 6.05 0 0 0 0.74 7.1 5.98 5.98 0 0 0 0.51 4.91 6.05 6.05 0 0 0 6.51 2.9A5.99 5.99 0 0 0 13.26 24a6.06 6.06 0 0 0 5.77-4.21 5.99 5.99 0 0 0 4-2.9 6.06 6.06 0 0 0-0.75-7.07zM13.26 22.43a4.48 4.48 0 0 1-2.88-1.04l0.14-0.08 4.78-2.76a0.80.8 0 0 0 0.39-0.68v-6.74l2.02 1.17a0.070.07 0 0 1 0.040.05v5.58a4.5 4.5 0 0 1-4.49 4.49zM3.6 18.3a4.47 4.47 0 0 1-0.54-3.01l0.140.09 4.78 2.76a0.770.77 0 0 0 0.78 0l5.84-3.37v2.33a0.080.08 0 0 1-0.030.06L9.74 19.95a4.5 4.5 0 0 1-6.14-1.65zM2.34 7.9a4.49 4.49 0 0 1 2.37-1.97V11.6a0.770.77 0 0 0 0.390.68l5.82 3.35-2.02 1.17a0.080.08 0 0 1-0.07 0l-4.83-2.79A4.5 4.5 0 0 1 2.34 7.87zm16.6 3.85l-5.83-3.39L15.12 7.2a0.080.08 0 0 1 0.07 0l4.83 2.79a4.49 4.49 0 0 1-0.68 8.11v-5.68a0.790.79 0 0 0-0.41-0.67zm2.01-3.02l-0.14-0.09-4.77-2.78a0.780.78 0 0 0-0.79 0L9.41 9.23V6.9a0.070.07 0 0 1 0.03-0.06l4.83-2.79a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.13l-2.02-1.16a0.080.08 0 0 1-0.04-0.06V6.08a4.5 4.5 0 0 1 7.38-3.45l-0.140.08L8.7 5.46a0.80.8 0 0 0-0.390.68zm1.1-2.37l2.6-1.5 2.61 1.5v3l-2.6 1.5-2.61-1.5z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_cortex_code.xml b/apps/android/app/src/main/res/drawable/agent_cortex_code.xml
new file mode 100644
index 00000000..7c39ac14
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_cortex_code.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- cortex-code.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="362" android:viewportHeight="362">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M1562.6,107.1h-4.2v5.2h4.2c1.9,0,3.2-0.9,3.2-2.5,0-1.8-1.2-2.6-3.2-2.6ZM1553.3,102.3h9.4c5.2,0,8.6,2.8,8.6,7.2,0,2.7-1.4,4.8-3.4,6l3.7,5.3v1.1h-5.3l-3.6-5.2h-4.2v5.2h-5.2v-19.6ZM1579.6,112.5c0-10.5-7-18.5-17.7-18.5s-17.5,7.6-17.5,18.5,7,18.5,17.5,18.5,17.7-8,17.7-18.5ZM1584,112.5c0,12.3-8.3,22.6-22.1,22.6s-21.9-10.4-21.9-22.6,8.2-22.6,21.9-22.6,22.1,10.3,22.1,22.6ZM348.2,156.4l-42.5,24.6,42.5,24.5c10.8,6.2,14.4,19.9,8.2,30.7-6.2,10.7-19.9,14.4-30.6,8.2l-76.2-44c-5.1-3-8.6-7.6-10.2-12.8-0.7-2.4-1.1-4.9-1-7.30-1.80.3-3.50.8-5.3,1.5-5.5,5.1-10.4,10.4-13.5l76.2-44c10.7-6.2,24.4-2.5,30.6,8.2,6.2,10.7,2.5,24.4-8.2,30.6ZM307.9,275.7l-76.2-43.9c-4.1-2.4-8.6-3.3-13-2.9-11.60.8-20.8,10.5-20.8,22.3v88c0,12.4,10,22.4,22.4,22.4s22.4-10.1,22.4-22.4v-49.2l42.7,24.6c10.7,6.2,24.4,2.5,30.6-8.2,6.2-10.7,2.5-24.5-8.2-30.7ZM220,189.6l-31.7,31.6c-0.90.9-2.6,1.7-4,1.7h-9.3c-1.3,0-3.1-0.8-4-1.7l-31.7-31.6c-0.9-0.9-1.6-2.7-1.6-3.9v-9.3c0-1.30.7-3.1,1.6-4l31.7-31.6c0.9-0.9,2.7-1.7,4-1.7h9.3c1.3,0,3.10.7,4,1.7l31.7,31.6c0.90.9,1.6,2.7,1.6,4v9.3c0,1.3-0.7,3-1.6,3.9ZM194.7,180.8c0-1.3-0.8-3.1-1.7-4l-9.2-9.1c-0.9-0.9-2.7-1.6-4-1.6h-0.4c-1.3,0-30.8-3.9,1.6l-9.2,9.1c-0.90.9-1.6,2.7-1.6,4v0.4c0,1.30.7,3,1.6,4l9.2,9.2c0.90.9,2.7,1.6,3.9,1.6h0.4c1.3,0,3.1-0.8,4-1.6l9.2-9.2c0.9-0.9,1.7-2.7,1.7-4v-0.4ZM51.5,86.3l76.2,44c4.1,2.4,8.6,3.3,13,2.9,11.6-0.9,20.8-10.6,20.8-22.4V22.8c0-12.4-10.1-22.4-22.4-22.4s-22.4,10.1-22.4,22.4v49.2l-42.7-24.7c-10.7-6.2-24.4-2.5-30.6,8.2-6.2,10.8-2.5,24.5,8.2,30.7ZM218.8,133.2c4.40.4,8.9-0.6,13-2.9l76.2-44c10.7-6.2,14.4-19.9,8.2-30.7-6.2-10.7-19.9-14.4-30.6-8.2l-42.7,24.7V22.8c0-12.4-10-22.4-22.4-22.4s-22.4,10.1-22.4,22.4v88c0,11.8,9.1,21.5,20.8,22.4ZM140.7,228.8c-4.4-0.4-8.90.5-13,2.9l-76.2,43.9c-10.7,6.2-14.4,20-8.2,30.7,6.2,10.7,19.9,14.4,30.6,8.2l42.7-24.6v49.2c0,12.4,10,22.4,22.4,22.4s22.4-10.1,22.4-22.4v-88c0-11.8-9.2-21.5-20.8-22.3ZM120,187.6c0.8-2.4,1.1-4.9,1-7.3-0.1-1.8-0.3-3.5-0.8-5.3-1.5-5.5-5.1-10.4-10.4-13.5l-76.2-44c-10.8-6.2-24.4-2.5-30.6,8.2-6.2,10.7-2.5,24.4,8.2,30.6l42.5,24.6-42.5,24.5c-10.8,6.2-14.4,19.9-8.2,30.7,6.2,10.7,19.9,14.4,30.6,8.2l76.2-44c5.1-3,8.6-7.6,10.2-12.8Z" android:fillColor="#FF000000" android:fillType="evenOdd"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_crow_cli.xml b/apps/android/app/src/main/res/drawable/agent_crow_cli.xml
new file mode 100644
index 00000000..e5e9bb95
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_crow_cli.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- crow-cli.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="366" android:viewportHeight="368">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="m 26,275.9 c 0.7,-9.3 8.5,-15.4 15,-21 15.4,-13 35.7,-21.9 53,-32.7 20.7,-12.9 61.6,-40.3 80,-55 0,0 21,-18.4 21,-18.4 0,0 28,-23.9 28,-23.9 10,-8.3 14.1,-11.7 25,-18.9 7.4,-4.9 19.1,-12.6 24.5,-19.3 7.2,-8.9 4.2,-18.8 -4.5,-25.4 -5.7,-4.3 -23.5,-8.9 -31,-10.7 -3.1,-0.7 -11.4,-1.6 -13.4,-3.6 -3.2,-3.4 1.7,-7 4.4,-8.4 6.6,-3.5 17.5,-5.7 25,-5.8 0,0 4,0 4,0 16.5,-0.2 18.9,-12.5 40,-12 9.3,0.2 21.2,2.5 29,7.5 7.9,5.1 12.2,11.7 17.1,19.4 6.3,10.1 12.3,21.2 14.5,33 1.4,7.9 -0.5,13.6 -0.5,21 -0.3,24.3 6.7,37.9 -2.4,63 -5.9,16.2 -14.9,35.4 -24,50 -9.3,15 -20.8,30.6 -35.6,40.6 0,0 -16,9.4 -16,9.4 -3.3,1.9 -6.2,2.9 -6.6,7 -0.7,2.8 -0.2,7.1 0,10 0,0 1.3,8 1.3,8 1.6,5.2 8.5,12.2 12.3,16 3.4,3.4 6.8,7.8 12,7.9 4.2,0.1 8.1,-2.9 12,-4.4 5.2,-2.1 11.3,-3.5 17,-3.9 6.3,-0.4 17.1,1.9 14,10.5 -2.8,-3.5 -6.1,-6.4 -11,-5.6 -2.5,0.4 -10.1,3.6 -8.1,7.1 1.2,2.1 7.7,3 10.1,3.9 6.3,2.2 10.8,5.8 14,11.6 0,0 -17,-6.3 -17,-6.3 -9.7,-2.1 -18.7,0.6 -28,3.3 5.5,3.7 8.1,5.5 12,11 -8.2,-2 -13.6,-7.5 -26,-7 -9.6,0.4 -11.9,4.1 -27,4 -9.4,-0.1 -17.8,-4.4 -27,-4 -9.4,0.4 -13.2,5.6 -21,9 3.2,-14.9 19.7,-16 32,-16 -7.3,-10.2 -20.5,-18.1 -23.3,-26 -0.7,-2 -0.7,-3.9 -0.7,-6 0,0 0,-14 0,-14 0.2,-2.4 1.1,-5.6 0,-7.7 -1.7,-2.8 -8.9,-4.6 -12,-5.5 -20.1,-6 -24.6,-0.8 -43,2 0,0 -14,2.1 -14,2.1 -9.8,1.1 -18.8,0.9 -28,5 0,0 -15,7.9 -15,7.9 -16.8,8.6 -42,22.3 -59,27.9 -9.1,3 -16.2,6.2 -26,6.3 0,0 5,-10 5,-10 -3.9,0.2 -15.8,3.1 -17.9,-0.5 -2.4,-4.1 5.3,-9 7.9,-10.9 0,0 36,-24.6 36,-24.6 0,0 -19,3.2 -19,3.2 z m 227,1.8 c -3,0.8 -11.4,3.6 -13,6.3 -0.9,1.9 -0.2,5.5 0,7.7 0,2.5 -0.1,4.6 0.6,7 1.5,5.1 11.8,17.3 16.4,19.9 3.4,1.9 15.9,0.1 20,-0.9 -4.1,-8.7 -16.7,-15.1 -22,-24 -3.4,-5.8 -0.8,-10.1 -2,-16 z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_cursor.xml b/apps/android/app/src/main/res/drawable/agent_cursor.xml
new file mode 100644
index 00000000..49c41f4c
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_cursor.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- cursor.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="466.73" android:viewportHeight="532.09">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M457.4,125.9L244.4,3c-6.8-4-15.3-4-22.1,0L9.3,125.9c-5.8,3.3-9.3,9.5-9.3,16.1v248c0,6.7,3.5,12.8,9.3,16.1l213,123c6.8,4,15.3,4,22.1,0l213-123c5.8-3.3,9.3-9.5,9.3-16.1v-248c0-6.7-3.5-12.8-9.3-16.1h-0ZM444.1,152l-205.6,356.2c-1.4,2.4-5.1,1.4-5.1-1.4v-233.2c0-4.7-2.5-9-6.5-11.3L24.9,145.7c-2.4-1.4-1.4-5.1,1.4-5.1h411.3c5.8,0,9.5,6.3,6.6,11.4h-0Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_deepagents.xml b/apps/android/app/src/main/res/drawable/agent_deepagents.xml
new file mode 100644
index 00000000..05724b20
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_deepagents.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- deepagents.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="128" android:viewportHeight="128">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M40.1 85.1C47.6 77.6 51.8 67.3 51.8 56.7C51.8 46.1 47.6 35.9 40.1 28.4L11.7 0C4.2 7.5 0 17.7 0 28.4C0 39 4.2 49.2 11.7 56.7L40.1 85.1H40.1Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M99.4 87.7C91.9 80.2 81.7 76 71.1 76C60.5 76 50.2 80.2 42.7 87.7L71.1 116.1C78.6 123.6 88.8 127.8 99.4 127.8C110.1 127.8 120.3 123.6 127.8 116.1L99.4 87.7H99.4Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M11.8 116C19.3 123.5 29.5 127.7 40.2 127.7V87.6H0.1C0.1 98.3 4.3 108.5 11.8 116Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M110.4 45.8C102.9 38.3 92.7 34 82 34C71.4 34 61.2 38.3 53.7 45.8L82 74.1L110.4 45.8Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_devin.xml b/apps/android/app/src/main/res/drawable/agent_devin.xml
new file mode 100644
index 00000000..42502ef8
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_devin.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- devin.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="263" android:viewportHeight="300">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M1.8e-10 100.8V38.6C1.9e-05 35.9 1.5 33.4 3.8 32L57.7 0.9C60 -0.4 62.9 -0.4 65.3 0.9L119.1 32C121.5 33.4 123 35.9 123 38.6V70.4C123.2 80.9 128.8 91.1 138.6 96.8C148.4 102.4 160 102.2 169.2 97.1L196.7 81.2C199.1 79.9 202 79.9 204.4 81.2L258.2 112.3C260.6 113.7 262 116.2 262 118.9V181.1C262 183.8 260.6 186.3 258.2 187.7L204.4 218.8C202 220.2 199.1 220.2 196.7 218.8L169.5 203C160.2 197.8 148.5 197.5 138.6 203.2C128.8 208.9 123.2 219.1 123 229.6V261.4C123 264.1 121.5 266.6 119.1 268L65.3 299.1C62.9 300.4 60 300.4 57.7 299.1L3.8 268C1.5 266.6 0 264.1 0 261.4V199.2C0 196.5 1.5 194 3.8 192.6L57.7 161.5C60 160.2 62.9 160.2 65.3 161.5L92.9 177.4C102.1 182.5 113.7 182.7 123.5 177.1C133.3 171.4 138.9 161.1 139.1 150.4C138.8 139.9 133.3 128.6 123.5 122.9C113.7 117.3 102.1 117.5 92.8 122.6L65.2 138.6C62.8 140 59.9 140 57.5 138.6L3.8 107.4C1.4 106 -1.9e-05 103.5 1.8e-10 100.8Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_dimcode.xml b/apps/android/app/src/main/res/drawable/agent_dimcode.xml
new file mode 100644
index 00000000..21a2fd1c
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_dimcode.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- dimcode.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M3.12 11.01H2V5.49H3.12V11.01ZM3.7 5.49C4.92 5.49 5.31 5.57 5.81 5.74C6.5 5.97 6.85 6.41 6.86 7.04V9.46C6.86 10.21 6.38 10.68 5.41 10.87C4.96 10.96 4.7 11.01 3.7 11.01V10.61C4.72 10.61 4.96 10.55 5.35 10.44C5.91 10.27 6.2 9.94 6.2 9.46V7.04C6.2 6.49 5.83 6.14 5.09 6C4.74 5.93 4.59 5.9 3.7 5.89V5.49ZM9.17 5.49V11.01H8.05V5.49H9.17ZM14 6.79V11.01H12.88V8.08L13.89 6.79H14ZM14 5.49V5.74L11.36 8.98H10.79L9.74 6.95V6.08H9.87L11.07 8.33L13.43 5.49H14Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_factory_droid.xml b/apps/android/app/src/main/res/drawable/agent_factory_droid.xml
new file mode 100644
index 00000000..84c4c957
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_factory_droid.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- factory-droid.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="900" android:viewportHeight="900">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M622 192.5a10.6 10.6 0 0 1-4.1-2 10.6 10.6 0 0 1-4-7.9 10.6 10.6 0 0 1 0.8-4.5c20.2-49.2 29.1-88.6 14.7-105-38.1-43.7-191 43.2-239.8 72.7a10.6 10.6 0 0 1-10.80 10.6 10.6 0 0 1-4.4-5.1c-20.5-49.1-42-83.2-63.9-84.7-57.9-4-104.5 165.6-118.2 220.9a10.6 10.6 0 0 1-2 4.1 10.6 10.6 0 0 1-7.9 4 10.6 10.6 0 0 1-4.4-0.8c-49.2-20.2-88.6-29.1-105-14.7-43.7 38.1 43.2 191 72.6 239.8a10.6 10.6 0 0 1 1.5 4.3 10.6 10.6 0 0 1-6.5 11c-49.1 20.5-83.2 42-84.7 63.9-3.9 57.9 165.6 104.5 220.9 118.2a10.6 10.6 0 0 1 5.7 3.6 10.6 10.6 0 0 1 2.4 6.3 10.6 10.6 0 0 1-0.8 4.4c-20.2 49.2-29.1 88.6-14.7 105 38.1 43.7 191-43.2 239.8-72.6a10.6 10.6 0 0 1 15.2 5c20.5 49.1 42 83.2 63.9 84.7 57.9 3.9 104.5-165.6 118.2-220.9a10.6 10.6 0 0 1 9.9-8 10.6 10.6 0 0 1 4.40.8c49.2 20.2 88.6 29.1 105 14.7 43.7-38.1-43.2-191-72.7-239.8a10.6 10.6 0 0 1 1.3-12.7 10.6 10.6 0 0 1 3.7-2.6c49.1-20.5 83.2-42 84.7-63.9 4-57.9-165.6-104.5-220.9-118.2Zm-66.4-55.5c11.1 19.9-46.2 152.8-88.8 245.7a8.4 8.4 0 0 1-8.2 4.9 8.4 8.4 0 0 1-7.4-6c-17.2-60.4-36.9-131.4-58-191.7a10.6 10.6 0 0 1 4.9-12.8c52.6-28.7 142.6-66.9 157.5-40.1ZM303.6 153.5c22 6.2 75.4 140.7 110.9 236.6a8.4 8.4 0 0 1-2.4 9.2 8.4 8.4 0 0 1-9.51c-54.9-30.5-119-66.8-176.5-94.5a10.6 10.6 0 0 1-5.5-12.5c16.9-57.4 53.5-148.1 83-139.7ZM137.1 343.3c19.9-11.1 152.8 46.2 245.7 88.8a8.4 8.4 0 0 1-1.2 15.7c-60.4 17.2-131.4 36.9-191.7 58a10.6 10.6 0 0 1-12.7-4.9c-28.7-52.6-66.9-142.6-40.1-157.5Zm16.4 252c6.2-22 140.7-75.4 236.6-110.9a8.4 8.4 0 0 1 10.2 11.9c-30.5 54.9-66.8 119-94.6 176.5a10.5 10.5 0 0 1-5.2 5.1 10.5 10.5 0 0 1-7.30.5c-57.4-16.8-148.1-53.5-139.7-83ZM343.3 761.9c-11.1-19.9 46.2-152.8 88.8-245.7a8.4 8.4 0 0 1 5.7-4.7 8.4 8.4 0 0 1 7.2 1.7 8.4 8.4 0 0 1 2.8 4.2c17.2 60.4 36.9 131.4 58 191.7a10.6 10.6 0 0 1-4.9 12.7c-52.6 28.7-142.6 66.9-157.4 40.1h-0.1Zm252-16.4c-22-6.2-75.4-140.7-110.9-236.6a8.4 8.4 0 0 1 11.9-10.2c54.9 30.5 119 66.8 176.5 94.6a10.5 10.5 0 0 1 5.5 12.5c-16.9 57.5-53.5 148.1-83 139.7Zm166.6-189.8c-19.9 11.1-152.8-46.2-245.7-88.8a8.4 8.4 0 0 1-3-12.9 8.4 8.4 0 0 1 4.2-2.8c60.4-17.2 131.4-36.9 191.7-58a10.6 10.6 0 0 1 12.8 4.9c28.7 52.6 66.9 142.6 40.1 157.5Zm-16.4-252c-6.2 22-140.7 75.4-236.6 110.9a8.4 8.4 0 0 1-10.2-11.9c30.5-54.9 66.8-119 94.5-176.5a10.6 10.6 0 0 1 12.5-5.5c57.4 16.9 148.1 53.5 139.7 83Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_gemini.xml b/apps/android/app/src/main/res/drawable/agent_gemini.xml
new file mode 100644
index 00000000..1ef97cf9
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_gemini.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- gemini.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M11.04 19.32Q12 21.51 12 24q0-2.490.93-4.680.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-0.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-0.96 4.68-0.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.680.96 2.190.93 3.81 2.55t2.55 3.81" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_github_copilot_cli.xml b/apps/android/app/src/main/res/drawable/agent_github_copilot_cli.xml
new file mode 100644
index 00000000..ca3441cd
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_github_copilot_cli.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- github-copilot-cli.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M8 14.28C12.07 14.28 15 11.63 15 10.96V9.32C14.94 8.77 14.42 7.82 13.61 7.49C13.6 7.42 13.59 7.36 13.58 7.3C13.55 7.14 13.52 6.96 13.46 6.76C13.64 6.32 13.69 5.81 13.69 5.31C13.69 4.55 13.58 3.76 13.08 3.14C12.57 2.5 11.77 2.15 10.7 2.03C9.64 1.92 8.72 2.06 8.12 2.7C8.08 2.75 8.03 2.8 8 2.85C7.96 2.8 7.92 2.75 7.87 2.7C7.28 2.06 6.35 1.92 5.3 2.03C4.22 2.15 3.42 2.5 2.92 3.14C2.42 3.76 2.31 4.55 2.31 5.31C2.31 5.81 2.36 6.32 2.53 6.76C2.47 6.96 2.45 7.14 2.42 7.3C2.41 7.36 2.4 7.42 2.39 7.49C1.58 7.82 1.06 8.77 1 9.32V10.96C1 11.63 3.93 14.28 8 14.28ZM10.55 3.34C9.64 3.24 9.25 3.42 9.08 3.6C8.9 3.79 8.77 4.19 8.87 5.01C8.95 5.65 9.13 6.09 9.41 6.37C9.67 6.64 10.1 6.84 10.84 6.84C11.65 6.84 11.96 6.67 12.11 6.51C12.26 6.34 12.37 6 12.37 5.31C12.37 4.64 12.27 4.22 12.05 3.95C11.85 3.69 11.44 3.44 10.55 3.34ZM6.92 3.6C6.75 3.42 6.36 3.24 5.45 3.34C4.55 3.44 4.15 3.69 3.95 3.95C3.73 4.22 3.62 4.64 3.62 5.31C3.62 6 3.74 6.34 3.89 6.51C4.03 6.67 4.35 6.84 5.15 6.84C5.9 6.84 6.33 6.64 6.59 6.37C6.86 6.09 7.05 5.65 7.13 5.01C7.23 4.19 7.09 3.79 6.92 3.6ZM8 12.98C9.99 12.98 12.01 12.01 12.37 11.72V8L12.35 7.9C11.93 8.08 11.41 8.16 10.84 8.16C9.84 8.16 9.04 7.87 8.47 7.29C8.28 7.09 8.13 6.87 8 6.64C7.87 6.87 7.72 7.09 7.52 7.29C6.95 7.87 6.16 8.16 5.15 8.16C4.58 8.16 4.07 8.08 3.64 7.9L3.62 8V11.72C3.99 12.01 6 12.98 8 12.98Z" android:fillColor="#FF000000" android:fillType="evenOdd"/>
+ <path android:pathData="M6.47 9.03C6.83 9.03 7.12 9.32 7.12 9.69V11C7.12 11.36 6.83 11.66 6.47 11.66C6.11 11.66 5.81 11.36 5.81 11V9.69C5.81 9.32 6.11 9.03 6.47 9.03Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M10.19 9.69C10.19 9.32 9.89 9.03 9.53 9.03C9.17 9.03 8.87 9.32 8.87 9.69V11C8.87 11.36 9.17 11.66 9.53 11.66C9.89 11.66 10.19 11.36 10.19 11V9.69Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_glm_acp_agent.xml b/apps/android/app/src/main/res/drawable/agent_glm_acp_agent.xml
new file mode 100644
index 00000000..2f95d2ac
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_glm_acp_agent.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- glm-acp-agent.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M8.07 1.33L6.62 3.3H0.43L1.89 1.33h6.18zM15.5 12.7L14.05 14.67h-6.16l1.45-1.97h6.16zM16 1.33L6.18 14.67H0L9.82 1.33H16z" android:fillColor="#FF000000" android:fillType="evenOdd"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_goose.xml b/apps/android/app/src/main/res/drawable/agent_goose.xml
new file mode 100644
index 00000000..7065f40e
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_goose.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- goose.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M20.91 19.39L19.52 18.24C18.76 17.62 18.12 16.87 17.62 16.03C16.92 14.87 15.96 13.89 14.81 13.17L14.25 12.85C14.06 12.71 13.93 12.51 13.91 12.27C13.9 12.12 13.93 11.99 14.02 11.87C14.31 11.46 15.9 9.75 16.17 9.52C16.53 9.22 16.92 8.98 17.29 8.7C17.34 8.66 17.4 8.62 17.45 8.58C17.45 8.58 17.45 8.58 17.45 8.58C17.57 8.48 17.68 8.38 17.77 8.27C18.2 7.77 18.2 7.34 18.2 7.34C18.2 7.34 18.2 7.34 18.2 7.34C18.15 7.23 17.98 6.88 17.65 6.72C17.95 6.71 18.28 6.82 18.43 6.97C18.61 6.69 18.73 6.5 18.92 6.19C18.96 6.11 18.98 5.98 18.9 5.9C18.9 5.9 18.9 5.9 18.9 5.9C18.9 5.9 18.9 5.9 18.9 5.9C18.9 5.9 18.9 5.9 18.89 5.89C18.89 5.89 18.89 5.89 18.89 5.89C18.89 5.89 18.89 5.89 18.89 5.89C18.89 5.89 18.89 5.89 18.89 5.89C18.89 5.89 18.88 5.88 18.88 5.88C18.88 5.88 18.87 5.87 18.87 5.87C18.87 5.87 18.87 5.87 18.86 5.87C18.86 5.86 18.86 5.86 18.86 5.86C18.86 5.86 18.85 5.86 18.85 5.86C18.85 5.86 18.85 5.85 18.85 5.85C18.85 5.85 18.85 5.85 18.85 5.85C18.85 5.85 18.85 5.85 18.84 5.84C18.84 5.84 18.84 5.84 18.84 5.84C18.84 5.84 18.84 5.84 18.84 5.84C18.77 5.76 18.63 5.78 18.56 5.83C18.15 6.07 17.76 6.32 17.4 6.55C17.4 6.55 16.98 6.54 16.48 6.97C16.36 7.06 16.26 7.17 16.17 7.29C16.17 7.29 16.17 7.29 16.16 7.3C16.12 7.35 16.08 7.4 16.04 7.45C15.76 7.82 15.52 8.22 15.23 8.57C15 8.85 13.29 10.43 12.88 10.73C12.76 10.81 12.62 10.85 12.47 10.84C12.24 10.82 12.03 10.68 11.9 10.49L11.57 9.93C10.85 8.78 9.87 7.82 8.71 7.13C7.87 6.62 7.13 5.98 6.5 5.23L5.36 3.83C5.3 3.77 5.19 3.78 5.15 3.86C5.02 4.11 4.77 4.64 4.58 5.36C4.58 5.38 4.58 5.4 4.59 5.41C4.83 5.7 5.38 6.33 6.03 6.86C6.08 6.9 6.04 6.97 5.98 6.96C5.42 6.8 4.87 6.56 4.46 6.35C4.43 6.33 4.39 6.35 4.38 6.39C4.32 6.9 4.3 7.46 4.37 8.05C4.37 8.07 4.39 8.09 4.4 8.09C4.87 8.3 5.62 8.59 6.4 8.78C6.46 8.79 6.46 8.88 6.4 8.89C5.79 9 5.15 9.03 4.63 9.02C4.59 9.02 4.57 9.06 4.58 9.09C4.68 9.46 4.82 9.83 5.01 10.21C5.09 10.38 5.17 10.55 5.26 10.71C5.27 10.74 5.3 10.75 5.34 10.75C5.77 10.73 6.28 10.69 6.81 10.6C6.9 10.58 6.94 10.7 6.87 10.75C6.51 10.98 6.14 11.19 5.78 11.36C5.74 11.38 5.72 11.44 5.75 11.48C5.96 11.76 6.19 12.03 6.44 12.28C6.44 12.28 7.67 13.54 7.7 13.64C8.42 12.91 9.6 12.1 10.9 11.39C9.15 12.8 8.18 13.85 7.7 14.44L7.35 14.92C7.18 15.17 7.02 15.43 6.9 15.71C6.47 16.64 5.76 18.51 5.76 18.51C5.7 18.65 5.75 18.8 5.84 18.89C5.84 18.89 5.85 18.89 5.85 18.9C5.85 18.9 5.85 18.9 5.85 18.9C5.95 19 6.09 19.04 6.24 18.99C6.24 18.99 8.11 18.28 9.03 17.85C9.31 17.72 9.57 17.57 9.82 17.39L10.35 17.02C10.63 16.82 11.01 16.85 11.25 17.09L12.47 18.3C12.71 18.55 12.98 18.78 13.27 18.99C13.31 19.02 13.37 19.01 13.39 18.96C13.56 18.61 13.76 18.23 14 17.88C14.05 17.8 14.17 17.85 14.15 17.94C14.06 18.46 14.01 18.98 13.99 19.41C13.99 19.44 14.01 19.47 14.03 19.49C14.2 19.58 14.36 19.66 14.53 19.74C14.91 19.92 15.29 20.06 15.65 20.17C15.69 20.18 15.72 20.15 15.72 20.12C15.72 19.59 15.74 18.96 15.86 18.34C15.87 18.29 15.95 18.29 15.96 18.34C16.15 19.13 16.45 19.87 16.65 20.34C16.66 20.36 16.67 20.37 16.69 20.37C17.28 20.44 17.85 20.42 18.36 20.36C18.39 20.36 18.41 20.32 18.4 20.28C18.19 19.87 17.94 19.32 17.79 18.76C17.77 18.7 17.84 18.67 17.88 18.71C18.42 19.37 19.05 19.91 19.33 20.15C19.34 20.16 19.36 20.17 19.38 20.16C20.1 19.97 20.64 19.72 20.89 19.59C20.97 19.55 20.98 19.44 20.91 19.39L20.91 19.39Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_grok_build.xml b/apps/android/app/src/main/res/drawable/agent_grok_build.xml
new file mode 100644
index 00000000..d7c1f77e
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_grok_build.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- grok-build.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M0.58,14.93 L0.83,14.66 C2,13.43 3.17,12.21 2.46,10.48 C1.51,8.17 2.06,5.46 3.82,3.7 C5.65,1.87 8.34,1.41 10.59,2.34 C11.09,2.52 11.52,2.79 11.86,3.03 L9.98,3.9 C8.23,3.16 6.23,3.66 5.01,4.89 C3.35,6.54 3.02,9.41 4.96,11.27 L-0.34,16 C-0.07,15.63 0.25,15.28 0.58,14.93 Z M14.04,2.29 L16.33,2.58e-12 L16.21,0.17 C14.47,2.57 13.62,3.75 14.3,6.69 C14.76,8.68 14.26,10.9 12.64,12.53 C10.59,14.58 7.31,15.04 4.61,13.19 L6.49,12.32 C8.21,13 10.1,12.7 11.45,11.34 C12.81,9.99 13.11,8.01 12.43,6.36 C12.3,6.05 11.91,5.97 11.64,6.18 L6.1,10.27 L14.04,2.29 Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_harn.xml b/apps/android/app/src/main/res/drawable/agent_harn.xml
new file mode 100644
index 00000000..552a5a97
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_harn.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- harn.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M11.2 1.4 14.6 4.8a1 1 0 0 1 0 1.4l-1.5 1.5-4.8-4.8 1.5-1.5a1 1 0 0 1 1.4 0ZM7.6 3.6l4.8 4.8-6.9 6.9a1 1 0 0 1-0.50.27l-3.40.73a0.60.6 0 0 1-0.71-0.71l0.73-3.4a1 1 0 0 1 0.27-0.5l5.6-5.6Zm-4.5 8.1-0.4 1.9 1.9-0.4-1.5-1.5Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_kilo.xml b/apps/android/app/src/main/res/drawable/agent_kilo.xml
new file mode 100644
index 00000000..135ac1e5
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_kilo.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- kilo.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="40" android:viewportHeight="40">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M28,34.67h6.67v5.33h-8.38l-3.62-3.62v-8.38h5.33v6.67ZM40,26.29l-3.62-3.62h-8.38v5.33h6.67v6.67h5.33v-8.38ZM17.33,22.67h-5.33v5.33h5.33v-5.33ZM0,36.38l3.62,3.62h13.71v-5.33H5.33v-12H0v13.71ZM33.96,12V3.62L30.34-0h-7.67v5.33h5.96v6.67h-5.96v5.33h17.33v-5.33h-6.04ZM5.33,0H0v17.33h5.33v-6h6.67v6h5.33v-6l-5.33-5.33h-6.67V0ZM17.33,0h-5.33v6h5.33V0Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_kimchi.xml b/apps/android/app/src/main/res/drawable/agent_kimchi.xml
new file mode 100644
index 00000000..ee95a292
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_kimchi.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- kimchi.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M3 1h2.5v5.5L9 1h3L8.5 6.5 12.5 13H9.5L6 8v5H3V1z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_kimi.xml b/apps/android/app/src/main/res/drawable/agent_kimi.xml
new file mode 100644
index 00000000..20452341
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_kimi.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- kimi.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M19.51 7.34C19.71 7.86 19.81 8.41 19.82 8.97C19.82 12.49 16 14.7 12.95 12.93C11.53 12.12 10.66 10.61 10.66 8.97C10.66 5.65 14.09 3.43 17.11 4.79C15.26 3.37 12.99 2.61 10.65 2.61C4.77 2.61 0.01 7.38 0 13.27C0 19.15 4.77 23.92 10.65 23.92C16.54 23.92 21.31 19.15 21.31 13.27C21.31 11.15 20.69 9.1 19.51 7.34ZM14.84 4.67C14.84 8.19 18.66 10.39 21.71 8.63C23.13 7.81 24 6.3 24 4.67C24 1.14 20.18-1.06 17.13 0.7C15.71 1.52 14.84 3.03 14.84 4.67" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_minimax_code.xml b/apps/android/app/src/main/res/drawable/agent_minimax_code.xml
new file mode 100644
index 00000000..3e8adf28
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_minimax_code.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- minimax-code.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M2 3h3l3 5 3-5h3v10h-2V6.5l-4 6-4-6V13H2V3Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_mistral_vibe.xml b/apps/android/app/src/main/res/drawable/agent_mistral_vibe.xml
new file mode 100644
index 00000000..88ab2597
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_mistral_vibe.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- mistral-vibe.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="28" android:viewportHeight="28">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M8.81 5.36H5.36V8.47H8.81V5.36Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M22.64 5.36H19.19V8.47H22.64V5.36Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M15.73 15.73H12.27V18.84H15.73V15.73Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M8.81 15.73H5.36V18.84H8.81V15.73Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M22.64 15.73H19.19V18.84H22.64V15.73Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M12.27 8.81H5.36V11.93H12.27V8.81Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M12.27 19.19H1.9V22.3H12.27V19.19Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M26.1 19.19H15.73V22.3H26.1V19.19Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M22.64 12.27H5.36V15.38H22.64V12.27Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M22.64 8.81H15.73V11.93H22.64V8.81Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_omp.xml b/apps/android/app/src/main/res/drawable/agent_omp.xml
new file mode 100644
index 00000000..379d56f4
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_omp.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- omp.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="40" android:viewportHeight="40">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M2 0H38V8H28V40H20V8H14V30H6V8H2V0Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_opencode.xml b/apps/android/app/src/main/res/drawable/agent_opencode.xml
new file mode 100644
index 00000000..9c5b25df
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_opencode.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- opencode.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M13 14H3V2H13V14ZM10.5 4.4H5.5V11.6H10.5V4.4Z" android:fillColor="#FF000000" android:fillType="evenOdd"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_pi_acp.xml b/apps/android/app/src/main/res/drawable/agent_pi_acp.xml
new file mode 100644
index 00000000..d51892e0
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_pi_acp.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- pi-acp.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M1 1H11.77V8H8.18V11.5H4.59V15H1V1ZM4.59 4.5V8H8.18V4.5H4.59Z" android:fillColor="#FF000000"/>
+ <path android:pathData="M11.77 7.46H15V15H11.77V7.46Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_poolside.xml b/apps/android/app/src/main/res/drawable/agent_poolside.xml
new file mode 100644
index 00000000..e9936d9e
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_poolside.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- poolside.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M2.64 5.51L2.19 5.29C2.1 5.47 2.13 5.68 2.26 5.84C2.4 5.99 2.61 6.04 2.8 5.98L2.64 5.51ZM5.84 6.94L5.37 7.13L5.56 7.6L6.03 7.4L5.84 6.94ZM10.74 9.44L10.26 9.57L10.39 10.06L10.88 9.92L10.74 9.44ZM2.5 8.25C2.5 7.97 2.28 7.75 2 7.75C1.72 7.75 1.5 7.97 1.5 8.25L2.5 8.25ZM13.41 10.78C12.02 13.63 8.58 14.81 5.72 13.41L5.29 14.31C8.63 15.95 12.68 14.56 14.31 11.21L13.41 10.78ZM3.09 5.72C4.48 2.87 7.92 1.69 10.78 3.09L11.21 2.19C7.87 0.55 3.82 1.94 2.19 5.29L3.09 5.72ZM10.78 3.09C13.63 4.48 14.81 7.92 13.41 10.78L14.31 11.21C15.95 7.87 14.56 3.82 11.21 2.19L10.78 3.09ZM2.8 5.98C3.02 5.9 3.55 5.85 4.09 6.01C4.61 6.16 5.11 6.48 5.37 7.13L6.3 6.75C5.89 5.76 5.12 5.26 4.37 5.05C3.64 4.84 2.91 4.88 2.47 5.03L2.8 5.98ZM6.03 7.4C6.25 7.31 6.56 7.26 6.85 7.36C7.13 7.46 7.49 7.72 7.79 8.44L8.71 8.06C8.34 7.14 7.79 6.63 7.18 6.42C6.59 6.21 6.02 6.32 5.64 6.48L6.03 7.4ZM6.27 7.19C6.8 6.27 8.19 4.19 11.17 3.11L10.82 2.17C7.53 3.36 5.99 5.67 5.4 6.69L6.27 7.19ZM14.34 10.83C14.18 10.39 13.76 9.8 13.14 9.38C12.5 8.95 11.63 8.67 10.61 8.96L10.88 9.92C11.56 9.73 12.14 9.91 12.58 10.21C13.04 10.52 13.32 10.94 13.39 11.16L14.34 10.83ZM11.23 9.31C11.12 8.93 10.88 8.39 10.36 8.02C9.83 7.64 9.08 7.5 8.12 7.77L8.38 8.73C9.12 8.53 9.54 8.66 9.78 8.84C10.05 9.03 10.19 9.32 10.26 9.57L11.23 9.31ZM11.22 9.61C11.62 8.44 12.42 5.48 11.47 2.48L10.52 2.79C11.37 5.47 10.65 8.18 10.27 9.28L11.22 9.61ZM7.8 8.03L5.06 13.64L5.95 14.08L8.7 8.47L7.8 8.03ZM5.72 13.41C3.69 12.42 2.5 10.38 2.5 8.25L1.5 8.25C1.5 10.74 2.89 13.14 5.29 14.31L5.72 13.41Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_qoder.xml b/apps/android/app/src/main/res/drawable/agent_qoder.xml
new file mode 100644
index 00000000..20dea9dd
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_qoder.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- qoder.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M8 1C4.13 1 1 4.13 1 8s3.13 7 7 7c1.5 0 2.9-0.47 4.05-1.28l1.12 1.12a0.750.75 0 1 0 1.06-1.06l-1.12-1.12A6.97 6.97 0 0 0 15 8c0-3.87-3.13-7-7-7Zm0 2c2.76 0 5 2.24 5 5s-2.24 5-5 5-5-2.24-5-5 2.24-5 5-5Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_qwen_code.xml b/apps/android/app/src/main/res/drawable/agent_qwen_code.xml
new file mode 100644
index 00000000..eaec9312
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_qwen_code.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- qwen-code.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="141.38" android:viewportHeight="140">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="m140.9 85-16.4-28.3-1.9-3.3 8.7-15a3.3 3.3 0 0 0 0-3.3l-9.6-16.7c-0.3-0.5-0.7-0.9-1.2-1.2s-1.1-0.5-1.7-0.5H82.2l-8.7-15a3.3 3.3 0 0 0-2.9-1.7H51.4c-0.6 0-1.20.2-1.70.5-0.50.3-0.90.7-1.2 1.2L32.2 30l-1.9 3.3H13c-0.6 0-1.20.2-1.70.5-0.50.3-0.90.7-1.2 1.2L0.5 51.7a3.3 3.3 0 0 0 0 3.3l18.3 31.7-8.7 15a3.3 3.3 0 0 0 0 3.3l9.6 16.7c0.30.50.70.9 1.2 1.2s1.10.5 1.70.5h36.6l8.7 15a3.4 3.4 0 0 0 2.9 1.7h19.2a3.3 3.3 0 0 0 2.9-1.7l18.3-31.7h17.3c0.6 0 1.2-0.2 1.7-0.5s0.9-0.7 1.2-1.2l9.6-16.7a3.3 3.3 0 0 0 0-3.3ZM51.4 3.3 61.1 20l-9.6 16.7h77l-9.6 16.7H45.7l-11.5-20zM57.2 120H22.6l9.6-16.7h19.2l-38.5-66.7h19.2l9.6 16.7L68.8 100l-11.6 20Zm61.6-33.3-9.6-16.7-38.5 66.7-9.6-16.7 9.6-16.7 26.9-46.7h23.1l17.3 30z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/agent_stakpak.xml b/apps/android/app/src/main/res/drawable/agent_stakpak.xml
new file mode 100644
index 00000000..f5dd75cb
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/agent_stakpak.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- stakpak.svg from the desktop app's agent logos. Generated by tools/agent_icons.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="16" android:viewportHeight="16">
+ <group android:translateX="0" android:translateY="0">
+ <path android:pathData="M6.53 4.41h5.88v3.59H9.47v3.59H3.59V8H6.53Z" android:fillColor="#FF000000"/>
+ </group>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/google_logo.xml b/apps/android/app/src/main/res/drawable/google_logo.xml
new file mode 100644
index 00000000..38c27993
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/google_logo.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Google's "G", as the desktop app's sign-in button shows it. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="48dp" android:height="48dp" android:viewportWidth="48" android:viewportHeight="48">
+ <path android:fillColor="#EA4335" android:pathData="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 android:fillColor="#4285F4" android:pathData="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 android:fillColor="#FBBC05" android:pathData="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 android:fillColor="#34A853" android:pathData="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"/>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/apps/android/app/src/main/res/drawable/ic_launcher_foreground.xml
new file mode 100644
index 00000000..8af9591f
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/ic_launcher_foreground.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generated by tools/launcher_icon.py from desktop/resources/icon.svg. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
+ <path android:fillColor="#FFFFFFFF" android:pathData="M37.275,34.090a1.792,1.792 0 1,0 3.585,0a1.792,1.792 0 1,0 -3.585,0M42.253,34.090a1.792,1.792 0 1,0 3.585,0a1.792,1.792 0 1,0 -3.585,0M47.230,34.090a1.792,1.792 0 1,0 3.585,0a1.792,1.792 0 1,0 -3.585,0M52.208,34.090a1.792,1.792 0 1,0 3.585,0a1.792,1.792 0 1,0 -3.585,0M57.195,34.090a1.782,1.782 0 1,0 3.565,0a1.782,1.782 0 1,0 -3.565,0M62.225,34.090a1.730,1.730 0 1,0 3.460,0a1.730,1.730 0 1,0 -3.460,0M67.258,34.090a1.675,1.675 0 1,0 3.350,0a1.675,1.675 0 1,0 -3.350,0M32.298,39.067a1.792,1.792 0 1,0 3.585,0a1.792,1.792 0 1,0 -3.585,0M37.275,39.067a1.792,1.792 0 1,0 3.585,0a1.792,1.792 0 1,0 -3.585,0M42.253,39.067a1.792,1.792 0 1,0 3.585,0a1.792,1.792 0 1,0 -3.585,0M47.230,39.067a1.792,1.792 0 1,0 3.585,0a1.792,1.792 0 1,0 -3.585,0M52.235,39.067a1.765,1.765 0 1,0 3.530,0a1.765,1.765 0 1,0 -3.530,0M57.265,39.067a1.712,1.712 0 1,0 3.425,0a1.712,1.712 0 1,0 -3.425,0M62.297,39.067a1.657,1.657 0 1,0 3.315,0a1.657,1.657 0 1,0 -3.315,0M67.328,39.067a1.605,1.605 0 1,0 3.210,0a1.605,1.605 0 1,0 -3.210,0M72.360,39.067a1.550,1.550 0 1,0 3.100,0a1.550,1.550 0 1,0 -3.100,0M32.298,44.045a1.792,1.792 0 1,0 3.585,0a1.792,1.792 0 1,0 -3.585,0M37.275,44.045a1.792,1.792 0 1,0 3.585,0a1.792,1.792 0 1,0 -3.585,0M42.253,44.045a1.792,1.792 0 1,0 3.585,0a1.792,1.792 0 1,0 -3.585,0M47.275,44.045a1.748,1.748 0 1,0 3.495,0a1.748,1.748 0 1,0 -3.495,0M52.307,44.045a1.692,1.692 0 1,0 3.385,0a1.692,1.692 0 1,0 -3.385,0M57.337,44.045a1.640,1.640 0 1,0 3.280,0a1.640,1.640 0 1,0 -3.280,0M62.370,44.045a1.585,1.585 0 1,0 3.170,0a1.585,1.585 0 1,0 -3.170,0M67.400,44.045a1.532,1.532 0 1,0 3.065,0a1.532,1.532 0 1,0 -3.065,0M72.432,44.045a1.478,1.478 0 1,0 2.955,0a1.478,1.478 0 1,0 -2.955,0M32.298,49.023a1.792,1.792 0 1,0 3.585,0a1.792,1.792 0 1,0 -3.585,0M37.285,49.023a1.782,1.782 0 1,0 3.565,0a1.782,1.782 0 1,0 -3.565,0M42.315,49.023a1.730,1.730 0 1,0 3.460,0a1.730,1.730 0 1,0 -3.460,0M52.377,49.023a1.623,1.623 0 1,0 3.245,0a1.623,1.623 0 1,0 -3.245,0M62.440,49.023a1.515,1.515 0 1,0 3.030,0a1.515,1.515 0 1,0 -3.030,0M67.473,49.023a1.460,1.460 0 1,0 2.920,0a1.460,1.460 0 1,0 -2.920,0M72.502,49.023a1.407,1.407 0 1,0 2.815,0a1.407,1.407 0 1,0 -2.815,0M32.325,54.000a1.765,1.765 0 1,0 3.530,0a1.765,1.765 0 1,0 -3.530,0M37.355,54.000a1.712,1.712 0 1,0 3.425,0a1.712,1.712 0 1,0 -3.425,0M42.388,54.000a1.657,1.657 0 1,0 3.315,0a1.657,1.657 0 1,0 -3.315,0M52.450,54.000a1.550,1.550 0 1,0 3.100,0a1.550,1.550 0 1,0 -3.100,0M62.512,54.000a1.442,1.442 0 1,0 2.885,0a1.442,1.442 0 1,0 -2.885,0M67.543,54.000a1.390,1.390 0 1,0 2.780,0a1.390,1.390 0 1,0 -2.780,0M72.575,54.000a1.335,1.335 0 1,0 2.670,0a1.335,1.335 0 1,0 -2.670,0M32.398,58.977a1.692,1.692 0 1,0 3.385,0a1.692,1.692 0 1,0 -3.385,0M37.427,58.977a1.640,1.640 0 1,0 3.280,0a1.640,1.640 0 1,0 -3.280,0M42.460,58.977a1.585,1.585 0 1,0 3.170,0a1.585,1.585 0 1,0 -3.170,0M47.490,58.977a1.532,1.532 0 1,0 3.065,0a1.532,1.532 0 1,0 -3.065,0M52.523,58.977a1.478,1.478 0 1,0 2.955,0a1.478,1.478 0 1,0 -2.955,0M57.553,58.977a1.425,1.425 0 1,0 2.850,0a1.425,1.425 0 1,0 -2.850,0M62.585,58.977a1.370,1.370 0 1,0 2.740,0a1.370,1.370 0 1,0 -2.740,0M67.615,58.977a1.317,1.317 0 1,0 2.635,0a1.317,1.317 0 1,0 -2.635,0M72.647,58.977a1.262,1.262 0 1,0 2.525,0a1.262,1.262 0 1,0 -2.525,0M32.468,63.955a1.623,1.623 0 1,0 3.245,0a1.623,1.623 0 1,0 -3.245,0M37.500,63.955a1.567,1.567 0 1,0 3.135,0a1.567,1.567 0 1,0 -3.135,0M42.530,63.955a1.515,1.515 0 1,0 3.030,0a1.515,1.515 0 1,0 -3.030,0M47.562,63.955a1.460,1.460 0 1,0 2.920,0a1.460,1.460 0 1,0 -2.920,0M52.593,63.955a1.407,1.407 0 1,0 2.815,0a1.407,1.407 0 1,0 -2.815,0M57.625,63.955a1.353,1.353 0 1,0 2.705,0a1.353,1.353 0 1,0 -2.705,0M62.655,63.955a1.300,1.300 0 1,0 2.600,0a1.300,1.300 0 1,0 -2.600,0M67.688,63.955a1.245,1.245 0 1,0 2.490,0a1.245,1.245 0 1,0 -2.490,0M72.718,63.955a1.192,1.192 0 1,0 2.385,0a1.192,1.192 0 1,0 -2.385,0M32.540,68.933a1.550,1.550 0 1,0 3.100,0a1.550,1.550 0 1,0 -3.100,0M37.570,68.933a1.498,1.498 0 1,0 2.995,0a1.498,1.498 0 1,0 -2.995,0M42.602,68.933a1.442,1.442 0 1,0 2.885,0a1.442,1.442 0 1,0 -2.885,0M47.633,68.933a1.390,1.390 0 1,0 2.780,0a1.390,1.390 0 1,0 -2.780,0M52.665,68.933a1.335,1.335 0 1,0 2.670,0a1.335,1.335 0 1,0 -2.670,0M57.695,68.933a1.282,1.282 0 1,0 2.565,0a1.282,1.282 0 1,0 -2.565,0M62.727,68.933a1.228,1.228 0 1,0 2.455,0a1.228,1.228 0 1,0 -2.455,0M67.758,68.933a1.175,1.175 0 1,0 2.350,0a1.175,1.175 0 1,0 -2.350,0M72.790,68.933a1.120,1.120 0 1,0 2.240,0a1.120,1.120 0 1,0 -2.240,0M37.642,73.910a1.425,1.425 0 1,0 2.850,0a1.425,1.425 0 1,0 -2.850,0M42.675,73.910a1.370,1.370 0 1,0 2.740,0a1.370,1.370 0 1,0 -2.740,0M47.705,73.910a1.317,1.317 0 1,0 2.635,0a1.317,1.317 0 1,0 -2.635,0M52.737,73.910a1.262,1.262 0 1,0 2.525,0a1.262,1.262 0 1,0 -2.525,0M57.767,73.910a1.210,1.210 0 1,0 2.420,0a1.210,1.210 0 1,0 -2.420,0M62.800,73.910a1.155,1.155 0 1,0 2.310,0a1.155,1.155 0 1,0 -2.310,0M67.830,73.910a1.103,1.103 0 1,0 2.205,0a1.103,1.103 0 1,0 -2.205,0"/>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/ic_notification.xml b/apps/android/app/src/main/res/drawable/ic_notification.xml
new file mode 100644
index 00000000..78a4e1c1
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/ic_notification.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Generated by tools/launcher_icon.py from desktop/resources/icon.svg. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:fillColor="#FFFFFFFF" android:pathData="M3.808,2.248a0.878,0.878 0 1,0 1.756,0a0.878,0.878 0 1,0 -1.756,0M6.246,2.248a0.878,0.878 0 1,0 1.756,0a0.878,0.878 0 1,0 -1.756,0M8.684,2.248a0.878,0.878 0 1,0 1.756,0a0.878,0.878 0 1,0 -1.756,0M11.122,2.248a0.878,0.878 0 1,0 1.756,0a0.878,0.878 0 1,0 -1.756,0M13.565,2.248a0.873,0.873 0 1,0 1.746,0a0.873,0.873 0 1,0 -1.746,0M16.029,2.248a0.847,0.847 0 1,0 1.695,0a0.847,0.847 0 1,0 -1.695,0M18.493,2.248a0.820,0.820 0 1,0 1.641,0a0.820,0.820 0 1,0 -1.641,0M1.370,4.686a0.878,0.878 0 1,0 1.756,0a0.878,0.878 0 1,0 -1.756,0M3.808,4.686a0.878,0.878 0 1,0 1.756,0a0.878,0.878 0 1,0 -1.756,0M6.246,4.686a0.878,0.878 0 1,0 1.756,0a0.878,0.878 0 1,0 -1.756,0M8.684,4.686a0.878,0.878 0 1,0 1.756,0a0.878,0.878 0 1,0 -1.756,0M11.136,4.686a0.864,0.864 0 1,0 1.729,0a0.864,0.864 0 1,0 -1.729,0M13.599,4.686a0.839,0.839 0 1,0 1.678,0a0.839,0.839 0 1,0 -1.678,0M16.064,4.686a0.812,0.812 0 1,0 1.624,0a0.812,0.812 0 1,0 -1.624,0M18.528,4.686a0.786,0.786 0 1,0 1.572,0a0.786,0.786 0 1,0 -1.572,0M20.993,4.686a0.759,0.759 0 1,0 1.518,0a0.759,0.759 0 1,0 -1.518,0M1.370,7.124a0.878,0.878 0 1,0 1.756,0a0.878,0.878 0 1,0 -1.756,0M3.808,7.124a0.878,0.878 0 1,0 1.756,0a0.878,0.878 0 1,0 -1.756,0M6.246,7.124a0.878,0.878 0 1,0 1.756,0a0.878,0.878 0 1,0 -1.756,0M8.706,7.124a0.856,0.856 0 1,0 1.712,0a0.856,0.856 0 1,0 -1.712,0M11.171,7.124a0.829,0.829 0 1,0 1.658,0a0.829,0.829 0 1,0 -1.658,0M13.635,7.124a0.803,0.803 0 1,0 1.607,0a0.803,0.803 0 1,0 -1.607,0M16.100,7.124a0.776,0.776 0 1,0 1.553,0a0.776,0.776 0 1,0 -1.553,0M18.563,7.124a0.751,0.751 0 1,0 1.501,0a0.751,0.751 0 1,0 -1.501,0M21.028,7.124a0.724,0.724 0 1,0 1.447,0a0.724,0.724 0 1,0 -1.447,0M1.370,9.562a0.878,0.878 0 1,0 1.756,0a0.878,0.878 0 1,0 -1.756,0M3.813,9.562a0.873,0.873 0 1,0 1.746,0a0.873,0.873 0 1,0 -1.746,0M6.277,9.562a0.847,0.847 0 1,0 1.695,0a0.847,0.847 0 1,0 -1.695,0M11.205,9.562a0.795,0.795 0 1,0 1.589,0a0.795,0.795 0 1,0 -1.589,0M16.134,9.562a0.742,0.742 0 1,0 1.484,0a0.742,0.742 0 1,0 -1.484,0M18.599,9.562a0.715,0.715 0 1,0 1.430,0a0.715,0.715 0 1,0 -1.430,0M21.062,9.562a0.689,0.689 0 1,0 1.379,0a0.689,0.689 0 1,0 -1.379,0M1.384,12.000a0.864,0.864 0 1,0 1.729,0a0.864,0.864 0 1,0 -1.729,0M3.847,12.000a0.839,0.839 0 1,0 1.678,0a0.839,0.839 0 1,0 -1.678,0M6.312,12.000a0.812,0.812 0 1,0 1.624,0a0.812,0.812 0 1,0 -1.624,0M11.241,12.000a0.759,0.759 0 1,0 1.518,0a0.759,0.759 0 1,0 -1.518,0M16.169,12.000a0.707,0.707 0 1,0 1.413,0a0.707,0.707 0 1,0 -1.413,0M18.633,12.000a0.681,0.681 0 1,0 1.362,0a0.681,0.681 0 1,0 -1.362,0M21.098,12.000a0.654,0.654 0 1,0 1.308,0a0.654,0.654 0 1,0 -1.308,0M1.419,14.438a0.829,0.829 0 1,0 1.658,0a0.829,0.829 0 1,0 -1.658,0M3.883,14.438a0.803,0.803 0 1,0 1.607,0a0.803,0.803 0 1,0 -1.607,0M6.348,14.438a0.776,0.776 0 1,0 1.553,0a0.776,0.776 0 1,0 -1.553,0M8.811,14.438a0.751,0.751 0 1,0 1.501,0a0.751,0.751 0 1,0 -1.501,0M11.276,14.438a0.724,0.724 0 1,0 1.447,0a0.724,0.724 0 1,0 -1.447,0M13.740,14.438a0.698,0.698 0 1,0 1.396,0a0.698,0.698 0 1,0 -1.396,0M16.205,14.438a0.671,0.671 0 1,0 1.342,0a0.671,0.671 0 1,0 -1.342,0M18.669,14.438a0.645,0.645 0 1,0 1.291,0a0.645,0.645 0 1,0 -1.291,0M21.133,14.438a0.618,0.618 0 1,0 1.237,0a0.618,0.618 0 1,0 -1.237,0M1.453,16.876a0.795,0.795 0 1,0 1.589,0a0.795,0.795 0 1,0 -1.589,0M3.918,16.876a0.768,0.768 0 1,0 1.536,0a0.768,0.768 0 1,0 -1.536,0M6.382,16.876a0.742,0.742 0 1,0 1.484,0a0.742,0.742 0 1,0 -1.484,0M8.847,16.876a0.715,0.715 0 1,0 1.430,0a0.715,0.715 0 1,0 -1.430,0M11.311,16.876a0.689,0.689 0 1,0 1.379,0a0.689,0.689 0 1,0 -1.379,0M13.776,16.876a0.662,0.662 0 1,0 1.325,0a0.662,0.662 0 1,0 -1.325,0M16.239,16.876a0.637,0.637 0 1,0 1.273,0a0.637,0.637 0 1,0 -1.273,0M18.704,16.876a0.610,0.610 0 1,0 1.220,0a0.610,0.610 0 1,0 -1.220,0M21.168,16.876a0.584,0.584 0 1,0 1.168,0a0.584,0.584 0 1,0 -1.168,0M1.489,19.314a0.759,0.759 0 1,0 1.518,0a0.759,0.759 0 1,0 -1.518,0M3.953,19.314a0.733,0.733 0 1,0 1.467,0a0.733,0.733 0 1,0 -1.467,0M6.418,19.314a0.707,0.707 0 1,0 1.413,0a0.707,0.707 0 1,0 -1.413,0M8.881,19.314a0.681,0.681 0 1,0 1.362,0a0.681,0.681 0 1,0 -1.362,0M11.346,19.314a0.654,0.654 0 1,0 1.308,0a0.654,0.654 0 1,0 -1.308,0M13.810,19.314a0.628,0.628 0 1,0 1.256,0a0.628,0.628 0 1,0 -1.256,0M16.275,19.314a0.601,0.601 0 1,0 1.202,0a0.601,0.601 0 1,0 -1.202,0M18.738,19.314a0.576,0.576 0 1,0 1.151,0a0.576,0.576 0 1,0 -1.151,0M21.203,19.314a0.549,0.549 0 1,0 1.097,0a0.549,0.549 0 1,0 -1.097,0M3.988,21.752a0.698,0.698 0 1,0 1.396,0a0.698,0.698 0 1,0 -1.396,0M6.453,21.752a0.671,0.671 0 1,0 1.342,0a0.671,0.671 0 1,0 -1.342,0M8.917,21.752a0.645,0.645 0 1,0 1.291,0a0.645,0.645 0 1,0 -1.291,0M11.382,21.752a0.618,0.618 0 1,0 1.237,0a0.618,0.618 0 1,0 -1.237,0M13.845,21.752a0.593,0.593 0 1,0 1.185,0a0.593,0.593 0 1,0 -1.185,0M16.310,21.752a0.566,0.566 0 1,0 1.131,0a0.566,0.566 0 1,0 -1.131,0M18.774,21.752a0.540,0.540 0 1,0 1.080,0a0.540,0.540 0 1,0 -1.080,0"/>
+</vector>
diff --git a/apps/android/app/src/main/res/drawable/splash_blank.xml b/apps/android/app/src/main/res/drawable/splash_blank.xml
new file mode 100644
index 00000000..befdb782
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/splash_blank.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- The system splash shows nothing; Codync's own launch splash (the app-icon bot) follows it, as on iOS. -->
+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
+ <solid android:color="@android:color/transparent" />
+</shape>
diff --git a/apps/android/app/src/main/res/drawable/widget_background.xml b/apps/android/app/src/main/res/drawable/widget_background.xml
new file mode 100644
index 00000000..bcda23d8
--- /dev/null
+++ b/apps/android/app/src/main/res/drawable/widget_background.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shape xmlns:android="http://schemas.android.com/apk/res/android">
+ <solid android:color="@color/widget_background" />
+ <corners android:radius="22dp" />
+</shape>
diff --git a/apps/android/app/src/main/res/layout/widget_loading.xml b/apps/android/app/src/main/res/layout/widget_loading.xml
new file mode 100644
index 00000000..f160dfe2
--- /dev/null
+++ b/apps/android/app/src/main/res/layout/widget_loading.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<TextView xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp"
+ android:background="@drawable/widget_background" android:textColor="@color/widget_foreground"
+ android:textSize="17sp" android:text="@string/widget_loading" />
diff --git a/apps/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/apps/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 00000000..0b0d585e
--- /dev/null
+++ b/apps/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_launcher_background"/>
+ <foreground android:drawable="@drawable/ic_launcher_foreground"/>
+ <monochrome android:drawable="@drawable/ic_launcher_foreground"/>
+</adaptive-icon>
diff --git a/apps/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/apps/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
new file mode 100644
index 00000000..0b0d585e
--- /dev/null
+++ b/apps/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_launcher_background"/>
+ <foreground android:drawable="@drawable/ic_launcher_foreground"/>
+ <monochrome android:drawable="@drawable/ic_launcher_foreground"/>
+</adaptive-icon>
diff --git a/apps/android/app/src/main/res/values-night/launcher.xml b/apps/android/app/src/main/res/values-night/launcher.xml
new file mode 100644
index 00000000..323b3880
--- /dev/null
+++ b/apps/android/app/src/main/res/values-night/launcher.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="launch_background">#0A0A0A</color>
+</resources>
diff --git a/apps/android/app/src/main/res/values-night/widget.xml b/apps/android/app/src/main/res/values-night/widget.xml
new file mode 100644
index 00000000..073a299f
--- /dev/null
+++ b/apps/android/app/src/main/res/values-night/widget.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="widget_background">#1C1C1C</color>
+ <color name="widget_foreground">#EEEEEE</color>
+ <color name="widget_secondary">#A5A5A5</color>
+ <color name="widget_warning">#F0A030</color>
+ <color name="widget_track">#444444</color>
+</resources>
diff --git a/apps/android/app/src/main/res/values-v31/styles.xml b/apps/android/app/src/main/res/values-v31/styles.xml
new file mode 100644
index 00000000..534d6289
--- /dev/null
+++ b/apps/android/app/src/main/res/values-v31/styles.xml
@@ -0,0 +1,7 @@
+<resources>
+ <!-- Android 12+ shows the system splash: the ground color only, Codync draws its own launch screen. -->
+ <style name="Theme.Codync" parent="Theme.Codync.Base">
+ <item name="android:windowSplashScreenBackground">@color/launch_background</item>
+ <item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_blank</item>
+ </style>
+</resources>
diff --git a/apps/android/app/src/main/res/values/launcher.xml b/apps/android/app/src/main/res/values/launcher.xml
new file mode 100644
index 00000000..62a55775
--- /dev/null
+++ b/apps/android/app/src/main/res/values/launcher.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <!-- The iOS and desktop app icon's black square. -->
+ <color name="ic_launcher_background">#000000</color>
+ <!-- iOS LaunchBackground: the app's ground behind the launch splash. -->
+ <color name="launch_background">#FFFFFF</color>
+</resources>
diff --git a/apps/android/app/src/main/res/values/styles.xml b/apps/android/app/src/main/res/values/styles.xml
new file mode 100644
index 00000000..ec53e292
--- /dev/null
+++ b/apps/android/app/src/main/res/values/styles.xml
@@ -0,0 +1,10 @@
+<resources>
+ <style name="Theme.Codync.Base" parent="android:style/Theme.Material.Light.NoActionBar">
+ <item name="android:fontFamily">sans</item>
+ <item name="android:windowLightStatusBar">true</item>
+ <item name="android:windowActionModeOverlay">true</item>
+ <item name="android:windowBackground">@color/launch_background</item>
+ </style>
+ <style name="Theme.Codync" parent="Theme.Codync.Base" />
+</resources>
+
diff --git a/apps/android/app/src/main/res/values/widget.xml b/apps/android/app/src/main/res/values/widget.xml
new file mode 100644
index 00000000..ba8a0036
--- /dev/null
+++ b/apps/android/app/src/main/res/values/widget.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="widget_loading">Codync · Open the app for the latest report</string>
+ <string name="widget_bots_description">Latest bot status and unread counts</string>
+ <string name="widget_team_description">Four bots as characters, the ones that need you first</string>
+ <string name="widget_provider_description">Latest limits from your selected provider</string>
+ <color name="widget_background">#F8F8F8</color>
+ <color name="widget_foreground">#111111</color>
+ <color name="widget_secondary">#666666</color>
+ <color name="widget_warning">#BF791F</color>
+ <color name="widget_track">#DDDDDD</color>
+</resources>
diff --git a/apps/android/app/src/main/res/xml/data_extraction_rules.xml b/apps/android/app/src/main/res/xml/data_extraction_rules.xml
new file mode 100644
index 00000000..b853a8d2
--- /dev/null
+++ b/apps/android/app/src/main/res/xml/data_extraction_rules.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<data-extraction-rules>
+ <cloud-backup>
+ <exclude domain="root" path="." />
+ <exclude domain="file" path="." />
+ <exclude domain="database" path="." />
+ <exclude domain="sharedpref" path="." />
+ <exclude domain="external" path="." />
+ <exclude domain="device_root" path="." />
+ <exclude domain="device_file" path="." />
+ <exclude domain="device_database" path="." />
+ <exclude domain="device_sharedpref" path="." />
+ </cloud-backup>
+ <device-transfer>
+ <exclude domain="root" path="." />
+ <exclude domain="file" path="." />
+ <exclude domain="database" path="." />
+ <exclude domain="sharedpref" path="." />
+ <exclude domain="external" path="." />
+ <exclude domain="device_root" path="." />
+ <exclude domain="device_file" path="." />
+ <exclude domain="device_database" path="." />
+ <exclude domain="device_sharedpref" path="." />
+ </device-transfer>
+</data-extraction-rules>
diff --git a/apps/android/app/src/main/res/xml/shared_file_paths.xml b/apps/android/app/src/main/res/xml/shared_file_paths.xml
new file mode 100644
index 00000000..43bb0937
--- /dev/null
+++ b/apps/android/app/src/main/res/xml/shared_file_paths.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<paths xmlns:android="http://schemas.android.com/apk/res/android">
+ <cache-path name="attachments" path="shared-attachments/" />
+</paths>
diff --git a/apps/android/app/src/main/res/xml/widget_bots.xml b/apps/android/app/src/main/res/xml/widget_bots.xml
new file mode 100644
index 00000000..96117c04
--- /dev/null
+++ b/apps/android/app/src/main/res/xml/widget_bots.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ android:minWidth="110dp" android:minHeight="110dp" android:minResizeWidth="110dp" android:minResizeHeight="110dp"
+ android:targetCellWidth="4" android:targetCellHeight="2" android:resizeMode="horizontal|vertical"
+ android:updatePeriodMillis="1800000" android:initialLayout="@layout/widget_loading"
+ android:description="@string/widget_bots_description" android:previewLayout="@layout/widget_loading"
+ android:widgetCategory="home_screen" />
diff --git a/apps/android/app/src/main/res/xml/widget_provider.xml b/apps/android/app/src/main/res/xml/widget_provider.xml
new file mode 100644
index 00000000..15b15a6a
--- /dev/null
+++ b/apps/android/app/src/main/res/xml/widget_provider.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ android:minWidth="110dp" android:minHeight="110dp" android:minResizeWidth="110dp" android:minResizeHeight="110dp"
+ android:targetCellWidth="2" android:targetCellHeight="2" android:resizeMode="horizontal|vertical"
+ android:updatePeriodMillis="1800000" android:initialLayout="@layout/widget_loading"
+ android:description="@string/widget_provider_description" android:previewLayout="@layout/widget_loading"
+ android:configure="com.codync.android.WidgetConfigurationActivity" android:widgetFeatures="reconfigurable|configuration_optional"
+ android:widgetCategory="home_screen" />
diff --git a/apps/android/app/src/main/res/xml/widget_team.xml b/apps/android/app/src/main/res/xml/widget_team.xml
new file mode 100644
index 00000000..a96a5e99
--- /dev/null
+++ b/apps/android/app/src/main/res/xml/widget_team.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ android:minWidth="110dp" android:minHeight="110dp" android:minResizeWidth="110dp" android:minResizeHeight="110dp"
+ android:targetCellWidth="2" android:targetCellHeight="2" android:resizeMode="horizontal|vertical"
+ android:updatePeriodMillis="1800000" android:initialLayout="@layout/widget_loading"
+ android:description="@string/widget_team_description" android:previewLayout="@layout/widget_loading"
+ android:configure="com.codync.android.WidgetConfigurationActivity" android:widgetFeatures="reconfigurable|configuration_optional"
+ android:widgetCategory="home_screen" />
diff --git a/apps/android/app/src/releaseAcceptance/kotlin/com/codync/android/ReleaseWidgetSmoke.kt b/apps/android/app/src/releaseAcceptance/kotlin/com/codync/android/ReleaseWidgetSmoke.kt
new file mode 100644
index 00000000..e588d1c4
--- /dev/null
+++ b/apps/android/app/src/releaseAcceptance/kotlin/com/codync/android/ReleaseWidgetSmoke.kt
@@ -0,0 +1,98 @@
+package com.codync.android
+
+import android.app.Instrumentation
+import android.appwidget.AppWidgetHost
+import android.appwidget.AppWidgetManager
+import android.content.ComponentName
+import android.os.Bundle
+import android.util.AtomicFile
+import android.view.View
+import android.view.ViewGroup
+import android.widget.FrameLayout
+import android.widget.TextView
+import androidx.glance.appwidget.GlanceAppWidgetManager
+import com.codync.android.core.*
+import java.io.File
+import java.util.UUID
+import kotlinx.coroutines.*
+
+/** No JUnit/Clerk keep rules: actual minified Glance → Android RemoteViews. */
+object ReleaseWidgetSmoke {
+ @JvmStatic fun run(instrumentation: Instrumentation) {
+ val context = instrumentation.targetContext
+ check(PushPreferences.activeUser(context) == null)
+ val original = AtomicFile(File(context.noBackupFilesDir, "widget-owner.json"))
+ val bytes = if (original.baseFile.exists()) original.readFully() else null
+ val computer = LocalStore(context).computers().single()
+ check(computer.id == "9ESVKkTXlLyIExxnW7-PIg")
+ val local = LocalStore(context, "widget-r8-" + UUID.randomUUID())
+ val manager = AppWidgetManager.getInstance(context)
+ val host = AppWidgetHost(context, 49372)
+ val ids = mutableListOf<Int>()
+ try {
+ local.saveComputers(listOf(computer))
+ val owner = WidgetStore.activate(context, local.contextId)
+ WidgetStore.publish(context, owner, computer, listOf(Bot("r8-bot", "R8 bot", status = "needsInput")), UsageReport(listOf(
+ UsageProvider("codex", "Codex", listOf(UsageWindow("daily", "Daily", 24.0))))), true, true)
+ val widgetId = host.allocateAppWidgetId(); ids.add(widgetId)
+ val botId = host.allocateAppWidgetId(); ids.add(botId)
+ instrumentation.uiAutomation.adoptShellPermissionIdentity(android.Manifest.permission.BIND_APPWIDGET)
+ try {
+ check(manager.bindAppWidgetIdIfAllowed(widgetId, ComponentName(context, ProviderWidgetReceiver::class.java)))
+ check(manager.bindAppWidgetIdIfAllowed(botId, ComponentName(context, BotsWidgetReceiver::class.java)))
+ }
+ finally { instrumentation.uiAutomation.dropShellPermissionIdentity() }
+ manager.updateAppWidgetOptions(widgetId, Bundle().apply {
+ putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 300); putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, 300)
+ putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, 160); putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, 160)
+ })
+ WidgetStore.selectProvider(context, widgetId, "codex")
+ lateinit var root: FrameLayout
+ lateinit var bots: FrameLayout
+ instrumentation.runOnMainSync {
+ root = FrameLayout(context)
+ host.startListening()
+ val view = host.createView(context, widgetId, requireNotNull(manager.getAppWidgetInfo(widgetId)))
+ root.addView(view)
+ bots = FrameLayout(context)
+ bots.addView(host.createView(context, botId, requireNotNull(manager.getAppWidgetInfo(botId))))
+ }
+ val glanceManager = GlanceAppWidgetManager(context)
+ val glance = glanceManager.getGlanceIdBy(widgetId)
+ val botGlance = glanceManager.getGlanceIdBy(botId)
+ runBlocking {
+ val providers = glanceManager.getGlanceIds(ProviderWidget::class.java)
+ check(glance in providers && botGlance !in providers) { "Minified widget kinds lost their distinct identities" }
+ CodyncWidgets.update(context)
+ }
+ runBlocking { withTimeout(30_000) {
+ while (true) {
+ var content = emptyList<String>()
+ var botContent = emptyList<String>()
+ instrumentation.runOnMainSync {
+ fun text(view: View): List<String> = buildList {
+ if (view is TextView) add(view.text.toString())
+ if (view is ViewGroup) for (i in 0 until view.childCount) addAll(text(view.getChildAt(i)))
+ }
+ content = text(root)
+ botContent = text(bots)
+ }
+ if ("Codex" in content && "Daily" in content && "24%" in content && "Bots" in botContent && "R8 bot" in botContent) break
+ delay(100)
+ }
+ } }
+ } finally {
+ instrumentation.uiAutomation.dropShellPermissionIdentity()
+ val active = WidgetStore.owner(context)
+ if (active?.context == local.contextId) WidgetStore.retire(context, active)
+ ids.forEach { host.deleteAppWidgetId(it) }; WidgetStore.remove(context, ids.toIntArray())
+ host.stopListening(); host.deleteHost()
+ runBlocking { WidgetRefreshWorker.stop(context) }
+ local.erase()
+ if (bytes == null) original.delete() else {
+ val output = original.startWrite(); output.write(bytes); original.finishWrite(output)
+ }
+ WidgetStore.changes.value++
+ }
+ }
+}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt
new file mode 100644
index 00000000..dd910baa
--- /dev/null
+++ b/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt
@@ -0,0 +1,18 @@
+package com.codync.android
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class AnalyticsTest {
+ @Test fun `the computer tag matches the host's hash`() {
+ // sha256("codync-analytics:<id>")[0..8], as host/src/analytics.rs and the iPhone compute it.
+ assertEquals("fbfcd4f4fe9f876c", Analytics.computerTag("tZ1WMzsVltt-fj7mUDwZsg"))
+ }
+
+ @Test fun `a crash keeps its type and Codync frames but never its message`() {
+ val error = IllegalStateException("secret prompt text")
+ val properties = CrashReports.properties(error).toString()
+ assert("IllegalStateException" in properties)
+ assert("secret prompt text" !in properties)
+ }
+}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt
new file mode 100644
index 00000000..12bfd4f5
--- /dev/null
+++ b/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt
@@ -0,0 +1,43 @@
+package com.codync.android
+
+import com.codync.android.core.*
+import org.junit.Assert.*
+import org.junit.Test
+
+class ConnectionPresentationTest {
+ private val computer = Computer("fixture", "Computer", "fixture")
+ private fun state(link: LinkState, loaded: Boolean = false) = AppState(
+ account = AccountState(configured = false), loading = false, setupComplete = true,
+ computers = listOf(computer), connection = link, actualConnection = link, rosterLoaded = loaded)
+
+ @Test fun anUnreachableComputerIsNotAnEmptyRoster() {
+ for (loaded in listOf(false, true)) {
+ val empty = emptyRoster(state(LinkState.ComputerOffline(null), loaded), "", false)
+ assertEquals("Computer offline", empty.title)
+ assertFalse(empty.canCreate)
+ assertNotNull(empty.detail)
+ }
+ }
+
+ @Test fun accessAndCompatibilityFailuresKeepTheirActionableMessage() {
+ for ((status, title) in listOf(403 to "Access denied", 426 to "Update required", 500 to "Disconnected")) {
+ val link = LinkState.Failed("Actionable host error", status)
+ assertEquals(title, connectionLabel(link))
+ val empty = emptyRoster(state(link), "", false)
+ assertEquals(title, empty.title)
+ assertEquals(link.message, empty.detail)
+ assertFalse(empty.canCreate)
+ }
+ }
+
+ @Test fun creationWaitsForAnAuthoritativeOnlineRoster() {
+ val online = state(LinkState.Ready(HostRoute.Direct))
+ assertEquals("Syncing bots…", emptyRoster(online, "", false).title)
+ val loaded = online.copy(rosterLoaded = true)
+ assertTrue(emptyRoster(loaded, "", false).canCreate)
+ assertFalse(emptyRoster(loaded.copy(actualConnection = LinkState.Connecting), "", false).canCreate)
+ assertEquals("No matching bots", emptyRoster(loaded, "missing", false).title)
+ assertEquals("No hidden bots", emptyRoster(loaded, "", true).title)
+ assertFalse(emptyRoster(loaded, "", true).canCreate)
+ }
+}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/SlashCommandsTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/SlashCommandsTest.kt
new file mode 100644
index 00000000..ac55439a
--- /dev/null
+++ b/apps/android/app/src/test/kotlin/com/codync/android/SlashCommandsTest.kt
@@ -0,0 +1,26 @@
+package com.codync.android
+
+import com.codync.android.core.Bot
+import com.codync.android.core.InstalledSkill
+import org.junit.Assert.*
+import org.junit.Test
+
+class SlashCommandsTest {
+ @Test fun `only a leading slash word lists commands, and skills need a host that runs them`() {
+ assertEquals("ne", SlashCommands.query("/ne"))
+ assertNull(SlashCommands.query("/new session"))
+ assertNull(SlashCommands.query("hi /new"))
+ val bot = Bot("b", "Bot", skills = listOf("review"))
+ val skills = listOf(InstalledSkill("review", "Review", "Reads diffs", "src", "/p"), InstalledSkill("other", "Other", "", "src", "/q"))
+ assertEquals(listOf("new", "review"), SlashCommands.list(bot, "", skills, "2.14.1").map { it.name }.filter { it != "fast" })
+ assertEquals(listOf("new"), SlashCommands.list(bot, "", skills, "2.9.3").map { it.name }.filter { it != "fast" })
+ assertEquals("new", SlashCommands.builtIn(bot, " /new ")?.name)
+ assertTrue(SlashCommands.list(Bot("g", "Team", kind = "group"), "", skills, null).isEmpty())
+ }
+
+ @Test fun `mentions start after a space and stay short`() {
+ assertEquals("Re", mentionQuery("hi @Re"))
+ assertNull(mentionQuery("mail@host"))
+ assertNull(mentionQuery("@" + "x".repeat(25)))
+ }
+}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/UndecodableTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/UndecodableTest.kt
new file mode 100644
index 00000000..8f2466b9
--- /dev/null
+++ b/apps/android/app/src/test/kotlin/com/codync/android/UndecodableTest.kt
@@ -0,0 +1,13 @@
+package com.codync.android
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class UndecodableTest {
+ @Test fun `an unreadable event fetches everything again once, then waits for an update or passes it over`() {
+ assertEquals(Undecodable.Rewind, undecodable(alreadyRewound = false, hostNewer = true))
+ assertEquals(Undecodable.Rewind, undecodable(alreadyRewound = false, hostNewer = false))
+ assertEquals(Undecodable.AwaitUpdate, undecodable(alreadyRewound = true, hostNewer = true))
+ assertEquals(Undecodable.Skip, undecodable(alreadyRewound = true, hostNewer = false))
+ }
+}
diff --git a/apps/android/build.gradle.kts b/apps/android/build.gradle.kts
new file mode 100644
index 00000000..003fc746
--- /dev/null
+++ b/apps/android/build.gradle.kts
@@ -0,0 +1,8 @@
+plugins {
+ alias(libs.plugins.android.application) apply false
+ alias(libs.plugins.android.library) apply false
+ alias(libs.plugins.kotlin.jvm) apply false
+ alias(libs.plugins.kotlin.serialization) apply false
+ alias(libs.plugins.kotlin.compose) apply false
+ alias(libs.plugins.google.services) apply false
+}
diff --git a/apps/android/core/build.gradle.kts b/apps/android/core/build.gradle.kts
new file mode 100644
index 00000000..3e727470
--- /dev/null
+++ b/apps/android/core/build.gradle.kts
@@ -0,0 +1,31 @@
+plugins {
+ alias(libs.plugins.kotlin.jvm)
+ alias(libs.plugins.kotlin.serialization)
+}
+
+kotlin {
+ jvmToolchain(21)
+ compilerOptions.jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
+}
+
+java {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+}
+
+dependencies {
+ implementation(libs.coroutines.core)
+ implementation(libs.serialization.json)
+ implementation(libs.okhttp)
+ implementation(libs.bouncycastle)
+ implementation(libs.zxing)
+ testImplementation(libs.junit)
+ testImplementation(libs.coroutines.test)
+ testImplementation(libs.mockwebserver)
+}
+
+tasks.test {
+ // Consume upstream vectors in place; never copy or regenerate them for Android.
+ systemProperty("codync.vectors", rootProject.file("../../docs/reference/fixtures/remote-relay-vectors.json").absolutePath)
+ inputs.file(rootProject.file("../../docs/reference/fixtures/remote-relay-vectors.json"))
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSettings.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSettings.kt
new file mode 100644
index 00000000..87cfe2f0
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSettings.kt
@@ -0,0 +1,26 @@
+package com.codync.android.core
+
+import kotlinx.serialization.Serializable
+
+/** A model setting (effort, fast…) and the values the agent accepts. */
+@Serializable data class ModelOption(val id: String, val name: String, val values: List<ModelOptionValue> = emptyList(), val default: String? = null)
+@Serializable data class ModelOptionValue(val id: String, val name: String)
+@Serializable data class AgentModel(val id: String, val name: String, val description: String? = null, val options: List<ModelOption>? = null)
+/** `fastMode`: the agent offers Fast mode (absent on older hosts). */
+@Serializable data class AgentModels(val models: List<AgentModel>, val currentModelId: String? = null, val fastMode: Boolean? = null) {
+ val agentDefault: AgentModel? get() = models.firstOrNull { it.name.lowercase().startsWith("default") }
+ fun options(selected: String?): List<ModelChoice> {
+ val default = agentDefault
+ val available = models.filter { it.id != default?.id }
+ val current = available.firstOrNull { it.id == currentModelId }
+ val choices = mutableListOf(ModelChoice(null, default?.name ?: current?.let { "Default · ${it.name}" } ?: "Default", default?.description))
+ choices += available.map { ModelChoice(it.id, it.name, it.description) }
+ if (!selected.isNullOrBlank() && selected != default?.id && available.none { it.id == selected }) choices += ModelChoice(selected, selected)
+ return choices
+ }
+ fun normalize(selected: String?): String? = selected?.takeIf { it.isNotBlank() && it != agentDefault?.id }
+}
+data class ModelChoice(val id: String?, val name: String, val description: String? = null)
+
+@Serializable data class DirListing(val path: String, val parent: String? = null, val isGit: Boolean = false, val dirs: List<DirItem>)
+@Serializable data class DirItem(val name: String, val path: String, val isGit: Boolean = false)
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSetup.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSetup.kt
new file mode 100644
index 00000000..6ab78c9c
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSetup.kt
@@ -0,0 +1,171 @@
+package com.codync.android.core
+
+import java.io.IOException
+import java.util.Base64
+import kotlinx.coroutines.*
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.*
+
+@Serializable data class AgentBackend(val id: String, val name: String, val installed: Boolean = false,
+ val available: Boolean = false, val description: String? = null, val installHint: String = "",
+ val signedIn: Boolean? = null, val canInstall: Boolean = false, val curated: Boolean = false,
+ val registry: String? = null, val node: String? = null) {
+ /** Runs on Node.js and the computer has none yet. */
+ val needsNode: Boolean get() = node == "missing"
+}
+@Serializable data class AgentAuth(val signedIn: Boolean? = null, val detail: String? = null,
+ val methods: List<AgentAuthMethod> = emptyList(), val savedEnv: List<String> = emptyList(), val login: Boolean = false)
+@Serializable data class AgentAuthMethod(val id: String, val name: String, val description: String? = null,
+ val kind: String? = null, val vars: List<AgentAuthVar> = emptyList(), val link: String? = null) {
+ fun complete(values: Map<String, String>, saved: List<String>): Boolean = vars.all {
+ it.optional || values[it.name]?.isNotBlank() == true || it.name in saved
+ }
+}
+@Serializable data class AgentAuthVar(val name: String, val label: String, val secret: Boolean = true, val optional: Boolean = false)
+
+sealed interface TerminalEvent {
+ data class Output(val bytes: ByteArray) : TerminalEvent
+ data class Exit(val code: Int) : TerminalEvent
+ companion object {
+ fun decode(event: JsonObject): TerminalEvent = when (event.text("type")) {
+ "output" -> {
+ val encoded = requireNotNull(event.text("data"))
+ require(encoded.length <= 350_000) { "Terminal output is too large." }
+ val bytes = Base64.getDecoder().decode(encoded)
+ require(bytes.size <= 256 * 1024) { "Terminal output is too large." }
+ Output(bytes)
+ }
+ "exit" -> Exit(requireNotNull(event["code"]?.jsonPrimitive?.intOrNull))
+ else -> throw IOException("Unknown terminal event.")
+ }
+ }
+}
+
+interface SetupTerminalTransport {
+ suspend fun setup(cols: Int, rows: Int): String
+ suspend fun awaitActive() {}
+ fun output(term: String): Flow<TerminalEvent>
+ suspend fun input(term: String, bytes: ByteArray)
+ suspend fun resize(term: String, cols: Int, rows: Int)
+ suspend fun close(term: String)
+}
+interface TerminalSink {
+ suspend fun write(bytes: ByteArray)
+ fun reset()
+ fun input(enabled: Boolean)
+}
+data class SetupTerminalState(val starting: Boolean = true, val connected: Boolean = false,
+ val exitCode: Int? = null, val error: String? = null)
+
+/** Screen ownership and account ownership are separate: leaving closes the PTY, rotation replays it. */
+class SetupTerminalSession(parent: CoroutineScope, private val transport: SetupTerminalTransport) {
+ private val job = SupervisorJob(parent.coroutineContext[Job])
+ private val scope = CoroutineScope(parent.coroutineContext + job)
+ private val mutableState = MutableStateFlow(SetupTerminalState())
+ val state = mutableState.asStateFlow()
+ private val started = CompletableDeferred<String>()
+ private var term: String? = null
+ private var size = 80 to 24
+ private var sentSize = size
+ private var closed = false
+ private var inputFailed = false
+ private var queuedBytes = 0
+ private val commands = Channel<ByteArray?>(64) // null asks the one ordered sender to synchronize size.
+ private var outputJob: Job? = null
+ private var inputJob: Job? = null
+ private var sink: TerminalSink? = null
+ private val startJob = scope.launch {
+ try {
+ val initial = size
+ val id = transport.setup(initial.first, initial.second)
+ term = id; sentSize = initial
+ if (closed) return@launch
+ mutableState.update { it.copy(starting = false) }
+ started.complete(id)
+ commands.trySend(null)
+ inputJob = scope.launch {
+ try {
+ for (bytes in commands) {
+ if (size != sentSize) { val next = size; transport.resize(id, next.first, next.second); sentSize = next }
+ if (bytes != null) {
+ try { transport.input(id, bytes) } finally { queuedBytes -= bytes.size; bytes.fill(0) }
+ }
+ }
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) { failInput("Terminal input wasn't confirmed. Leave this terminal and check the computer before starting again.") }
+ }
+ // Account retirement also owns cleanup, before its channel is removed.
+ awaitCancellation()
+ } catch (cancelled: CancellationException) { started.cancel(); throw cancelled }
+ catch (_: Exception) {
+ started.completeExceptionally(IOException("Couldn't start agent setup. Check the computer and try again."))
+ mutableState.update { it.copy(starting = false, error = "Couldn't start agent setup. Check the computer and try again.") }
+ } finally {
+ job.cancel()
+ commands.close()
+ while (true) { val remaining = commands.tryReceive(); if (remaining.isFailure) break; remaining.getOrNull()?.fill(0) }
+ term?.let { closeRemote(it) }
+ }
+ }
+
+ fun attach(target: TerminalSink) {
+ sink?.input(false); outputJob?.cancel(); sink = target
+ outputJob = scope.launch {
+ val id = try { started.await() } catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) { return@launch }
+ var attempts = 0
+ while (!closed) {
+ try {
+ transport.awaitActive()
+ target.reset(); target.input(!inputFailed && state.value.exitCode == null)
+ mutableState.update { it.copy(connected = true, error = if (inputFailed) it.error else null) }
+ transport.output(id).collect { event ->
+ attempts = 0
+ when (event) {
+ is TerminalEvent.Output -> target.write(event.bytes)
+ is TerminalEvent.Exit -> { target.input(false); mutableState.update { it.copy(exitCode = event.code, connected = false) } }
+ }
+ }
+ if (state.value.exitCode != null) return@launch
+ throw IOException("Terminal stream ended.")
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (error: Exception) {
+ target.input(false); mutableState.update { it.copy(connected = false) }
+ if (error is HostError && error.status == 404 || ++attempts > 5) {
+ mutableState.update { it.copy(error = "This setup terminal is unavailable. Go back and check the agent again.") }; return@launch
+ }
+ }
+ delay(1_000)
+ }
+ }
+ }
+ fun detach(target: TerminalSink) { if (sink === target) { target.input(false); sink = null; outputJob?.cancel(); outputJob = null } }
+ fun type(bytes: ByteArray) {
+ if (bytes.isEmpty()) return
+ if (closed || inputFailed || !state.value.connected || state.value.exitCode != null) { bytes.fill(0); return }
+ if (bytes.size > 64 * 1024 || queuedBytes + bytes.size > 256 * 1024) {
+ bytes.fill(0); failInput("Terminal input filled its queue. Leave this terminal and check the computer before starting again.")
+ return
+ }
+ queuedBytes += bytes.size
+ if (commands.trySend(bytes).isFailure) {
+ queuedBytes -= bytes.size; bytes.fill(0)
+ failInput("Terminal input filled its queue. Leave this terminal and check the computer before starting again.")
+ }
+ }
+ private fun failInput(message: String) { inputFailed = true; sink?.input(false); inputJob?.cancel(); commands.close(); mutableState.update { it.copy(error = message) } }
+ fun resized(cols: Int, rows: Int) { size = cols.coerceIn(20, 500) to rows.coerceIn(4, 500); commands.trySend(null) }
+ fun close() {
+ if (closed) return
+ closed = true; sink?.input(false); sink = null; outputJob?.cancel(); inputJob?.cancel(); commands.close()
+ mutableState.update { it.copy(connected = false) }
+ // A setup reply can arrive after Back. Keep waiting for its ID so we can close that PTY.
+ if (term != null) startJob.cancel()
+ }
+ suspend fun closeAndJoin() { close(); startJob.cancelAndJoin(); job.cancelAndJoin() }
+ private suspend fun closeRemote(id: String) = withContext(NonCancellable) {
+ withTimeoutOrNull(2_000) { try { transport.close(id) } catch (_: Exception) {} }
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/BotDestination.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/BotDestination.kt
new file mode 100644
index 00000000..75a2c390
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/BotDestination.kt
@@ -0,0 +1,31 @@
+package com.codync.android.core
+
+import java.net.URI
+import java.net.URLDecoder
+import java.nio.charset.StandardCharsets
+
+/** A bot ID alone is never a destination: notifications and widgets retain their account/computer. */
+data class BotDestination(val scope: String, val computerId: String, val botId: String) {
+ companion object {
+ fun parse(value: String, scheme: String): BotDestination {
+ val uri = URI(value)
+ require(uri.scheme == scheme && uri.rawAuthority == "bot" && uri.fragment == null)
+ val path = uri.path
+ require(path.startsWith('/') && path.count { it == '/' } == 1)
+ val bot = path.drop(1)
+ require(bot.isNotBlank() && bot.length <= 128 && bot.none(Char::isISOControl))
+ val query = uri.rawQuery.orEmpty().split('&').filter(String::isNotEmpty).map { item ->
+ val pair = item.split('=', limit = 2)
+ require(pair.size == 2)
+ URLDecoder.decode(pair[0], StandardCharsets.UTF_8.name()) to URLDecoder.decode(pair[1], StandardCharsets.UTF_8.name())
+ }
+ require(query.count { it.first == "scope" } == 1 && query.count { it.first == "computer" } == 1)
+ val scope = query.single { it.first == "scope" }.second
+ val computer = query.single { it.first == "computer" }.second
+ require(scope == "local" || scope.matches(Regex("[a-f0-9]{64}")))
+ require(computer.matches(Regex("[A-Za-z0-9_-]{22}")))
+ computer.decodeBase64Url(16)
+ return BotDestination(scope, computer, bot)
+ }
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt
new file mode 100644
index 00000000..775d6d39
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt
@@ -0,0 +1,50 @@
+package com.codync.android.core
+
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.encodeToJsonElement
+import kotlinx.serialization.json.jsonObject
+
+@Serializable
+data class BotDraft(
+ val id: String? = null,
+ val name: String = "",
+ val description: String = "",
+ val avatarColor: String = AVATAR_COLORS.random(),
+ val avatarShape: String = AVATAR_SHAPES.random(),
+ val backend: String = "claude",
+ val command: String? = null,
+ val cwd: String = "",
+ val permission: String = "auto",
+ val model: String? = null,
+ val modelOptions: Map<String, String> = emptyMap(),
+ val fastMode: Boolean? = null,
+ val pinned: Boolean = false,
+ val hidden: Boolean = false,
+ val notify: Boolean? = null,
+ val connectors: List<String>? = null,
+ val skills: List<String> = emptyList(),
+ val computer: Boolean = false,
+) {
+ val isValid: Boolean get() = id == null || name.isNotBlank()
+ fun toggleNotifications(): BotDraft = copy(notify = !(notify ?: true))
+ fun body(): JsonObject {
+ val normalized = if (backend == "custom") this else copy(command = null)
+ // updateBot merges a patch: null clears model, command or the connector choice, but an unset
+ // switch must stay out (the host's booleans don't take null).
+ return JsonObject(WireJson.encodeToJsonElement(normalized).jsonObject.filterNot { (key, value) -> value == JsonNull && key in SWITCHES })
+ }
+ fun template(): String = JsonObject(body().filterKeys { it !in setOf("id", "pinned", "hidden") }).toString()
+
+ companion object {
+ /** A new bot starts with a random face, like iOS. */
+ val AVATAR_COLORS = listOf("black", "brown", "red", "orange", "yellow", "green", "cyan", "blue", "violet", "magenta", "gray")
+ private val SWITCHES = setOf("fastMode", "notify")
+ val AVATAR_SHAPES = listOf("blob", "pebble", "squircle", "tablet", "wedge", "hex", "cloud", "teardrop")
+
+ fun from(bot: Bot): BotDraft = BotDraft(bot.id, bot.name, bot.description, bot.avatarColor, bot.avatarShape,
+ bot.backend, bot.command, if (bot.managedWorkspace) "" else bot.cwd, bot.permission, bot.model,
+ bot.modelOptions, bot.fastMode, bot.pinned, bot.hidden, bot.notify, bot.connectors, bot.skills, bot.computer)
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/BotExchange.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/BotExchange.kt
new file mode 100644
index 00000000..1c9fdba0
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/BotExchange.kt
@@ -0,0 +1,75 @@
+package com.codync.android.core
+
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.jsonPrimitive
+
+/** One bot-to-bot exchange as seen from the chat of one of the two bots (CodyncKit `BotExchange`). */
+data class BotExchange(val id: String, val chatId: String, val seq: Long, val rev: Long, val createdAt: Long,
+ val source: String, val target: String, val text: String, val reply: String?, val outcome: Outcome) {
+ sealed interface Outcome {
+ data object Pending : Outcome
+ data object Done : Outcome
+ data class Failed(val detail: String) : Outcome
+ }
+
+ val isOutgoing: Boolean get() = chatId == source
+ val peerId: String get() = if (isOutgoing) target else source
+ val verb: String get() = if (isOutgoing) "Messaged" else "Message from"
+
+ companion object {
+ /** A notice carrying the host's structured `botMessage` is an exchange; other notices stay plain. */
+ fun of(entry: Entry): BotExchange? {
+ val message = entry.data["botMessage"] as? JsonObject ?: return null
+ if (entry.kind != "notice") return null
+ fun field(name: String) = message[name]?.jsonPrimitive?.contentOrNull
+ val source = field("sourceBotId") ?: return null
+ val target = field("targetBotId") ?: return null
+ val outcome = when (entry.status) {
+ "completed" -> Outcome.Done
+ "failed", "cancelled" -> Outcome.Failed(field("detail").orEmpty())
+ else -> Outcome.Pending
+ }
+ return BotExchange(entry.id, entry.botId, entry.seq, entry.rev, entry.createdAt, source, target, field("text").orEmpty(), field("reply"), outcome)
+ }
+
+ /** The exchanges with `peer` in a chat, oldest first: what the host returned plus the live chat (the higher `rev` wins). */
+ fun conversation(fetched: List<Entry>, live: List<Entry>, peer: String): List<BotExchange> =
+ (fetched + live).filter { it.kind == "notice" }.groupBy { it.id }.values.map { copies -> copies.maxBy { it.rev } }
+ .mapNotNull(::of).filter { it.peerId == peer }.sortedBy { it.seq }
+ }
+}
+
+/** A run of consecutive exchanges with one peer in a chat's main transcript, shown as one row. */
+data class BotExchangeGroup(val exchanges: List<BotExchange>) {
+ val id: String get() = exchanges.first().id
+ val peerId: String get() = exchanges.first().peerId
+ val createdAt: Long get() = exchanges.first().createdAt
+ val failed: Boolean get() = exchanges.any { it.outcome is BotExchange.Outcome.Failed }
+ /** What the row says before the peer's name: "Messaged" for one, "3 messages with" for more. */
+ val title: String get() = if (exchanges.size == 1) exchanges.first().verb else "${exchanges.size} messages with"
+}
+
+/** A line of the read-only conversation sheet. */
+sealed interface BotConversationRow {
+ val id: String
+ data class Separator(override val id: String, val at: Long) : BotConversationRow
+ data class Message(override val id: String, val author: String, val text: String, val showsAuthor: Boolean) : BotConversationRow
+ /** `awaiting` is the bot being waited for while the outcome is pending. */
+ data class Status(override val id: String, val outcome: BotExchange.Outcome, val awaiting: String) : BotConversationRow
+
+ companion object {
+ /** Rows for exchanges oldest first; a gap over an hour starts a new time block, and a separator or status resets the author. */
+ fun build(exchanges: List<BotExchange>): List<BotConversationRow> = buildList {
+ var author: String? = null
+ var at: Long? = null
+ for (x in exchanges) {
+ if (at == null || x.createdAt - at > 3_600_000) { add(Separator("sep-${x.id}", x.createdAt)); author = null }
+ at = x.createdAt
+ add(Message("${x.id}-request", x.source, x.text, author != x.source)); author = x.source
+ if (!x.reply.isNullOrEmpty()) { add(Message("${x.id}-reply", x.target, x.reply, author != x.target)); author = x.target }
+ if (x.outcome != BotExchange.Outcome.Done) { add(Status("${x.id}-status", x.outcome, x.target)); author = null }
+ }
+ }
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/BotSnapshot.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/BotSnapshot.kt
new file mode 100644
index 00000000..8aeeed4c
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/BotSnapshot.kt
@@ -0,0 +1,39 @@
+package com.codync.android.core
+
+import java.io.IOException
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.flow.takeWhile
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.longOrNull
+
+/** The initial hello is a catch-up target, never evidence that the roster arrived. */
+internal suspend fun botSnapshot(events: Flow<JsonObject>): List<Bot> {
+ val bots = linkedMapOf<String, Bot>()
+ var head: Long? = null
+ var complete = false
+ events.takeWhile { event ->
+ when (event.text("type")) {
+ "hello" -> {
+ check(head == null) { "The computer restarted its roster snapshot." }
+ head = requireNotNull(event["rev"]?.jsonPrimitive?.longOrNull).also { require(it >= 0) }
+ complete = head == 0L
+ }
+ "bot", "entry" -> {
+ val target = requireNotNull(head) { "The computer sent updates before its snapshot header." }
+ if (event.text("type") == "bot") {
+ val bot = HostClient.decode(event.getValue("bot").jsonObject)
+ if (bot.deleted) bots.remove(bot.id) else bots[bot.id] = bot
+ }
+ val revision = requireNotNull(event["rev"]?.jsonPrimitive?.longOrNull)
+ complete = revision >= target
+ }
+ "resync" -> throw IOException("The computer's roster changed too quickly. Try again.")
+ }
+ !complete
+ }.collect()
+ check(complete) { "The computer disconnected before its roster finished loading." }
+ return bots.values.toList()
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/ChannelSocket.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/ChannelSocket.kt
new file mode 100644
index 00000000..35dab511
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/ChannelSocket.kt
@@ -0,0 +1,93 @@
+package com.codync.android.core
+
+import java.io.IOException
+import java.util.concurrent.TimeUnit
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.channels.Channel
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.Response
+import okhttp3.WebSocket
+import okhttp3.WebSocketListener
+import okio.ByteString
+
+internal interface ChannelSocket {
+ suspend fun send(text: String)
+ suspend fun receive(): String
+ fun close(code: Int = 1000)
+}
+
+class ChannelClosed(val code: Int) : IOException(when (code) {
+ 4001, 4003 -> "This device isn't allowed on the computer. Pair it again."
+ 4400 -> "Update Codync to connect to this computer."
+ 4410 -> "This pairing code expired. Show a new one on the computer."
+ else -> "Connection to the computer ended."
+})
+
+internal class SocketRefused(val status: Int) : IOException("The connection was refused ($status).")
+
+internal class OkHttpChannelSocket private constructor(client: OkHttpClient, request: Request) : ChannelSocket {
+ private val opened = CompletableDeferred<Unit>()
+ private val incoming = Channel<String>(16)
+ private val socket = client.newWebSocket(request, object : WebSocketListener() {
+ override fun onOpen(webSocket: WebSocket, response: Response) { opened.complete(Unit) }
+ override fun onMessage(webSocket: WebSocket, text: String) {
+ if (text.toByteArray().size > 1024 * 1024) {
+ incoming.close(IOException("The computer sent an oversized channel message."))
+ webSocket.close(1009, null)
+ return
+ }
+ // This callback runs on OkHttp's socket reader, never the UI thread.
+ // Waiting here propagates bounded backpressure to the TCP reader.
+ try { runBlocking { incoming.send(text) } }
+ catch (_: Exception) { webSocket.cancel() }
+ }
+ override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
+ incoming.close(IOException("Unexpected binary channel message"))
+ webSocket.close(1003, null)
+ }
+ override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
+ incoming.close(ChannelClosed(code))
+ opened.completeExceptionally(ChannelClosed(code))
+ webSocket.close(code, null)
+ }
+ override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
+ incoming.close(ChannelClosed(code))
+ opened.completeExceptionally(ChannelClosed(code))
+ }
+ override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
+ val failure = response?.let { SocketRefused(it.code) } ?: IOException("Can't reach the computer.", t)
+ opened.completeExceptionally(failure)
+ incoming.close(failure)
+ }
+ })
+
+ override suspend fun send(text: String) {
+ opened.await()
+ if (!socket.send(text)) throw IOException("Connection to the computer ended.")
+ }
+ override suspend fun receive(): String = incoming.receive()
+ override fun close(code: Int) {
+ socket.cancel()
+ incoming.cancel(CancellationException("Socket closed ($code)"))
+ opened.cancel()
+ }
+
+ companion object {
+ // Native pings detect dead direct links even when no application events arrive.
+ private val client = OkHttpClient.Builder().pingInterval(15, TimeUnit.SECONDS)
+ .connectTimeout(10, TimeUnit.SECONDS).readTimeout(0, TimeUnit.SECONDS).build()
+ suspend fun dial(request: Request): ChannelSocket {
+ val result = OkHttpChannelSocket(client, request)
+ try {
+ result.opened.await()
+ return result
+ } catch (error: Throwable) {
+ result.close()
+ throw error
+ }
+ }
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt
new file mode 100644
index 00000000..9c7821b3
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt
@@ -0,0 +1,138 @@
+package com.codync.android.core
+
+import java.io.IOException
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.NonCancellable
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.suspendCancellableCoroutine
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.*
+import okhttp3.Call
+import okhttp3.Callback
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import okhttp3.Response
+import java.util.concurrent.TimeUnit
+
+@Serializable
+data class CloudComputer(val computerId: String, val name: String, val signKey: String,
+ val platform: String? = null, val device: String? = null, val boxKey: String? = null,
+ val version: String? = null, val online: Boolean? = null, val lastSeenAt: Long? = null,
+ val claimedAt: Long? = null, val access: String? = null)
+
+data class AccessTicket(val requestId: String, val expiresAt: Long, val code: String, val computerId: String, val signKey: String)
+
+@Serializable
+data class AccessStatus(val requestId: String, val status: String, val computerId: String? = null,
+ val expiresAt: Long? = null, val hostNonce: String? = null, val grantId: String? = null) {
+ // Unrecognized terminal states never authorize the device.
+ val state: String get() = status.takeIf { it in setOf("pending", "approved", "denied", "expired", "cancelled") } ?: "expired"
+}
+
+class CloudError(val status: Int, val code: String, detail: String? = null) : IOException(when (code) {
+ "requestExpired" -> "The request expired. Ask again."
+ "accountDeleted" -> "This account was deleted."
+ "rateLimited" -> "Too many requests. Try again in a little while."
+ else -> detail ?: "Codync cloud error ($code)"
+}) {
+ val isTransient: Boolean get() = status >= 500 || status == 429 || status == 401
+}
+
+/** Existing /v1 account protocol; a login is never a host authorization. */
+class CloudClient private constructor(base: String, private val identity: DeviceIdentity,
+ private val token: suspend () -> String, private val http: OkHttpClient,
+ private val pollInterval: Long) {
+ private val baseUrl = base.trimEnd('/').toHttpUrl()
+ private val json = Json { ignoreUnknownKeys = true }
+
+ constructor(base: String, identity: DeviceIdentity, token: suspend () -> String) : this(base, identity, token,
+ OkHttpClient.Builder().followRedirects(false).followSslRedirects(false).callTimeout(20, TimeUnit.SECONDS).build(), 2_000) {
+ require(isCloudUrl(base)) { "Invalid cloud address" }
+ }
+
+ internal constructor(base: String, identity: DeviceIdentity, token: suspend () -> String,
+ http: OkHttpClient, pollInterval: Long, testOnly: Unit) : this(base, identity, token, http, pollInterval)
+
+ suspend fun registerDevice(name: String) { request("POST", listOf("v1", "devices"),
+ buildJsonObject { put("name", name); put("platform", "android") }, signed = true) }
+
+ suspend fun computers(): List<CloudComputer> {
+ val result = request("GET", listOf("v1", "computers"), signed = true)
+ return json.decodeFromJsonElement(result.getValue("computers"))
+ }
+
+ suspend fun requestAccess(id: String, signKey: String): AccessTicket {
+ val hostKey = signKey.decodeBase64Url(32)
+ require(RelayCrypto.computerId(hostKey) == id) { "This computer's key doesn't match its ID." }
+ val nonce = RelayCrypto.randomBytes(32)
+ var requestId: String? = null
+ try {
+ val created = request("POST", listOf("v1", "computers", id, "access-requests"),
+ buildJsonObject { put("commit", RelayCrypto.sasCommit(identity.deviceKey, nonce).base64Url()) }, signed = true)
+ val rid = created.getValue("requestId").jsonPrimitive.content
+ requestId = rid
+ val expiresAt = created.getValue("expiresAt").jsonPrimitive.long
+ var hostNonce: ByteArray? = null
+ while (hostNonce == null) {
+ if (System.currentTimeMillis() >= expiresAt) throw CloudError(410, "requestExpired")
+ val status = accessStatus(rid)
+ require(status.requestId == rid && (status.computerId == null || status.computerId == id)) { "Invalid access response" }
+ if (status.state != "pending") throw CloudError(0, status.state, "The computer didn't take the request.")
+ hostNonce = status.hostNonce?.decodeBase64Url(32)
+ if (hostNonce == null) delay(pollInterval)
+ }
+ request("POST", listOf("v1", "access-requests", rid, "reveal"),
+ buildJsonObject { put("nonce", nonce.base64Url()) }, signed = true)
+ return AccessTicket(rid, expiresAt, RelayCrypto.sasCode(hostKey, identity.deviceKey, nonce, hostNonce), id, signKey)
+ } catch (error: Throwable) {
+ // A cancelled nonce exchange leaves no invisible request waiting at the host.
+ requestId?.let { rid -> withContext(NonCancellable) { try { cancelAccess(rid) } catch (_: Exception) { } } }
+ throw error
+ } finally { nonce.fill(0) }
+ }
+
+ suspend fun accessStatus(id: String): AccessStatus {
+ val result = request("GET", listOf("v1", "access-requests", id))
+ return json.decodeFromJsonElement(result)
+ }
+ suspend fun cancelAccess(id: String) { request("DELETE", listOf("v1", "access-requests", id)) }
+
+ private suspend fun request(method: String, path: List<String>, body: JsonObject? = null, signed: Boolean = false): JsonObject {
+ val url = baseUrl.newBuilder().apply { path.forEach(::addPathSegment) }.build()
+ val bytes = body?.toString()?.toByteArray() ?: byteArrayOf()
+ val jwt = token()
+ val builder = Request.Builder().url(url).header("Authorization", "Bearer $jwt")
+ .method(method, if (body != null) bytes.toRequestBody("application/json".toMediaType()) else null)
+ if (signed) builder.header("Codync-Sig", RequestSigner.header(identity, method, url, bytes))
+ val call = http.newCall(builder.build())
+ val value = suspendCancellableCoroutine<JsonObject> { continuation ->
+ continuation.invokeOnCancellation { call.cancel() }
+ call.enqueue(object : Callback {
+ override fun onFailure(call: Call, e: IOException) { continuation.resumeWith(Result.failure(e)) }
+ override fun onResponse(call: Call, response: Response) {
+ try {
+ val parsed = response.use {
+ val source = response.body?.source()
+ if (source?.request(MAX_RESPONSE + 1) == true) throw IOException("Cloud response is too large.")
+ val text = source?.readUtf8().orEmpty().ifBlank { "{}" }
+ val result = json.parseToJsonElement(text).jsonObject
+ if (!response.isSuccessful) {
+ val detail = result["error"]?.jsonObject
+ throw CloudError(response.code, detail?.text("code") ?: "http${response.code}", detail?.text("message"))
+ }
+ result
+ }
+ continuation.resumeWith(Result.success(parsed))
+ } catch (error: Exception) { continuation.resumeWith(Result.failure(error)) }
+ }
+ })
+ }
+ return value
+ }
+
+ companion object { private const val MAX_RESPONSE = 2L * 1024 * 1024 }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Compatibility.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Compatibility.kt
new file mode 100644
index 00000000..55d5167a
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Compatibility.kt
@@ -0,0 +1,41 @@
+package com.codync.android.core
+
+/**
+ * Which side must update before this app and a host can work together
+ * (docs/reference/compatibility.md): each names the oldest version of the other it works with.
+ */
+sealed interface VersionMismatch {
+ /** This app is older than the host's `minApp`. */
+ data class UpdateApp(val minimum: String) : VersionMismatch
+ /** The host is older than `MIN_HOST`. */
+ data class UpdateHost(val version: String, val minimum: String) : VersionMismatch
+
+ companion object {
+ /** The oldest host this app works with; raise it only when a core flow needs something older hosts lack. */
+ const val MIN_HOST = "2.12.0"
+
+ /** An unknown version is never a reason to lock someone out. */
+ fun check(app: String, hostVersion: String?, minApp: String?, minHost: String = MIN_HOST): VersionMismatch? = when {
+ hostVersion == null -> null
+ minApp != null && AppVersion.isBelow(app, minApp) -> UpdateApp(minApp)
+ AppVersion.isBelow(hostVersion, minHost) -> UpdateHost(hostVersion, minHost)
+ else -> null
+ }
+ }
+}
+
+object AppVersion {
+ /** `2.9.0` < `2.14.1`, numerically, ignoring a `-dev` style suffix; unreadable versions compare as not below. */
+ fun isBelow(version: String, minimum: String): Boolean {
+ val have = parse(version) ?: return false
+ val need = parse(minimum) ?: return false
+ for (i in 0 until maxOf(have.size, need.size)) {
+ val a = have.getOrElse(i) { 0 }
+ val b = need.getOrElse(i) { 0 }
+ if (a != b) return a < b
+ }
+ return false
+ }
+
+ private fun parse(version: String): List<Int>? = version.substringBefore('-').split('.').map { it.toIntOrNull() ?: return null }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
new file mode 100644
index 00000000..5419bf8c
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
@@ -0,0 +1,36 @@
+package com.codync.android.core
+
+import kotlinx.serialization.Serializable
+import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
+
+@Serializable
+data class Computer(
+ val id: String,
+ val name: String,
+ val signKey: String,
+ val boxKey: String? = null,
+ val urls: List<String> = emptyList(),
+ val cloud: String? = null,
+ val route: ConnectionRoute = ConnectionRoute.Automatic,
+) {
+ fun validate() {
+ require(RelayCrypto.computerId(signKey.decodeBase64Url(32)) == id) { "This computer's identity changed. Pair it again." }
+ boxKey?.decodeBase64Url(32)
+ require(urls.size <= 16 && urls.all(::isDirectUrl)) { "Invalid computer address" }
+ require(cloud == null || isCloudUrl(cloud)) { "Invalid cloud address" }
+ }
+}
+
+@Serializable
+enum class ConnectionRoute { Automatic, CloudflareFirst, DirectOnly }
+
+internal fun isDirectUrl(value: String): Boolean {
+ val url = value.toHttpUrlOrNull() ?: return false
+ return url.username.isEmpty() && url.password.isEmpty() && url.fragment == null
+}
+
+internal fun isCloudUrl(value: String): Boolean {
+ val url = value.toHttpUrlOrNull() ?: return false
+ return url.isHttps && url.username.isEmpty() && url.password.isEmpty() && url.query == null && url.fragment == null
+}
+
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Connections.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Connections.kt
new file mode 100644
index 00000000..b48821eb
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Connections.kt
@@ -0,0 +1,163 @@
+package com.codync.android.core
+
+import java.net.URI
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.Serializable
+
+/** Public metadata from the existing host marketplace and credential APIs. */
+@Serializable data class ComposioStatus(val configured: Boolean, val keyUrl: String)
+@Serializable data class ComposioApp(val slug: String, val name: String, val description: String? = null,
+ val logo: String? = null, val connection: ComposioConnectionState? = null) {
+ val connected: Boolean get() = connection?.status == "active"
+}
+@Serializable data class ComposioApps(val items: List<ComposioApp>, val nextCursor: String? = null)
+@Serializable data class ComposioConnectionState(val id: String, val status: String)
+@Serializable data class ComposioField(val name: String, val label: String, val description: String? = null,
+ val secret: Boolean = false, val required: Boolean = false)
+@Serializable data class ComposioConnect(val status: String, val url: String? = null, val connection: String? = null,
+ val mode: String? = null, val fields: List<ComposioField>? = null) {
+ fun checked(): ComposioConnect {
+ when (status) {
+ "redirect" -> {
+ require(!connection.isNullOrBlank()) { "The host did not return a connection ID." }
+ requireNotNull(url).let(::externalHttps)
+ }
+ "needsFields" -> {
+ require(!mode.isNullOrBlank()) { "The host did not return an authentication mode." }
+ val names = fields.orEmpty().map(ComposioField::name)
+ require(names.size in 1..64 && names.all(String::isNotBlank) && names.toSet().size == names.size) {
+ "The host returned unsupported connection fields."
+ }
+ }
+ else -> error("This connection method needs a newer app.")
+ }
+ return this
+ }
+ fun complete(values: Map<String, String>): Boolean = status == "needsFields" && fields.orEmpty().all {
+ !it.required || values[it.name]?.isNotEmpty() == true
+ }
+ fun submitted(values: Map<String, String>): Map<String, String> {
+ checked()
+ require(complete(values)) { "Fill in the required connection fields." }
+ val known = fields.orEmpty().mapTo(mutableSetOf(), ComposioField::name)
+ require(values.keys.all { it in known }) { "Unknown connection field." }
+ require(values.values.all { it.toByteArray().size <= 64 * 1024 }) { "A connection field is too large." }
+ return values.filterValues(String::isNotEmpty) // Credential whitespace is meaningful.
+ }
+}
+fun externalHttps(value: String): URI {
+ require(value.length <= 8_192 && value.none(Char::isISOControl)) { "Invalid sign-in link." }
+ val uri = URI(value)
+ require(uri.scheme == "https" && !uri.host.isNullOrBlank() && uri.userInfo == null) { "Invalid sign-in link." }
+ return uri
+}
+
+@Serializable data class SavedLogin(val id: String, val site: String, val username: String = "")
+@Serializable data class CredentialStatus(val provider: String, val onePasswordConnected: Boolean = false)
+@Serializable data class ConnectionRequest(val kind: String, val status: String, val title: String, val botId: String,
+ val toolkit: String? = null, val registryName: String? = null, val connectorId: String? = null,
+ val field: String? = null, val location: String? = null, val site: String? = null,
+ val backend: String? = null, val logo: String? = null) {
+ val canConnect: Boolean get() = status == "pending" && when (kind) {
+ "login", "secret" -> true
+ "agent" -> !backend.isNullOrBlank()
+ "app" -> !toolkit.isNullOrBlank()
+ "connection" -> !connectorId.isNullOrBlank() || !registryName.isNullOrBlank()
+ else -> false
+ }
+}
+
+/** Blank replacement fields preserve host values; no operation can reveal an existing value. */
+fun credentialReplacements(connector: InstalledConnector, values: Map<String, String>): Map<String, String> {
+ require(values.keys.all { it in connector.keys }) { "Unknown credential field." }
+ require(values.values.all { it.toByteArray().size <= 64 * 1024 }) { "A credential field is too large." }
+ return values.filterValues(String::isNotEmpty)
+}
+
+interface AppConnectionTransport {
+ suspend fun awaitActive()
+ suspend fun start(): ComposioConnect
+ suspend fun state(id: String): ComposioConnectionState
+ suspend fun submit(mode: String, fields: Map<String, String>): ComposioConnectionState
+}
+data class AppConnectionState(val loading: Boolean = true, val plan: ComposioConnect? = null,
+ val connected: Boolean = false, val saving: Boolean = false, val status: String? = null,
+ val connectionId: String? = null, val error: String? = null)
+
+/** An account owns sign-in; a screen may detach for rotation or the external browser. */
+class AppConnectionSession(parent: CoroutineScope, private val transport: AppConnectionTransport, resumeId: String? = null) {
+ private val job = SupervisorJob(parent.coroutineContext[Job])
+ private val scope = CoroutineScope(parent.coroutineContext + job)
+ private val mutableState = MutableStateFlow(AppConnectionState())
+ val state = mutableState.asStateFlow()
+ private var polling: Job? = null
+ init {
+ if (resumeId != null) {
+ require(resumeId.isNotBlank() && resumeId.length <= 1024 && resumeId.none(Char::isISOControl))
+ mutableState.update { it.copy(loading = false, connectionId = resumeId, status = "initiated") }
+ poll(resumeId) // A cold restore reads the existing attempt; it never starts another one.
+ } else {
+ scope.launch {
+ try {
+ transport.awaitActive()
+ val response = transport.start()
+ val plan = response.checked()
+ mutableState.update { it.copy(loading = false, plan = plan, connectionId = plan.connection) }
+ if (plan.status == "redirect") poll(requireNotNull(plan.connection))
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) { mutableState.update { it.copy(loading = false,
+ error = "Couldn't start sign-in. Check installed apps before trying again.") } }
+ }
+ }
+ }
+ private fun poll(id: String) {
+ polling?.cancel()
+ polling = scope.launch {
+ val completed = withTimeoutOrNull(600_000) {
+ while (true) {
+ delay(2_000)
+ transport.awaitActive()
+ val response = try { transport.state(id) }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) { continue }
+ if (response.id != id) {
+ mutableState.update { it.copy(error = "The host returned a different connection. Close and check installed apps.") }
+ return@withTimeoutOrNull true
+ }
+ if (receive(response)) return@withTimeoutOrNull true
+ }
+ @Suppress("UNREACHABLE_CODE") false
+ }
+ if (completed == null) mutableState.update { it.copy(error = "Timed out waiting for sign-in. Check installed apps before trying again.") }
+ }
+ }
+ private fun receive(response: ComposioConnectionState): Boolean {
+ if (response.id.isBlank()) {
+ mutableState.update { it.copy(error = "The host did not return a connection ID. Check installed apps.") }
+ return true
+ }
+ mutableState.update { it.copy(status = response.status, connectionId = response.id) }
+ return when (response.status) {
+ "active" -> { mutableState.update { it.copy(connected = true, error = null) }; true }
+ "failed", "expired" -> { mutableState.update { it.copy(error = "Sign-in ${response.status}. Close and try again.") }; true }
+ else -> false // Unknown statuses retain their actual value and never imply success.
+ }
+ }
+ fun submit(values: Map<String, String>) {
+ if (state.value.saving || state.value.connected || !job.isActive) return
+ val plan = requireNotNull(state.value.plan)
+ val fields = plan.submitted(values)
+ mutableState.update { it.copy(saving = true, error = null) }
+ scope.launch {
+ try {
+ transport.awaitActive()
+ val response = transport.submit(requireNotNull(plan.mode), fields)
+ if (!receive(response)) poll(response.id)
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) { mutableState.update { it.copy(error = "Connection wasn't confirmed. Check installed apps before trying again.") } }
+ finally { mutableState.update { it.copy(saving = false) } }
+ }
+ }
+ fun close() { job.cancel() }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/ConnectorOAuth.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/ConnectorOAuth.kt
new file mode 100644
index 00000000..b4a7110e
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/ConnectorOAuth.kt
@@ -0,0 +1,50 @@
+package com.codync.android.core
+
+import java.net.URI
+import java.net.URLDecoder
+import java.security.MessageDigest
+import kotlinx.serialization.Serializable
+
+@Serializable data class ConnectorSignIn(val url: String, val callback: String)
+@Serializable data class PendingConnectorOAuth(val connectorId: String, val computerId: String,
+ val stateHash: String, val expiresAt: Long, val requestId: String? = null) {
+ fun validate(back: OAuthReturn, computer: String, now: Long) {
+ require(now < expiresAt && expiresAt <= now + 15 * 60_000 && computerId == computer &&
+ MessageDigest.isEqual(stateHash.toByteArray(), hash(back.state).toByteArray())) { "This connector sign-in expired or belongs to another computer. Start sign-in again." }
+ }
+ companion object {
+ fun create(plan: ConnectorSignIn, connectorId: String, computerId: String, now: Long): PendingConnectorOAuth {
+ val uri = URI(plan.url)
+ require(plan.callback == "app" && uri.scheme == "https" && !uri.host.isNullOrBlank() && uri.userInfo == null && uri.fragment == null) { "This connector didn't provide a supported sign-in page." }
+ val state = query(uri)["state"]
+ require(!state.isNullOrBlank() && state.length <= 2048) { "The connector sign-in page is missing its state." }
+ return PendingConnectorOAuth(connectorId, computerId, hash(state), now + 15 * 60_000)
+ }
+ private fun hash(value: String): String = MessageDigest.getInstance("SHA-256").digest(value.toByteArray())
+ .joinToString("") { "%02x".format(it) }
+ }
+}
+data class OAuthReturn(val state: String, val code: String?, val error: String?) {
+ companion object {
+ fun parse(value: String, scheme: String): OAuthReturn {
+ require(value.length <= 16_384)
+ val uri = URI(value)
+ require(uri.scheme == scheme && uri.host == "oauth" && uri.userInfo == null && uri.port == -1 && uri.path.isNullOrEmpty() && uri.fragment == null)
+ val fields = query(uri)
+ val state = fields["state"]
+ val code = fields["code"]?.takeIf(String::isNotBlank)
+ val error = fields["error_description"]?.takeIf(String::isNotBlank) ?: fields["error"]?.takeIf(String::isNotBlank)
+ require(!state.isNullOrBlank() && state.length <= 2048 && (code != null) != (error != null))
+ return OAuthReturn(state, code, error)
+ }
+ }
+}
+private fun query(uri: URI): Map<String, String> {
+ val result = mutableMapOf<String, String>()
+ uri.rawQuery.orEmpty().split('&').filter(String::isNotBlank).forEach { part ->
+ val name = URLDecoder.decode(part.substringBefore('='), "UTF-8")
+ val value = URLDecoder.decode(part.substringAfter('=', ""), "UTF-8")
+ require(result.put(name, value) == null) { "The sign-in link contains repeated fields." }
+ }
+ return result
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt
new file mode 100644
index 00000000..deb099b6
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt
@@ -0,0 +1,117 @@
+package com.codync.android.core
+
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.decodeFromJsonElement
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.longOrNull
+
+val WireJson = Json { ignoreUnknownKeys = true; encodeDefaults = true }
+
+@Serializable
+data class Entry(
+ val id: String,
+ val seq: Long,
+ val botId: String,
+ val threadId: String? = null,
+ val rev: Long,
+ val kind: String,
+ val turn: Long = 0,
+ val data: JsonObject = JsonObject(emptyMap()),
+ val createdAt: Long = 0,
+ val updatedAt: Long = 0,
+) {
+ val text: String get() = data.text("text").orEmpty()
+ val clientNonce: String? get() = data.text("clientNonce")
+ val status: String? get() = data.text("status")
+ val isChat: Boolean get() = kind in listOf("user", "permission", "notice") ||
+ kind == "agent" && data["final"]?.jsonPrimitive?.booleanOrNull == true
+
+ companion object {
+ fun decode(value: JsonObject): Entry {
+ val entry = WireJson.decodeFromJsonElement<Entry>(value)
+ require(entry.id.isNotBlank() && entry.botId.isNotBlank() && entry.kind.isNotBlank() && entry.seq >= 0 && entry.rev >= 0) {
+ "The computer sent an invalid conversation update."
+ }
+ // Validate the fields used by rendering before the mirror can checkpoint them.
+ val fields = WireJson.decodeFromJsonElement<EntryFields>(entry.data)
+ require(fields.thread == null || fields.thread.count >= 0)
+ require(fields.callSeconds == null || fields.callSeconds >= 0)
+ require(fields.options.orEmpty().all { it.optionId.isNotBlank() })
+ require(fields.attachments.orEmpty().all { it.size in 0..MAX_FILE_BYTES && it.name.isNotBlank() })
+ return entry
+ }
+ }
+}
+
+const val MAX_FILE_BYTES = 100L * 1024 * 1024
+
+@Serializable
+private data class EntryFields(
+ val text: String? = null, val clientNonce: String? = null, val status: String? = null,
+ val final: Boolean? = null, val title: String? = null, val command: String? = null,
+ val detail: String? = null, val output: String? = null, val author: String? = null,
+ val options: List<PermissionChoice>? = null, val reactions: List<String>? = null,
+ val thread: ReplySummary? = null, val attachments: List<Attachment>? = null, val callSeconds: Long? = null,
+)
+@Serializable private data class PermissionChoice(val optionId: String, val name: String, val kind: String)
+@Serializable private data class ReplySummary(val count: Int)
+@Serializable data class Attachment(val id: String, val name: String, val size: Long) {
+ val isImage: Boolean get() = name.substringAfterLast('.', "").lowercase() in listOf("png", "jpg", "jpeg", "heic", "gif", "webp", "tiff", "bmp")
+}
+
+@Serializable
+enum class SendStatus { Sending, Waiting, Delivering, Failed }
+
+@Serializable
+data class PendingSend(
+ val nonce: String,
+ val botId: String,
+ val threadId: String? = null,
+ val text: String,
+ val createdAt: Long,
+ val status: SendStatus = SendStatus.Sending,
+ val error: String? = null,
+ val files: List<OutgoingFile> = emptyList(),
+)
+
+@Serializable
+data class OutgoingFile(val path: String, val name: String, val size: Long)
+
+sealed interface MirrorEvent {
+ data class Hello(val hostId: String, val rev: Long, val usage: JsonObject, val screen: JsonObject?) : MirrorEvent
+ data class BotChanged(val bot: Bot) : MirrorEvent
+ data class EntryChanged(val entry: Entry) : MirrorEvent
+ data class Usage(val value: JsonObject) : MirrorEvent
+ data class Screen(val value: JsonObject) : MirrorEvent
+ data object Resync : MirrorEvent
+ data object Ignored : MirrorEvent
+
+ companion object {
+ fun decode(value: JsonObject): MirrorEvent = when (value.text("type")) {
+ "hello" -> Hello(requireNotNull(value.text("hostId")),
+ requireNotNull(value["rev"]?.jsonPrimitive?.longOrNull),
+ value["usage"]?.jsonObject ?: JsonObject(emptyMap()), value["screen"]?.takeUnless { it == JsonNull }?.jsonObject)
+ "bot" -> BotChanged(HostClient.decode(value.getValue("bot").jsonObject))
+ "entry" -> EntryChanged(Entry.decode(value.getValue("entry").jsonObject))
+ "usage" -> Usage(value.getValue("usage").jsonObject)
+ "screen" -> Screen(value.getValue("screen").jsonObject)
+ "resync" -> Resync
+ // Match the existing clients: unknown events do not advance the cursor.
+ else -> Ignored
+ }
+ }
+}
+
+data class MirrorSnapshot(
+ val bots: List<Bot> = emptyList(),
+ val entries: List<Entry> = emptyList(),
+ val pending: List<PendingSend> = emptyList(),
+ val rev: Long = 0,
+ val usage: JsonObject = JsonObject(emptyMap()),
+ val screen: JsonObject? = null,
+)
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Deadline.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Deadline.kt
new file mode 100644
index 00000000..ba221e87
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Deadline.kt
@@ -0,0 +1,21 @@
+package com.codync.android.core
+
+import java.io.IOException
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.TimeoutCancellationException
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.ensureActive
+import kotlinx.coroutines.withTimeout
+
+/**
+ * `withTimeout` that fails like any other error: a `TimeoutCancellationException` is a
+ * cancellation, so the usual `catch (CancellationException) { throw }` would end the work
+ * silently. Cancellation by the caller's owner still cancels.
+ */
+suspend fun <T> deadline(milliseconds: Long, message: String, operation: suspend CoroutineScope.() -> T): T {
+ try { return withTimeout(milliseconds, operation) }
+ catch (error: TimeoutCancellationException) {
+ currentCoroutineContext().ensureActive()
+ throw IOException(message, error)
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/DeviceIdentity.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/DeviceIdentity.kt
new file mode 100644
index 00000000..40dd0923
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/DeviceIdentity.kt
@@ -0,0 +1,16 @@
+package com.codync.android.core
+
+/** Storage owns the private seeds; the channel never serializes or logs them. */
+class DeviceIdentity(signingSeed: ByteArray, pushSeed: ByteArray) {
+ private val signingSeed = signingSeed.copyOf()
+ private val pushSeed = pushSeed.copyOf()
+ init {
+ require(signingSeed.size == 32 && pushSeed.size == 32)
+ }
+ val publicKey: String get() = RelayCrypto.signingPublic(signingSeed).base64Url()
+ val pushKey: String get() = RelayCrypto.agreementPublic(pushSeed).base64Url()
+ internal val deviceKey: ByteArray get() = RelayCrypto.signingPublic(signingSeed)
+ internal fun sign(input: ByteArray): ByteArray = RelayCrypto.sign(signingSeed, input)
+ fun openPush(sealed: String, computerId: String): ByteArray = RelayCrypto.openPush(sealed, computerId, pushSeed)
+}
+
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Encoding.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Encoding.kt
new file mode 100644
index 00000000..f6513519
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Encoding.kt
@@ -0,0 +1,18 @@
+package com.codync.android.core
+
+import java.nio.ByteBuffer
+import java.util.Base64
+
+internal fun ByteArray.base64Url(): String = Base64.getUrlEncoder().withoutPadding().encodeToString(this)
+
+internal fun String.decodeBase64Url(size: Int? = null): ByteArray {
+ require(length % 4 != 1 && all { it in 'A'..'Z' || it in 'a'..'z' || it in '0'..'9' || it == '-' || it == '_' }) {
+ "Invalid base64url value"
+ }
+ val bytes = Base64.getUrlDecoder().decode(this)
+ require(bytes.base64Url() == this && (size == null || bytes.size == size)) { "Invalid base64url length or encoding" }
+ return bytes
+}
+
+internal fun Long.bigEndian(): ByteArray = ByteBuffer.allocate(8).putLong(this).array()
+
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/EncryptedChannel.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/EncryptedChannel.kt
new file mode 100644
index 00000000..f545aeb0
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/EncryptedChannel.kt
@@ -0,0 +1,339 @@
+package com.codync.android.core
+
+import java.io.IOException
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.AtomicLong
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.ensureActive
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.asSharedFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withTimeout
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.longOrNull
+import kotlinx.serialization.json.put
+
+enum class HostRoute { Direct, Relay }
+sealed interface LinkState {
+ data object Connecting : LinkState
+ data class Ready(val route: HostRoute) : LinkState
+ data class ComputerOffline(val lastSeenAt: Long?) : LinkState
+ data class Failed(val message: String, val status: Int? = null) : LinkState
+}
+
+class HostError(val status: Int, override val message: String) : IOException(message)
+
+/** One encrypted connection; its owner decides when to reconnect and when to retire it. */
+class EncryptedChannel internal constructor(
+ private val socket: ChannelSocket,
+ val route: HostRoute,
+ private val computer: Computer,
+ private val identity: DeviceIdentity,
+ private val pairing: Boolean,
+) : AutoCloseable {
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val writer = Mutex()
+ private val mutableState = MutableStateFlow<LinkState>(LinkState.Connecting)
+ val state: StateFlow<LinkState> = mutableState.asStateFlow()
+ private val firstState = CompletableDeferred<Unit>()
+ private var handshake: Handshake? = null
+ private var handshakeDeadline: Job? = null
+ private var sealer: FrameSealer? = null
+ private var opener: FrameOpener? = null
+ private val ids = AtomicLong()
+ private val calls = ConcurrentHashMap<Long, CompletableDeferred<JsonElement>>()
+ private val streams = ConcurrentHashMap<Long, Channel<JsonObject>>()
+ private val mailboxCalls = ConcurrentHashMap<String, CompletableDeferred<JsonObject>>()
+ private val listLock = Mutex()
+ private val mailboxUpdates = MutableSharedFlow<JsonObject>(extraBufferCapacity = 256)
+ val mailbox = mailboxUpdates.asSharedFlow()
+ @Volatile private var closed = false
+
+ internal suspend fun start(): EncryptedChannel {
+ scope.launch {
+ try {
+ if (route == HostRoute.Direct) beginHandshake()
+ while (true) {
+ val text = if (route == HostRoute.Relay) withTimeout(75_000) { socket.receive() } else socket.receive()
+ val wire = Json.parseToJsonElement(text).jsonObject
+ handle(wire)
+ }
+ } catch (error: CancellationException) {
+ if (!closed) fail(IOException("Connection to the computer timed out.", error))
+ } catch (error: Throwable) {
+ val failure = if (error is ChannelClosed) when (error.code) {
+ 4001, 4003, 4410 -> HostError(403, requireNotNull(error.message))
+ 4400 -> HostError(426, requireNotNull(error.message))
+ else -> error
+ } else error
+ fail(failure)
+ }
+ }
+ if (route == HostRoute.Relay) scope.launch {
+ try {
+ while (true) {
+ delay(30_000)
+ // The relay's auto-response requires these exact bytes.
+ writer.withLock { socket.send("{\"t\":\"ping\"}") }
+ }
+ } catch (error: CancellationException) {
+ throw error
+ } catch (error: Throwable) {
+ fail(error)
+ }
+ }
+ try {
+ deadline(15_000, "The computer didn't finish connecting.") { firstState.await() }
+ return this
+ } catch (error: Throwable) {
+ close()
+ throw error
+ }
+ }
+
+ private suspend fun beginHandshake() {
+ handshakeDeadline?.cancel()
+ mutableState.value = LinkState.Connecting
+ dropPending(IOException("The computer connection changed. Retry the action."))
+ writer.withLock {
+ sealer = null
+ opener = null
+ val next = Handshake(computer, identity)
+ handshake = next
+ mutableState.value = LinkState.Connecting
+ socket.send(next.hello(pairing).toString())
+ }
+ handshakeDeadline = scope.launch {
+ delay(10_000)
+ fail(IOException("The computer didn't finish connecting."))
+ }
+ }
+
+ private suspend fun handle(wire: JsonObject) {
+ when (wire.text("t")) {
+ "presence" -> if (wire["online"]?.jsonPrimitive?.booleanOrNull == true) {
+ beginHandshake()
+ } else {
+ handshakeDeadline?.cancel()
+ writer.withLock { handshake = null; sealer = null; opener = null }
+ dropPending(IOException("The computer is offline."))
+ mutableState.value = LinkState.ComputerOffline(wire["lastSeenAt"]?.jsonPrimitive?.longOrNull)
+ firstState.complete(Unit)
+ }
+ "welcome" -> {
+ val current = requireNotNull(handshake) { "Unexpected host welcome" }
+ val keys = current.finish(requireNotNull(wire.text("ek")).decodeBase64Url(32),
+ requireNotNull(wire.text("sig")).decodeBase64Url(64))
+ writer.withLock {
+ handshake = null
+ sealer = FrameSealer(keys.d2h)
+ opener = FrameOpener(keys.h2d)
+ }
+ handshakeDeadline?.cancel()
+ mutableState.value = LinkState.Ready(route)
+ firstState.complete(Unit)
+ }
+ "reject" -> throw HostError(if (wire.text("code") == "unsupportedVersion") 426 else 403,
+ wire.text("message") ?: "This device isn't allowed on the computer. Pair it again.")
+ "f" -> {
+ val current = requireNotNull(opener) { "Encrypted frame arrived before the handshake" }
+ val counter = requireNotNull(wire["c"]?.jsonPrimitive?.longOrNull)
+ val data = requireNotNull(wire.text("d")).decodeBase64Url()
+ val message = current.open(Frame(counter, data))
+ if (message != null) handleInner(Json.parseToJsonElement(message.toString(Charsets.UTF_8)).jsonObject)
+ }
+ "pong" -> Unit
+ "mbox.ok", "mbox.err", "mbox.cancelled", "mbox.gone", "mbox.items" -> {
+ val key = if (wire.text("t") == "mbox.items") "list" else requireNotNull(wire.text("nonce"))
+ mailboxCalls.remove(key)?.complete(wire)
+ }
+ "mbox.delivered", "mbox.failed", "mbox.expired" -> {
+ if (!mailboxUpdates.tryEmit(wire)) throw IOException("Mailbox updates fell behind. Reconnect to reconcile.")
+ }
+ else -> Unit
+ }
+ }
+
+ private suspend fun handleInner(message: JsonObject) {
+ val id = requireNotNull(message["id"]?.jsonPrimitive?.longOrNull) { "Missing RPC ID" }
+ require(id in 1..0xffff_ffffL) { "Invalid RPC ID" }
+ when {
+ "ev" in message -> {
+ val events = streams[id] ?: return
+ // Bounded suspension reaches the socket reader instead of dropping catch-up.
+ // A closed subscription is expected when the user leaves that screen.
+ try { events.send(message.getValue("ev").jsonObject) }
+ catch (_: kotlinx.coroutines.channels.ClosedSendChannelException) { }
+ catch (error: CancellationException) { val task = kotlinx.coroutines.currentCoroutineContext(); task.ensureActive() }
+ }
+ message["end"]?.jsonPrimitive?.booleanOrNull == true -> streams.remove(id)?.close()
+ "err" in message -> {
+ val detail = message.getValue("err").jsonObject
+ val failure = HostError(detail["status"]?.jsonPrimitive?.longOrNull?.toInt() ?: 500,
+ detail.text("message") ?: "The computer could not complete the request.")
+ calls.remove(id)?.completeExceptionally(failure)
+ streams.remove(id)?.close(failure)
+ }
+ "ok" in message -> calls.remove(id)?.complete(message.getValue("ok"))
+ else -> throw IOException("Invalid RPC response")
+ }
+ }
+
+ suspend fun awaitReady(timeoutMillis: Long = 15_000) {
+ val current = deadline(timeoutMillis, "The computer didn't finish connecting.") { state.first { it !is LinkState.Connecting } }
+ when (current) {
+ is LinkState.Ready -> Unit
+ is LinkState.ComputerOffline -> throw IOException("The computer is offline.")
+ is LinkState.Failed -> if (current.status != null) throw HostError(current.status, current.message) else throw IOException(current.message)
+ LinkState.Connecting -> error("Unreachable")
+ }
+ }
+
+ suspend fun call(method: String, body: JsonElement = JsonNull, timeoutMillis: Long = 20_000): JsonElement {
+ awaitReady(timeoutMillis)
+ require(!pairing || method == "pair") { "A pairing channel only accepts pair" }
+ val id = nextId()
+ val result = CompletableDeferred<JsonElement>()
+ calls[id] = result
+ try {
+ val request = buildJsonObject { put("id", id); put("m", method); put("b", body) }
+ sendInner(request)
+ val response = deadline(timeoutMillis, "The computer didn't respond in time. Check the result before retrying.") { result.await() }
+ return response
+ } finally {
+ if (calls.remove(id) != null) cancelRemote(id)
+ }
+ }
+
+ fun events(since: Long = 0): Flow<JsonObject> = subscribe("events", buildJsonObject { put("since", since); put("client", "android") })
+
+ fun subscribe(kind: String, body: JsonObject): Flow<JsonObject> = flow {
+ awaitReady()
+ require(!pairing)
+ val id = nextId()
+ val events = Channel<JsonObject>(256)
+ streams[id] = events
+ try {
+ sendInner(buildJsonObject {
+ put("id", id); put("sub", kind); put("b", body)
+ })
+ for (event in events) emit(event)
+ } finally {
+ streams.remove(id)
+ events.cancel()
+ cancelRemote(id)
+ }
+ }
+
+ suspend fun enqueue(send: PendingSend) {
+ require(route == HostRoute.Relay && !pairing && send.files.isEmpty()) { "Only text can wait in the relay mailbox." }
+ val inner = buildJsonObject {
+ put("m", "send"); put("ts", System.currentTimeMillis())
+ put("b", buildJsonObject { put("botId", send.botId); put("text", send.text); put("clientNonce", send.nonce)
+ send.threadId?.let { put("threadId", it) } })
+ }
+ val blob = RelayCrypto.sealMailbox(inner.toString().toByteArray(), computer, identity, send.nonce)
+ val result = mailboxRequest(send.nonce, buildJsonObject { put("t", "mbox.put"); put("nonce", send.nonce); put("d", blob) })
+ if (result.text("t") == "mbox.err") throw IOException(result.text("code") ?: "The relay couldn't queue this message.")
+ }
+
+ suspend fun queued(): JsonObject = listLock.withLock {
+ mailboxRequest("list", buildJsonObject { put("t", "mbox.list") })
+ }
+
+ suspend fun cancelQueued(nonce: String): String {
+ val result = mailboxRequest(nonce, buildJsonObject { put("t", "mbox.cancel"); put("nonce", nonce) })
+ return if (result.text("t") == "mbox.cancelled") "cancelled" else result.text("state") ?: "unknown"
+ }
+
+ private suspend fun mailboxRequest(key: String, message: JsonObject): JsonObject {
+ require(route == HostRoute.Relay && !pairing)
+ val deferred = CompletableDeferred<JsonObject>()
+ check(mailboxCalls.putIfAbsent(key, deferred) == null) { "This mailbox action is already pending." }
+ try {
+ writer.withLock { check(!closed); socket.send(message.toString()) }
+ val response = deadline(15_000, "The relay didn't respond in time. Reconnect to check delivery.") { deferred.await() }
+ return response
+ } finally { mailboxCalls.remove(key, deferred) }
+ }
+
+ private fun nextId(): Long {
+ val id = ids.incrementAndGet()
+ require(id <= 0xffff_ffffL) { "Channel must be replaced before request IDs wrap" }
+ return id
+ }
+
+ private suspend fun sendInner(message: JsonObject) {
+ writer.withLock {
+ if (closed) throw IOException("Connection to the computer ended.")
+ val current = sealer ?: throw IOException("The computer isn't connected.")
+ val frames = current.seal(message.toString().toByteArray())
+ try {
+ for (frame in frames) socket.send(buildJsonObject {
+ put("t", "f"); put("c", frame.counter); put("d", frame.data.base64Url())
+ }.toString())
+ } catch (error: Throwable) {
+ // A failed writer consumed counters. This channel can no longer be reused.
+ fail(error)
+ throw error
+ }
+ }
+ }
+
+ private fun cancelRemote(id: Long) {
+ scope.launch {
+ try { sendInner(buildJsonObject { put("id", id); put("cancel", true) }) }
+ catch (error: CancellationException) { throw error }
+ catch (_: Exception) { /* The owner will reconnect; an uncertain mutation is never replayed here. */ }
+ }
+ }
+
+ private fun dropPending(error: Throwable) {
+ calls.keys.toList().forEach { calls.remove(it)?.completeExceptionally(error) }
+ streams.keys.toList().forEach { streams.remove(it)?.close(error) }
+ }
+
+ private fun fail(error: Throwable) {
+ if (closed) return
+ mutableState.value = LinkState.Failed(error.message ?: "Can't reach the computer.", (error as? HostError)?.status)
+ firstState.completeExceptionally(error)
+ dropPending(error)
+ close()
+ }
+
+ override fun close() {
+ if (closed) return
+ closed = true
+ if (mutableState.value !is LinkState.Failed) mutableState.value = LinkState.Failed("Connection closed.")
+ firstState.cancel()
+ dropPending(IOException("Connection closed."))
+ mailboxCalls.keys.toList().forEach { mailboxCalls.remove(it)?.completeExceptionally(IOException("Relay connection closed.")) }
+ socket.close()
+ scope.cancel()
+ }
+}
+
+internal fun JsonObject.text(key: String): String? = this[key]?.takeUnless { it == JsonNull }?.jsonPrimitive?.content
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Frames.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Frames.kt
new file mode 100644
index 00000000..f32242ac
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Frames.kt
@@ -0,0 +1,38 @@
+package com.codync.android.core
+
+import java.io.ByteArrayOutputStream
+
+internal data class Frame(val counter: Long, val data: ByteArray)
+
+internal class FrameSealer(private val key: ByteArray) {
+ private var counter = 0L
+ fun seal(message: ByteArray): List<Frame> {
+ require(message.size <= RelayCrypto.MAX_OUTBOUND) { "Message is too large" }
+ val count = maxOf(1, (message.size + RelayCrypto.CHUNK_SIZE - 1) / RelayCrypto.CHUNK_SIZE)
+ require(counter + count <= RelayCrypto.MAX_COUNTER) { "Channel must be rekeyed" }
+ return (0 until count).map { index ->
+ val from = index * RelayCrypto.CHUNK_SIZE
+ val to = minOf(from + RelayCrypto.CHUNK_SIZE, message.size)
+ val frame = Frame(counter, RelayCrypto.sealFrame(key, counter, index == count - 1, message.copyOfRange(from, to)))
+ counter++
+ frame
+ }
+ }
+}
+
+internal class FrameOpener(private val key: ByteArray, private val limit: Int = RelayCrypto.MAX_INBOUND) {
+ private var counter = 0L
+ private val buffer = ByteArrayOutputStream()
+ fun open(frame: Frame): ByteArray? {
+ require(frame.counter == counter) { "Encrypted frame is out of order" }
+ val (final, chunk) = RelayCrypto.openFrame(key, counter, frame.data)
+ require(buffer.size() + chunk.size <= limit) { "Message is too large" }
+ counter++
+ buffer.write(chunk)
+ if (!final) return null
+ val message = buffer.toByteArray()
+ buffer.reset()
+ return message
+ }
+}
+
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Handshake.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Handshake.kt
new file mode 100644
index 00000000..8ddebe69
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Handshake.kt
@@ -0,0 +1,36 @@
+package com.codync.android.core
+
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+
+internal class Handshake(
+ computer: Computer,
+ private val identity: DeviceIdentity,
+ private val ephemeral: ByteArray = RelayCrypto.randomBytes(32),
+ private val nonce: ByteArray = RelayCrypto.randomBytes(32),
+) {
+ private val hostKey = computer.signKey.decodeBase64Url(32)
+ private val cid = computer.id.decodeBase64Url(16)
+ private val ekD = RelayCrypto.agreementPublic(ephemeral)
+ init {
+ computer.validate()
+ require(ephemeral.size == 32 && nonce.size == 32)
+ }
+ fun hello(pair: Boolean): JsonObject = buildJsonObject {
+ put("t", "hello")
+ put("v", 1)
+ put("dk", identity.publicKey)
+ put("ek", ekD.base64Url())
+ put("n", nonce.base64Url())
+ put("sig", identity.sign(RelayCrypto.hs1Input(cid, identity.deviceKey, ekD, nonce)).base64Url())
+ if (pair) put("pair", true)
+ }
+ fun finish(ekH: ByteArray, signature: ByteArray): RelayCrypto.ChannelKeys {
+ require(ekH.size == 32 && signature.size == 64)
+ val transcript = RelayCrypto.transcriptHash(cid, identity.deviceKey, ekD, nonce, ekH)
+ if (!RelayCrypto.verify(hostKey, transcript, signature)) throw SecurityException("This computer's identity changed. Pair it again.")
+ return RelayCrypto.channelKeys(RelayCrypto.sharedSecret(ephemeral, ekH), transcript)
+ }
+}
+
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
new file mode 100644
index 00000000..f832a369
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
@@ -0,0 +1,97 @@
+package com.codync.android.core
+
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.decodeFromJsonElement
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+
+@Serializable
+data class Bot(
+ val id: String,
+ val name: String = "",
+ val kind: String = "agent",
+ val members: List<String> = emptyList(),
+ val description: String = "",
+ val avatarColor: String = "blue",
+ val avatarShape: String = "blob",
+ val command: String? = null,
+ val cwd: String = "",
+ val managedWorkspace: Boolean = false,
+ val permission: String = "ask",
+ val model: String? = null,
+ /** The model's own settings (effort, fast…): agent option id → value. */
+ val modelOptions: Map<String, String> = emptyMap(),
+ /** The agent's Fast mode: faster replies for more usage. */
+ val fastMode: Boolean = false,
+ /** `unknown` (no session yet), `offered`, `unsupported` or `refused` (`fastModeIssue` says why). */
+ val fastModeSupport: String = "unknown",
+ val fastModeIssue: String? = null,
+ val notify: Boolean? = null,
+ val connectors: List<String> = emptyList(),
+ val skills: List<String> = emptyList(),
+ val computer: Boolean = false,
+ val autoName: Boolean = false,
+ val createdAt: Long = 0,
+ val startedAt: Long? = null,
+ val workingChat: String? = null,
+ val workingThread: String? = null,
+ val lastMessage: String? = null,
+ val lastAt: Long = 0,
+ val status: String = "idle",
+ val activity: String = "",
+ val backend: String = "",
+ val pinned: Boolean = false,
+ /** Where the user dragged it in the roster, synced by the host to every device. */
+ val position: Int = 0,
+ val hidden: Boolean = false,
+ val unread: Int = 0,
+ val rev: Long = 0,
+ val deleted: Boolean = false,
+) {
+ /** An agent bot unless its agent said it has no Fast mode, or one that has it on (so it can be turned off). */
+ val fastModeShown: Boolean get() = kind != "group" && (fastMode || fastModeSupport != "unsupported")
+
+ /** Why Fast mode isn't in effect, when the agent turned it off itself. */
+ val fastModeRefusal: String? get() = if (fastMode && fastModeSupport == "refused")
+ "The agent turned it off: ${fastModeIssue ?: "not available"}. Switch it off and on to try again." else null
+}
+
+object HostClient {
+ private val json = Json { ignoreUnknownKeys = true }
+
+ suspend fun hello(channel: EncryptedChannel, computer: Computer): Computer {
+ val response = channel.call("hello")
+ val hello = response.jsonObject
+ require(hello.text("computerId") == computer.id && hello.text("signKey") == computer.signKey) {
+ "This computer's identity changed. Pair it again."
+ }
+ val updated = computer.copy(
+ name = hello.text("name")?.takeIf(String::isNotBlank) ?: computer.name,
+ boxKey = hello.text("boxKey") ?: computer.boxKey,
+ urls = hello["urls"]?.jsonArray?.map { it.jsonPrimitive.content }?.filter(::isDirectUrl) ?: computer.urls,
+ cloud = hello.text("cloud"),
+ )
+ updated.validate()
+ return updated
+ }
+
+ suspend fun bots(channel: EncryptedChannel): List<Bot> {
+ // The host exposes its roster through revision-ordered events, like iOS.
+ // This finite read never advances the caller's durable mirror cursor.
+ return deadline(20_000, "The computer didn't send its bots in time.") { botSnapshot(channel.events(0)) }
+ }
+
+ fun decodeBot(event: JsonObject): Bot? {
+ if (event.text("type") != "bot") return null
+ return decode(event.getValue("bot").jsonObject)
+ }
+
+ fun decode(value: JsonObject): Bot {
+ val bot = json.decodeFromJsonElement<Bot>(value)
+ require(bot.id.isNotBlank() && bot.rev >= 0 && (bot.deleted || bot.name.isNotBlank())) { "The computer sent an invalid bot update." }
+ return bot
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt
new file mode 100644
index 00000000..3511c5f2
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt
@@ -0,0 +1,112 @@
+package com.codync.android.core
+
+import java.io.IOException
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withTimeoutOrNull
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.put
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import okhttp3.Request
+
+object HostConnector {
+ suspend fun pair(pairing: Pairing, identity: DeviceIdentity, deviceName: String): Computer {
+ require(deviceName.isNotBlank() && deviceName.codePointCount(0, deviceName.length) <= 100)
+ val channel = connect(pairing.computer, identity, pairing)
+ try {
+ val response = try {
+ channel.call("pair", buildJsonObject {
+ put("code", pairing.code); put("name", deviceName); put("platform", "android")
+ }, timeoutMillis = 30_000)
+ } catch (error: HostError) {
+ // Hosts from before Android support turn the platform down: say what to do, not the wire error.
+ if (error.status == 400 && "platform" in error.message) throw HostError(400, "Update Codync on this computer to pair an Android phone.")
+ throw error
+ }
+ val result = response.jsonObject
+ require(result.text("computerId") == pairing.computer.id) { "This computer's identity changed. Pair it again." }
+ return pairing.computer.copy(name = result.text("name")?.takeIf(String::isNotBlank) ?: pairing.computer.name)
+ } finally {
+ channel.close()
+ }
+ }
+
+ suspend fun connect(computer: Computer, identity: DeviceIdentity): EncryptedChannel = connect(computer, identity, null)
+
+ private suspend fun connect(computer: Computer, identity: DeviceIdentity, pairing: Pairing?): EncryptedChannel {
+ computer.validate()
+ if (computer.route == ConnectionRoute.CloudflareFirst && computer.cloud != null) {
+ try { return relay(computer, identity, pairing) }
+ catch (error: CancellationException) { throw error }
+ catch (error: SecurityException) { throw error }
+ catch (_: IOException) { /* Try the direct candidates below. */ }
+ }
+ var directError: Throwable? = null
+ var ownedWinner: EncryptedChannel? = null
+ val direct = try { coroutineScope {
+ val attempts = Channel<Result<EncryptedChannel>>(Channel.UNLIMITED,
+ onUndeliveredElement = { result -> result.getOrNull()?.close() })
+ val jobs = computer.urls.map { base -> launch {
+ var channel: EncryptedChannel? = null
+ try {
+ val url = base.toHttpUrl().newBuilder().encodedPath("/channel").query("v=1").build()
+ val socket = OkHttpChannelSocket.dial(Request.Builder().url(url).build())
+ channel = EncryptedChannel(socket, HostRoute.Direct, computer, identity, pairing != null)
+ val started = channel.start()
+ attempts.send(Result.success(started))
+ channel = null // Ownership passed to the result queue.
+ } catch (error: CancellationException) {
+ throw error
+ } catch (error: Throwable) {
+ attempts.send(Result.failure(error))
+ } finally { channel?.close() }
+ } }
+ try {
+ val budget = if (computer.route == ConnectionRoute.DirectOnly || computer.cloud == null) 15_000L else 1_500L
+ withTimeoutOrNull(budget) {
+ var winner: EncryptedChannel? = null
+ repeat(computer.urls.size) {
+ if (winner == null) {
+ val outcome = attempts.receive()
+ winner = outcome.getOrNull()
+ ownedWinner = winner
+ directError = outcome.exceptionOrNull() ?: directError
+ }
+ }
+ winner
+ }
+ } finally {
+ jobs.forEach { it.cancel() }
+ attempts.cancel()
+ }
+ } } catch (error: Throwable) { ownedWinner?.close(); throw error }
+ if (direct != null) return direct
+ if (directError is SecurityException) throw requireNotNull(directError)
+ if (computer.cloud != null && computer.route == ConnectionRoute.Automatic) return relay(computer, identity, pairing)
+ throw directError ?: IOException("Can't reach the computer. Check its connection and try again.")
+ }
+
+ private suspend fun relay(computer: Computer, identity: DeviceIdentity, pairing: Pairing?): EncryptedChannel {
+ val base = requireNotNull(computer.cloud).toHttpUrl()
+ val url = base.newBuilder().addPathSegments("v1/relay/device/${computer.id}").query("v=1")
+ .apply { if (pairing != null) addQueryParameter("pair", pairing.offerId) }.build()
+ var socket: ChannelSocket? = null
+ for (attempt in 0..3) {
+ val header = RequestSigner.header(identity, "GET", url)
+ val request = Request.Builder().url(url).header("Codync-Sig", header).build()
+ try { socket = OkHttpChannelSocket.dial(request); break }
+ catch (error: SocketRefused) {
+ if (error.status == 426) throw HostError(426, "Update Codync to connect to this computer.")
+ if (error.status != 403) throw error
+ if (attempt == 3) throw HostError(403, "This device isn't allowed on the computer. Pair it again.")
+ // The new device can reach the relay before the host's post-pairing ACL does.
+ delay((attempt + 1) * 500L)
+ }
+ }
+ return EncryptedChannel(requireNotNull(socket), HostRoute.Relay, computer, identity, pairing != null).start()
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostFiles.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostFiles.kt
new file mode 100644
index 00000000..c720e1c2
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostFiles.kt
@@ -0,0 +1,98 @@
+package com.codync.android.core
+
+import java.io.File
+import java.io.IOException
+import java.util.Base64
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.*
+
+/** The existing host file protocol, with memory bounded to one chunk. */
+class HostFiles(private val call: suspend (String, JsonObject, Long) -> JsonElement) {
+ constructor(channel: EncryptedChannel) : this({ method, body, timeout -> channel.call(method, body, timeout) })
+
+ suspend fun upload(botId: String, id: String, file: OutgoingFile, progress: (Long) -> Unit = {}) = withContext(Dispatchers.IO) {
+ val source = File(file.path)
+ require(file.size in 0..MAX_FILE_BYTES && source.length() == file.size && source.isFile) { "The selected file is no longer available. Choose it again." }
+ source.inputStream().use { input ->
+ var offset = 0L
+ do {
+ val buffer = ByteArray(minOf(CHUNK_BYTES.toLong(), file.size - offset).toInt())
+ var count = 0
+ while (count < buffer.size) {
+ val read = input.read(buffer, count, buffer.size - count)
+ if (read < 0) break
+ count += read
+ }
+ val chunk = if (count == buffer.size) buffer else buffer.copyOf(count)
+ require(offset + chunk.size <= file.size) { "The selected file changed during upload." }
+ val done = offset + chunk.size == file.size
+ require(done || chunk.isNotEmpty()) { "The selected file changed during upload." }
+ call("upload", buildJsonObject {
+ put("botId", botId); put("uploadId", id); put("name", file.name)
+ put("offset", offset); put("data", Base64.getEncoder().encodeToString(chunk)); put("done", done)
+ }, 60_000)
+ offset += chunk.size
+ progress(offset)
+ } while (offset < file.size)
+ require(input.read() == -1) { "The selected file changed during upload." }
+ }
+ }
+
+ suspend fun download(botId: String, file: Attachment, destination: File) = withContext(Dispatchers.IO) {
+ require(file.size in 0..MAX_FILE_BYTES)
+ val partial = File(destination.parentFile, destination.name + ".partial")
+ try {
+ partial.outputStream().use { output ->
+ var offset = 0L
+ do {
+ val result = call("readUpload", buildJsonObject { put("botId", botId); put("uploadId", file.id); put("offset", offset) }, 60_000).jsonObject
+ val size = result.getValue("size").jsonPrimitive.long
+ require(size == file.size) { "The computer returned a different file size." }
+ val bytes = Base64.getDecoder().decode(result.getValue("data").jsonPrimitive.content)
+ require(bytes.size <= CHUNK_BYTES && offset + bytes.size <= size && (bytes.isNotEmpty() || size == 0L)) {
+ "The computer returned an invalid file chunk."
+ }
+ output.write(bytes)
+ offset += bytes.size
+ } while (offset < file.size)
+ output.fd.sync()
+ }
+ if (!partial.renameTo(destination)) throw IOException("Couldn't save the downloaded file.")
+ } finally { partial.delete() }
+ }
+
+ /** A small text file the host prepared (a memory export), read chunk by chunk. */
+ suspend fun readText(botId: String, id: String): String {
+ val bytes = java.io.ByteArrayOutputStream()
+ var offset = 0L
+ do {
+ val result = call("readUpload", buildJsonObject { put("botId", botId); put("uploadId", id); put("offset", offset) }, 60_000).jsonObject
+ val size = result.getValue("size").jsonPrimitive.long
+ val chunk = Base64.getDecoder().decode(result.getValue("data").jsonPrimitive.content)
+ require(size in 0..MAX_FILE_BYTES && chunk.size <= CHUNK_BYTES && offset + chunk.size <= size && (chunk.isNotEmpty() || size == 0L)) {
+ "The computer returned an invalid file chunk."
+ }
+ bytes.write(chunk)
+ offset += chunk.size
+ } while (offset < size)
+ return bytes.toString(Charsets.UTF_8)
+ }
+
+ /** Text too big for one call (a memory backup), sent as an upload. */
+ suspend fun uploadText(botId: String, id: String, name: String, text: String) {
+ val data = text.toByteArray()
+ require(data.size <= MAX_FILE_BYTES) { "This backup is too large." }
+ var offset = 0
+ do {
+ val end = minOf(offset + CHUNK_BYTES, data.size)
+ call("upload", buildJsonObject {
+ put("botId", botId); put("uploadId", id); put("name", name); put("offset", offset)
+ put("data", Base64.getEncoder().encodeToString(data.copyOfRange(offset, end))); put("done", end == data.size)
+ }, 60_000)
+ offset = end
+ } while (offset < data.size)
+ }
+
+ companion object { const val CHUNK_BYTES = 384 * 1024 }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Management.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Management.kt
new file mode 100644
index 00000000..f319b344
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Management.kt
@@ -0,0 +1,74 @@
+package com.codync.android.core
+
+import kotlinx.serialization.SerialName
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.*
+
+/** A group uses the existing bot endpoints; it never owns an agent or workspace. */
+data class GroupDraft(
+ val id: String? = null,
+ val name: String = "",
+ val description: String = "",
+ val members: List<String> = emptyList(),
+ val pinned: Boolean = false,
+) {
+ fun body(roster: List<Bot>): JsonObject {
+ val picked = members.distinct().map { id ->
+ requireNotNull(roster.firstOrNull { it.id == id && !it.deleted && it.kind != "group" }) {
+ "A member is no longer available. Remove it before saving."
+ }
+ }
+ require(picked.isNotEmpty()) { "Choose at least one bot." }
+ return buildJsonObject {
+ id?.let { put("id", it) }
+ put("kind", "group")
+ put("name", name.trim().ifEmpty { picked.joinToString(", ") { it.name } })
+ put("description", description.trim())
+ put("members", JsonArray(picked.map { JsonPrimitive(it.id) }))
+ put("pinned", pinned)
+ }
+ }
+
+ companion object {
+ fun from(bot: Bot): GroupDraft {
+ require(bot.kind == "group")
+ return GroupDraft(bot.id, bot.name, bot.description, bot.members, bot.pinned)
+ }
+ }
+}
+
+/** One Engram memory, as the host lists it; unknown kinds and fields pass through. */
+@Serializable data class MemoryFact(
+ val id: String, val title: String = "", val content: String, val createdAt: Long = 0, val kind: String = "",
+ val memoryType: String = "", val scope: String = "project", val topicKey: String? = null, val pinned: Boolean = false,
+ val reviewAfter: String? = null, val revisionCount: Int = 0, val source: String? = null,
+)
+
+@Serializable data class MemoryListing(val facts: List<MemoryFact> = emptyList(), val total: Int = 0, val nextOffset: Int? = null) {
+ companion object {
+ fun decode(value: JsonElement): MemoryListing {
+ val listing = WireJson.decodeFromJsonElement<MemoryListing>(value)
+ require(listing.facts.all { it.id.isNotBlank() && it.content.isNotBlank() }) { "The computer sent invalid memory." }
+ return listing
+ }
+ }
+}
+
+/** A memory's past versions and the session it came from. */
+@Serializable data class MemoryDetail(val fact: MemoryFact, val history: History, val timeline: Timeline) {
+ @Serializable data class History(val result: String, @SerialName("history_cursor") val cursor: Int? = null)
+ @Serializable data class Timeline(val result: String)
+}
+
+data class MemoryDraft(val botId: String, val id: String? = null, val title: String = "", val content: String = "",
+ val scope: String = "project", val memoryType: String = "learning", val topicKey: String = "") {
+ fun body(): JsonObject = buildJsonObject {
+ put("botId", botId); id?.let { put("id", it) }; put("title", title); put("content", content)
+ put("scope", scope); put("memoryType", memoryType); put("topicKey", topicKey)
+ }
+
+ companion object {
+ fun of(botId: String, fact: MemoryFact?) = MemoryDraft(botId, fact?.id, fact?.title.orEmpty(), fact?.content.orEmpty(),
+ fact?.scope ?: "project", fact?.memoryType ?: "learning", fact?.topicKey.orEmpty())
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/MarkdownBlocks.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/MarkdownBlocks.kt
new file mode 100644
index 00000000..f01c2449
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/MarkdownBlocks.kt
@@ -0,0 +1,83 @@
+package com.codync.android.core
+
+/**
+ * Block-level Markdown as replies use it: paragraphs, headings, nested lists, quotes, rules,
+ * tables and fenced code. A line-for-line port of CodyncUI `MarkdownBlocks.swift` (the desktop
+ * app has the same), so every client splits a reply the same way.
+ */
+object MarkdownBlocks {
+ sealed interface Block {
+ data class Paragraph(val text: String) : Block
+ data class Heading(val text: String, val level: Int) : Block
+ data class Bullet(val text: String, val marker: String, val depth: Int = 0) : Block
+ data class Quote(val text: String) : Block
+ data class Code(val text: String, val language: String) : Block
+ data class Table(val header: List<String>, val rows: List<List<String>>) : Block
+ data object Rule : Block
+ }
+
+ fun parse(source: String): List<Block> {
+ val blocks = mutableListOf<Block>()
+ val paragraph = mutableListOf<String>()
+ val table = mutableListOf<String>()
+ var code: MutableList<String>? = null
+ var language = ""
+
+ fun flush() {
+ if (paragraph.isNotEmpty()) { blocks += Block.Paragraph(paragraph.joinToString("\n")); paragraph.clear() }
+ if (table.isNotEmpty()) {
+ // A header and its `|---|` line make a table; anything less stays text.
+ blocks += if (table.size >= 2 && isTableRule(table[1])) Block.Table(cells(table[0]), table.drop(2).map(::cells))
+ else Block.Paragraph(table.joinToString("\n"))
+ table.clear()
+ }
+ }
+
+ for (raw in source.split("\n")) {
+ val line = raw.trim(' ', '\t')
+ if (line.startsWith("```")) {
+ val open = code
+ if (open != null) { blocks += Block.Code(open.joinToString("\n"), language); code = null }
+ else { flush(); code = mutableListOf(); language = line.drop(3) }
+ continue
+ }
+ code?.let { it += raw; continue }
+ if (line.startsWith("|")) {
+ if (paragraph.isNotEmpty()) flush()
+ table += line
+ continue
+ }
+ if (table.isNotEmpty()) flush()
+ val depth = minOf(raw.takeWhile { it == ' ' || it == '\t' }.length / 2, 3)
+ val hashes = line.indexOfFirst { it != '#' }
+ val dot = line.indexOf('.')
+ when {
+ line.isEmpty() -> flush()
+ line == "---" || line == "***" || line == "___" -> { flush(); blocks += Block.Rule }
+ line.startsWith("#") && hashes > 0 && line[hashes] == ' ' -> {
+ flush(); blocks += Block.Heading(line.substring(hashes).trim(), hashes)
+ }
+ listOf("- ", "* ", "+ ", "• ").any(line::startsWith) -> {
+ flush(); blocks += Block.Bullet(line.drop(2), if (depth > 0) "◦" else "•", depth)
+ }
+ dot > 0 && line.substring(0, dot).all(Char::isDigit) && line.substring(dot + 1).startsWith(" ") -> {
+ flush(); blocks += Block.Bullet(line.substring(dot + 2), line.substring(0, dot + 1), depth)
+ }
+ line.startsWith(">") -> { flush(); blocks += Block.Quote(line.drop(1).trim()) }
+ else -> paragraph += raw
+ }
+ }
+ code?.let { blocks += Block.Code(it.joinToString("\n"), language) }
+ flush()
+ return blocks
+ }
+
+ private fun isTableRule(line: String) = '-' in line && line.all { it in "|-: " }
+
+ private fun cells(line: String): List<String> {
+ var row = line
+ if (row.startsWith("|")) row = row.drop(1)
+ if (row.endsWith("|")) row = row.dropLast(1)
+ return row.split("|").map(String::trim)
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Market.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Market.kt
new file mode 100644
index 00000000..4eadf394
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Market.kt
@@ -0,0 +1,32 @@
+package com.codync.android.core
+
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.SerialName
+
+@Serializable data class InstalledConnector(val id: String, val name: String, val description: String = "",
+ val registryName: String? = null, val kind: String, val command: String? = null, val url: String? = null,
+ val keys: List<String> = emptyList(), val logo: String? = null, val auth: String? = null) {
+ val needsSignIn: Boolean get() = auth == "signedOut"
+}
+@Serializable data class InstalledSkill(val id: String, val name: String, val description: String = "", val source: String, val path: String)
+data class PluginListing(val connectors: List<InstalledConnector>, val skills: List<InstalledSkill>)
+@Serializable data class MarketConnector(val name: String, val title: String, val description: String? = null,
+ val version: String? = null, val website: String? = null, val installed: Boolean = false, val options: List<InstallOption>)
+@Serializable data class InstallOption(val id: String, val kind: String, val label: String, val inputs: List<MarketInput> = emptyList()) {
+ fun complete(values: Map<String, String>): Boolean = inputs.none { it.required && (values[it.name] ?: it.defaultValue.orEmpty()).isBlank() }
+}
+@Serializable data class MarketInput(val name: String, val description: String? = null, val secret: Boolean = false,
+ val required: Boolean = false, @SerialName("default") val defaultValue: String? = null, val placeholder: String? = null)
+@Serializable data class MarketConnectors(val items: List<MarketConnector>, val nextCursor: String? = null)
+@Serializable data class MarketSkill(val source: String, val name: String, val description: String = "", val installed: Boolean = false)
+
+/** Registry metadata stays in memory; rows are revealed by explicit user actions. */
+data class CatalogPage<T>(val items: List<T> = emptyList(), val visibleCount: Int = 12) {
+ val visible: List<T> get() = items.take(visibleCount)
+ val hasHidden: Boolean get() = items.size > visibleCount
+ fun append(page: List<T>, id: (T) -> String): CatalogPage<T> {
+ val known = items.mapTo(mutableSetOf(), id)
+ return copy(items = items + page.filter { known.add(id(it)) })
+ }
+ fun reveal(): CatalogPage<T> = copy(visibleCount = minOf(items.size, visibleCount + 12))
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt
new file mode 100644
index 00000000..9f7d1029
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt
@@ -0,0 +1,45 @@
+package com.codync.android.core
+
+import java.net.URI
+import java.net.URLDecoder
+
+/** A short-lived pairing URL. Only the resulting Computer may be persisted. */
+data class Pairing(val computer: Computer, val code: String) {
+ internal val offerId: String get() = RelayCrypto.offerId(code.decodeBase64Url(16))
+
+ companion object {
+ fun parse(text: String, scheme: String): Pairing {
+ require(text.length <= 16 * 1024) { "This pairing code is damaged. Show a new one on your computer." }
+ val url = try { URI(text.trim()) } catch (error: Exception) {
+ throw IllegalArgumentException("That isn't a Codync pairing code.", error)
+ }
+ require(url.scheme == scheme && url.host == "pair" && url.rawQuery != null) { "That isn't a Codync pairing code." }
+ val params = linkedMapOf<String, String>()
+ try {
+ url.rawQuery.split('&').forEach { part ->
+ val key = URLDecoder.decode(part.substringBefore('='), "UTF-8")
+ val value = URLDecoder.decode(part.substringAfter('=', ""), "UTF-8")
+ require(params.put(key, value) == null) { "Duplicate pairing field" }
+ }
+ require(params["v"] == "3") { "Update Codync on your computer, then show a new pairing code." }
+ val code = requireNotNull(params["code"])
+ code.decodeBase64Url(16)
+ val computer = Computer(
+ id = requireNotNull(params["id"]),
+ name = params["name"]?.takeIf(String::isNotBlank) ?: "My computer",
+ signKey = requireNotNull(params["sk"]),
+ boxKey = requireNotNull(params["bk"]),
+ urls = params["urls"].orEmpty().split(',').filter { it.isNotEmpty() && isDirectUrl(it) }.distinct(),
+ cloud = params["cloud"]?.takeIf(String::isNotEmpty),
+ )
+ computer.validate()
+ require(computer.urls.isNotEmpty() || computer.cloud != null) { "No valid computer address" }
+ return Pairing(computer, code)
+ } catch (error: IllegalArgumentException) {
+ if (params["v"] != "3") throw IllegalArgumentException("Update Codync on your computer, then show a new pairing code.", error)
+ throw IllegalArgumentException("This pairing code is damaged. Show a new one on your computer.", error)
+ }
+ }
+ }
+}
+
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/PairingQr.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/PairingQr.kt
new file mode 100644
index 00000000..eba0e562
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/PairingQr.kt
@@ -0,0 +1,49 @@
+package com.codync.android.core
+
+import com.google.zxing.BinaryBitmap
+import com.google.zxing.DecodeHintType
+import com.google.zxing.PlanarYUVLuminanceSource
+import com.google.zxing.ReaderException
+import com.google.zxing.common.HybridBinarizer
+import com.google.zxing.qrcode.QRCodeReader
+import java.nio.ByteBuffer
+
+sealed interface PairingScan {
+ data class Found(val link: String) : PairingScan
+ data class Invalid(val message: String) : PairingScan
+}
+
+/** Bundled decoding works without Play services, network access or a model download. */
+class PairingQr(private val scheme: String) {
+ private val reader = QRCodeReader()
+ @Synchronized fun decode(pixels: ByteArray, width: Int, height: Int): PairingScan? {
+ require(width > 0 && height > 0 && width.toLong() * height <= MAX_PIXELS && pixels.size.toLong() == width.toLong() * height)
+ val source = PlanarYUVLuminanceSource(pixels, width, height, 0, 0, width, height, false)
+ for (luminance in listOf(source, source.invert())) {
+ try {
+ val result = reader.decode(BinaryBitmap(HybridBinarizer(luminance)), mapOf(DecodeHintType.TRY_HARDER to true))
+ val value = result.text
+ if (!value.startsWith("$scheme://pair?")) return null
+ try { Pairing.parse(value, scheme); return PairingScan.Found(value) }
+ catch (failure: IllegalArgumentException) { return PairingScan.Invalid(failure.message ?: "Show a fresh Codync pairing code on your computer.") }
+ } catch (_: ReaderException) { }
+ finally { reader.reset() }
+ }
+ return null
+ }
+
+ companion object {
+ private const val MAX_PIXELS = 4L * 1024 * 1024
+ /** Camera Y planes can have padding, a position offset, and non-unit pixel strides. */
+ fun luminance(buffer: ByteBuffer, width: Int, height: Int, rowStride: Int, pixelStride: Int): ByteArray {
+ require(width > 0 && height > 0 && width.toLong() * height <= MAX_PIXELS && pixelStride > 0)
+ val lastPixel = (width - 1L) * pixelStride
+ require(rowStride.toLong() > lastPixel)
+ val required = (height - 1L) * rowStride + lastPixel + 1
+ require(required <= buffer.remaining()) { "Incomplete camera image" }
+ val source = buffer.duplicate()
+ val base = source.position()
+ return ByteArray(width * height) { index -> source.get(base + index / width * rowStride + index % width * pixelStride) }
+ }
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/PushRelay.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/PushRelay.kt
new file mode 100644
index 00000000..441d0095
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/PushRelay.kt
@@ -0,0 +1,47 @@
+package com.codync.android.core
+
+import java.io.IOException
+import java.util.concurrent.TimeUnit
+import kotlinx.coroutines.suspendCancellableCoroutine
+import kotlinx.serialization.json.*
+import okhttp3.*
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.RequestBody.Companion.toRequestBody
+
+object PushRelay {
+ private val http = OkHttpClient.Builder().followRedirects(false).followSslRedirects(false).callTimeout(15, TimeUnit.SECONDS).build()
+
+ suspend fun ticket(base: String, token: String, contextId: String, computerId: String, botId: String? = null, taskId: String? = null): String {
+ require(isCloudUrl(base)) { "Invalid push relay address" }
+ require(token.length in 20..4096 && token.all { it.isLetterOrDigit() || it in "_:.-" }) { "Invalid push token" }
+ val body = buildJsonObject {
+ put("provider", "fcm"); put("token", token); put("ctx", contextId); put("computerId", computerId)
+ put("kind", if (botId == null) "alert" else "liveactivity")
+ botId?.let { put("botId", it) }
+ taskId?.let { put("taskId", it) }
+ }
+ val url = base.trimEnd('/').toHttpUrl().newBuilder().addPathSegment("register").build()
+ val request = Request.Builder().url(url).post(body.toString().toRequestBody("application/json".toMediaType())).build()
+ val call = http.newCall(request)
+ return suspendCancellableCoroutine { continuation ->
+ continuation.invokeOnCancellation { call.cancel() }
+ call.enqueue(object : Callback {
+ override fun onFailure(call: Call, e: IOException) { continuation.resumeWith(Result.failure(e)) }
+ override fun onResponse(call: Call, response: Response) {
+ try {
+ val ticket = response.use {
+ if (!response.isSuccessful) throw IOException("Push registration failed (${response.code}).")
+ val source = requireNotNull(response.body).source()
+ if (source.request(16_385)) throw IOException("Push response is too large.")
+ val value = Json.parseToJsonElement(source.readUtf8()).jsonObject.getValue("ticket").jsonPrimitive.content
+ require(value.isNotBlank() && value.length <= 8192) { "Invalid push ticket" }
+ value
+ }
+ continuation.resumeWith(Result.success(ticket))
+ } catch (error: Exception) { continuation.resumeWith(Result.failure(error)) }
+ }
+ })
+ }
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/RelayCrypto.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/RelayCrypto.kt
new file mode 100644
index 00000000..cb9f3180
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/RelayCrypto.kt
@@ -0,0 +1,149 @@
+package com.codync.android.core
+
+import java.security.MessageDigest
+import java.security.SecureRandom
+import javax.crypto.Mac
+import javax.crypto.spec.SecretKeySpec
+import org.bouncycastle.crypto.modes.ChaCha20Poly1305
+import org.bouncycastle.crypto.params.AEADParameters
+import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters
+import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters
+import org.bouncycastle.crypto.params.KeyParameter
+import org.bouncycastle.crypto.params.X25519PrivateKeyParameters
+import org.bouncycastle.crypto.params.X25519PublicKeyParameters
+import org.bouncycastle.crypto.signers.Ed25519Signer
+
+/** Protocol-v1 primitives. The algorithms come from BC; labels/framing belong to Codync. */
+object RelayCrypto {
+ const val CHUNK_SIZE = 256 * 1024
+ const val MAX_OUTBOUND = 1024 * 1024
+ const val MAX_INBOUND = 16 * 1024 * 1024
+ const val MAX_COUNTER = 1L shl 32
+ private val random = SecureRandom()
+
+ internal fun label(value: String): ByteArray = value.toByteArray(Charsets.UTF_8)
+ internal fun randomBytes(size: Int): ByteArray = ByteArray(size).also(random::nextBytes)
+ internal fun sha256(vararg parts: ByteArray): ByteArray {
+ val digest = MessageDigest.getInstance("SHA-256")
+ parts.forEach(digest::update)
+ return digest.digest()
+ }
+
+ fun computerId(signKey: ByteArray): String {
+ require(signKey.size == 32) { "Invalid host signing key" }
+ return sha256(signKey).copyOf(16).base64Url()
+ }
+
+ fun sasCommit(deviceKey: ByteArray, deviceNonce: ByteArray): ByteArray {
+ require(deviceKey.size == 32 && deviceNonce.size == 32) { "Invalid access request" }
+ return sha256(label("codync/sascommit/v1"), deviceKey, deviceNonce)
+ }
+
+ fun sasCode(hostSignKey: ByteArray, deviceKey: ByteArray, deviceNonce: ByteArray, hostNonce: ByteArray): String {
+ require(listOf(hostSignKey, deviceKey, deviceNonce, hostNonce).all { it.size == 32 }) { "Invalid access request" }
+ val hash = sha256(label("codync/sas/v2"), hostSignKey, deviceKey, deviceNonce, hostNonce)
+ val number = hash.take(4).fold(0L) { value, byte -> (value shl 8) or (byte.toLong() and 255) }
+ return (number % 1_000_000).toString().padStart(6, '0')
+ }
+
+ internal fun offerId(code: ByteArray): String = sha256(label("codync/offer/v1"), code).copyOf(16).base64Url()
+ internal fun signingPublic(seed: ByteArray): ByteArray = Ed25519PrivateKeyParameters(seed, 0).generatePublicKey().encoded
+ internal fun agreementPublic(seed: ByteArray): ByteArray = X25519PrivateKeyParameters(seed, 0).generatePublicKey().encoded
+
+ internal fun sign(seed: ByteArray, input: ByteArray): ByteArray {
+ require(seed.size == 32)
+ val signer = Ed25519Signer()
+ signer.init(true, Ed25519PrivateKeyParameters(seed, 0))
+ signer.update(input, 0, input.size)
+ return signer.generateSignature()
+ }
+
+ internal fun verify(key: ByteArray, input: ByteArray, signature: ByteArray): Boolean {
+ if (key.size != 32 || signature.size != 64) return false
+ val verifier = Ed25519Signer()
+ verifier.init(false, Ed25519PublicKeyParameters(key, 0))
+ verifier.update(input, 0, input.size)
+ return verifier.verifySignature(signature)
+ }
+
+ internal fun sharedSecret(privateKey: ByteArray, publicKey: ByteArray): ByteArray {
+ require(privateKey.size == 32 && publicKey.size == 32) { "Invalid agreement key" }
+ val result = ByteArray(32)
+ try {
+ X25519PrivateKeyParameters(privateKey, 0).generateSecret(X25519PublicKeyParameters(publicKey, 0), result, 0)
+ } catch (error: IllegalStateException) {
+ throw SecurityException("Invalid zero shared secret", error)
+ }
+ if (result.all { it == 0.toByte() }) throw SecurityException("Invalid zero shared secret")
+ return result
+ }
+
+ internal fun hmac(key: ByteArray, input: ByteArray): ByteArray {
+ val mac = Mac.getInstance("HmacSHA256")
+ mac.init(SecretKeySpec(key, "HmacSHA256"))
+ return mac.doFinal(input)
+ }
+ internal fun extract(salt: ByteArray, secret: ByteArray): ByteArray = hmac(salt, secret)
+ internal fun expand(prk: ByteArray, info: String): ByteArray = hmac(prk, label(info) + byteArrayOf(1))
+
+ internal data class ChannelKeys(val prk: ByteArray, val d2h: ByteArray, val h2d: ByteArray)
+
+ internal fun channelKeys(secret: ByteArray, transcript: ByteArray): ChannelKeys {
+ val prk = extract(transcript, secret)
+ return ChannelKeys(prk, expand(prk, "codync/d2h/v1"), expand(prk, "codync/h2d/v1"))
+ }
+
+ internal fun hs1Input(cid: ByteArray, dk: ByteArray, ekD: ByteArray, nonce: ByteArray): ByteArray =
+ label("codync/hs1/v1") + cid + dk + ekD + nonce
+
+ internal fun transcriptHash(cid: ByteArray, dk: ByteArray, ekD: ByteArray, nonce: ByteArray, ekH: ByteArray): ByteArray =
+ sha256(label("codync/hs2/v1"), cid, dk, ekD, nonce, ekH)
+
+ internal fun crypt(encrypt: Boolean, key: ByteArray, nonce: ByteArray, aad: ByteArray, input: ByteArray): ByteArray {
+ val cipher = ChaCha20Poly1305()
+ cipher.init(encrypt, AEADParameters(KeyParameter(key), 128, nonce, aad))
+ val output = ByteArray(cipher.getOutputSize(input.size))
+ try {
+ val written = cipher.processBytes(input, 0, input.size, output, 0)
+ val final = cipher.doFinal(output, written)
+ return output.copyOf(written + final)
+ } catch (error: org.bouncycastle.crypto.InvalidCipherTextException) {
+ throw SecurityException("Encrypted message authentication failed", error)
+ }
+ }
+
+ internal fun sealFrame(key: ByteArray, counter: Long, final: Boolean, chunk: ByteArray): ByteArray {
+ require(counter in 0 until MAX_COUNTER && chunk.size <= CHUNK_SIZE)
+ return crypt(true, key, ByteArray(4) + counter.bigEndian(), label("codync/frame/v1") + counter.bigEndian(),
+ byteArrayOf(if (final) 0 else 1) + chunk)
+ }
+
+ internal fun openFrame(key: ByteArray, counter: Long, data: ByteArray): Pair<Boolean, ByteArray> {
+ require(counter in 0 until MAX_COUNTER && data.size in 17..(CHUNK_SIZE + 17)) { "Malformed encrypted frame" }
+ val plain = crypt(false, key, ByteArray(4) + counter.bigEndian(), label("codync/frame/v1") + counter.bigEndian(), data)
+ require(plain[0] == 0.toByte() || plain[0] == 1.toByte()) { "Invalid chunk flag" }
+ return (plain[0] == 0.toByte()) to plain.copyOfRange(1, plain.size)
+ }
+
+ internal fun openPush(sealed: String, computerId: String, pushPrivate: ByteArray): ByteArray {
+ val raw = sealed.decodeBase64Url()
+ require(raw.size > 48) { "Malformed sealed push" }
+ val cid = computerId.decodeBase64Url(16)
+ val ephemeral = raw.copyOf(32)
+ val secret = sharedSecret(pushPrivate, ephemeral)
+ val prk = extract(label("codync/push/v1") + cid + agreementPublic(pushPrivate) + ephemeral, secret)
+ return crypt(false, expand(prk, "codync/push-key/v1"), ByteArray(12), cid, raw.copyOfRange(32, raw.size))
+ }
+
+ internal fun sealMailbox(plain: ByteArray, computer: Computer, identity: DeviceIdentity, nonce: String,
+ ephemeral: ByteArray = randomBytes(32)): String {
+ require(plain.size <= 64 * 1024 - 112 && nonce.isNotEmpty()) { "Message is too large for the offline mailbox." }
+ val cid = computer.id.decodeBase64Url(16)
+ val public = agreementPublic(ephemeral)
+ val secret = sharedSecret(ephemeral, requireNotNull(computer.boxKey).decodeBase64Url(32))
+ val prk = extract(label("codync/mbox/v1") + cid + identity.deviceKey + public, secret)
+ val cipher = crypt(true, expand(prk, "codync/mbox-key/v1"), ByteArray(12), identity.deviceKey + label(nonce), plain)
+ val signature = identity.sign(label("codync/mbox/v1") + cid + public + cipher)
+ return (public + signature + cipher).base64Url()
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/RequestSigner.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/RequestSigner.kt
new file mode 100644
index 00000000..e9eba7d4
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/RequestSigner.kt
@@ -0,0 +1,15 @@
+package com.codync.android.core
+
+import okhttp3.HttpUrl
+
+internal object RequestSigner {
+ fun header(identity: DeviceIdentity, method: String, url: HttpUrl, body: ByteArray = byteArrayOf(),
+ timestamp: Long = System.currentTimeMillis(), nonce: ByteArray = RelayCrypto.randomBytes(16)): String {
+ val authority = url.toUri().rawAuthority.lowercase()
+ val path = url.encodedPath + (url.encodedQuery?.let { "?$it" } ?: "")
+ val canonical = listOf("codync-sig-v1", method.uppercase(), authority, path, timestamp.toString(),
+ nonce.base64Url(), RelayCrypto.sha256(body).base64Url()).joinToString("\n")
+ val signature = identity.sign(canonical.toByteArray()).base64Url()
+ return "v=1,kid=${identity.publicKey},ts=$timestamp,nonce=${nonce.base64Url()},sig=$signature"
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Routine.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Routine.kt
new file mode 100644
index 00000000..4acfaedd
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Routine.kt
@@ -0,0 +1,62 @@
+package com.codync.android.core
+
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.*
+
+/** Schedules execute on the host. Raw triggers retain fields the mobile editor does not edit. */
+@Serializable data class Routine(
+ val id: String, val botId: String, val name: String, val instruction: String,
+ val triggers: List<JsonObject>, val enabled: Boolean,
+ val createdAt: Long = 0, val updatedAt: Long = 0,
+ val triggerDescriptions: List<String> = emptyList(), val nextRunAt: Long? = null,
+ val timeoutSeconds: Int? = null, val lastError: String? = null,
+) {
+ val keepsOriginal: Boolean get() = triggers.size != 1 || triggers.single()["type"]?.jsonPrimitive?.content !in listOf("cron", "webhook")
+ val hasWebhook: Boolean get() = triggers.any { it["type"]?.jsonPrimitive?.content in listOf("webhook", "event") }
+}
+
+@Serializable data class RoutineRun(
+ val id: String, val routineId: String, val botId: String, val status: String,
+ val createdAt: Long = 0, val finishedAt: Long? = null, val detail: String? = null, val rootId: String? = null,
+) {
+ val isActive: Boolean get() = status in listOf("pending", "starting", "running", "recovering")
+ val label: String get() = when (status) {
+ "pending" -> "Queued"; "starting" -> "Starting"; "running" -> "Running"
+ "recovering" -> "Resuming after restart"; "failed" -> "Failed"; "interrupted" -> "Interrupted"
+ else -> status.replaceFirstChar { it.uppercase() }
+ }
+}
+
+@Serializable data class RoutineListing(val routines: List<Routine>, val runs: List<RoutineRun>) {
+ fun summary(routine: Routine): String {
+ runs.firstOrNull { it.routineId == routine.id && it.isActive }?.let { return it.label }
+ if (routine.lastError != null) return "Schedule needs attention"
+ runs.firstOrNull { it.routineId == routine.id }?.takeIf { it.status in listOf("failed", "interrupted") }
+ ?.let { return "Last run ${it.label.lowercase()}" }
+ return routine.triggerDescriptions.joinToString(" · ")
+ }
+}
+
+@Serializable data class RoutineScheduleDraft(
+ val kind: String = "cron", val amount: String = "1", val unit: Long = 3600,
+ val calendarStyle: String = "daily", val weekday: Int = 1, val selectedDays: List<Int> = emptyList(),
+ val monthDay: Int = 1, val minuteStep: Int = 15, val hour: Int = 9, val minute: Int = 0,
+ val at: Long = 0, val expression: String = "", val zone: String = "", val original: List<JsonObject> = emptyList(),
+) {
+ fun forMobileEditor(): RoutineScheduleDraft = copy(calendarStyle = "custom", kind = if (kind in listOf("cron", "webhook")) kind else "keep")
+}
+
+@Serializable data class RoutineSchedulePreview(
+ val draft: RoutineScheduleDraft, val triggers: List<JsonObject>, val summary: String,
+ val nextRunAt: Long? = null, val warning: String? = null,
+)
+
+@Serializable data class RoutineWebhook(val url: String? = null, val localUrl: String, val key: String, val connected: Boolean)
+
+data class RoutineDraft(val id: String? = null, val name: String = "", val instruction: String = "",
+ val schedule: RoutineScheduleDraft = RoutineScheduleDraft(), val timeoutSeconds: String = "3600") {
+ fun body(botId: String): JsonObject = buildJsonObject {
+ put("botId", botId); id?.let { put("id", it) }; put("name", name); put("instruction", instruction)
+ put("schedule", WireJson.encodeToJsonElement(schedule)); put("timeoutSeconds", timeoutSeconds)
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Usage.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Usage.kt
new file mode 100644
index 00000000..ab2d26f0
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Usage.kt
@@ -0,0 +1,56 @@
+package com.codync.android.core
+
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.decodeFromJsonElement
+import java.time.Instant
+import java.time.MonthDay
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+import java.util.Locale
+
+@Serializable data class UsageReport(val providers: List<UsageProvider> = emptyList()) {
+ companion object { fun decode(value: JsonElement): UsageReport = WireJson.decodeFromJsonElement(value) }
+}
+
+@Serializable data class UsageProvider(val id: String, val name: String, val windows: List<UsageWindow> = emptyList(),
+ val source: String = "", val updatedAt: Long? = null) {
+ val tightest: UsageWindow? get() = windows.filter { it.percent?.isFinite() == true }.maxByOrNull { requireNotNull(it.percent) }
+ val sourceLabel: String get() = when (source) {
+ "claude" -> "Claude Code"; "statusline" -> "Claude Code status line"
+ "agent" -> "A running bot"; "sessions" -> "Codex sessions"; "" -> "Unknown source"; else -> source
+ }
+}
+
+@Serializable data class UsageWindow(val id: String, val label: String, val percent: Double? = null,
+ val resetsAt: Long? = null, val resetsText: String? = null) {
+ val reportedPercent: Double? get() = percent?.takeIf { it.isFinite() }
+ val barFraction: Float? get() = reportedPercent?.coerceIn(0.0, 100.0)?.div(100)?.toFloat()
+
+ /** When the window resets: `resetsAt`, or Claude Code's text read as a date. */
+ fun resetDate(now: Long = System.currentTimeMillis()): Long? = resetsAt?.takeIf { it > 0 } ?: resetsText?.let { parseReset(it, now) }
+
+ companion object {
+ private val claudeReset = Regex("""^(?:(\w{3} \d{1,2}) at )?(\d{1,2})(?::(\d{2}))?(am|pm)(?: \(([^)]+)\))?$""")
+
+ /**
+ * Claude Code's text: "Sep 26 at 12pm (Asia/Taipei)", "Sep 25 at 7:30pm (Asia/Taipei)", or just
+ * "7:30pm (…)". The year isn't given: the next such date from `now` (CodyncKit `parseReset`).
+ */
+ fun parseReset(text: String, now: Long = System.currentTimeMillis()): Long? {
+ val match = claudeReset.matchEntire(text) ?: return null
+ val (day, hour12, minute, half, zoneId) = match.destructured
+ val zone = zoneId.takeIf(String::isNotEmpty)?.let { runCatching { ZoneId.of(it) }.getOrNull() } ?: ZoneId.systemDefault()
+ val today = Instant.ofEpochMilli(now).atZone(zone).toLocalDate()
+ val date = if (day.isEmpty()) today else runCatching {
+ MonthDay.parse(day, DateTimeFormatter.ofPattern("MMM d", Locale.US)).atYear(today.year)
+ }.getOrNull() ?: return null
+ val hour = (hour12.toIntOrNull() ?: return null) % 12 + if (half == "pm") 12 else 0
+ var at = date.atTime(hour, minute.toIntOrNull() ?: 0).atZone(zone)
+ // Past by more than a day: it means next year (or tomorrow, for a bare time).
+ val millis = at.toInstant().toEpochMilli()
+ if (millis < now - 86_400_000 || (day.isEmpty() && millis < now)) at = if (day.isEmpty()) at.plusDays(1) else at.plusYears(1)
+ return at.toInstant().toEpochMilli()
+ }
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/UsageDestination.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/UsageDestination.kt
new file mode 100644
index 00000000..2e06d8e0
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/UsageDestination.kt
@@ -0,0 +1,14 @@
+package com.codync.android.core
+
+import java.net.URI
+
+data class UsageDestination(val scope: String, val computerId: String) {
+ companion object {
+ fun parse(value: String, scheme: String): UsageDestination {
+ val uri = URI(value)
+ require(uri.scheme == scheme && uri.rawAuthority == "usage" && uri.fragment == null && uri.path.orEmpty() in setOf("", "/"))
+ val scoped = BotDestination.parse("$scheme://bot/usage?" + uri.rawQuery.orEmpty(), scheme)
+ return UsageDestination(scoped.scope, scoped.computerId)
+ }
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Voice.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Voice.kt
new file mode 100644
index 00000000..ca0db43d
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Voice.kt
@@ -0,0 +1,217 @@
+package com.codync.android.core
+
+import kotlinx.coroutines.*
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.*
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.jsonPrimitive
+import java.io.IOException
+
+class VoiceUnavailable(message: String) : IOException(message)
+fun callDuration(seconds: Long): String {
+ require(seconds >= 0)
+ return (seconds / 60).toString().padStart(2, '0') + ":" + (seconds % 60).toString().padStart(2, '0')
+}
+
+/** Match the existing iOS spoken reply transformation, without sending audio to the host. */
+object SpokenText {
+ private val rules = listOf(
+ "```[\\s\\S]*?```" to "",
+ "!?\\[([^\\]]*)\\]\\([^)]*\\)" to "$1",
+ "`([^`]*)`" to "$1",
+ "(?m)^\\s{0,3}(#{1,6}|>|[-*+]|\\d+\\.)\\s+" to "",
+ "(\\*\\*|\\*|~~)(\\S[^\\n]*?)\\1" to "$2",
+ "(?m)^[ \\t]*\\|?[ \\t:|-]{3,}\\|?[ \\t]*$" to "",
+ "(?m)^[ \\t]*\\|[ \\t]*|[ \\t]*\\|[ \\t]*$" to "",
+ "[ \\t]*\\|[ \\t]*" to ", ", "\\n{2,}" to "\n",
+ ).map { (pattern, replacement) -> Regex(pattern) to replacement }
+ fun from(markdown: String): String {
+ require(markdown.length <= 256 * 1024) { "This reply is too long to read aloud." }
+ var text = markdown
+ for ((pattern, replacement) in rules) text = pattern.replace(text, replacement)
+ return text.trim()
+ }
+ /** Android TTS limits each utterance; split without cutting a UTF-16 surrogate pair. */
+ fun chunks(text: String, limit: Int = 3_500): List<String> {
+ require(limit >= 2)
+ val result = mutableListOf<String>(); var offset = 0
+ while (offset < text.length) {
+ var end = minOf(offset + limit, text.length)
+ if (end < text.length && text[end - 1].isHighSurrogate() && text[end].isLowSurrogate()) end--
+ result.add(text.substring(offset, end)); offset = end
+ }
+ return result
+ }
+}
+
+/** Only newly finalized main-chat replies are spoken. The mirror remains the history owner. */
+class VoiceReplyGate(private val botId: String, private val startRev: Long, initial: List<Entry>) {
+ private var previous = initial.associateBy(Entry::id)
+ fun observe(entries: List<Entry>): List<String> {
+ val result = mutableListOf<String>()
+ for (entry in entries) {
+ if (entry.botId != botId || entry.threadId != null || entry.rev <= startRev) continue
+ val before = previous[entry.id]
+ if (entry.kind == "agent" && entry.data["final"]?.jsonPrimitive?.booleanOrNull == true &&
+ before?.data?.get("final")?.jsonPrimitive?.booleanOrNull != true && entry.text.isNotBlank()) result.add(entry.text)
+ if (entry.kind == "permission" && entry.status == "pending" && before?.status != "pending")
+ result.add("Your bot needs approval. Open the conversation to allow or deny the request.")
+ }
+ previous = entries.associateBy(Entry::id)
+ return result
+ }
+}
+
+enum class VoicePhase { Starting, Listening, Speaking, Interrupted, Failed, Ended }
+data class VoiceSettings(val pauseMillis: Long = 1_500, val rate: Float = 1f) {
+ init { require(pauseMillis in listOf(1_000L, 1_500L, 2_500L)); require(rate in .5f..2f) }
+}
+data class VoiceState(val phase: VoicePhase = VoicePhase.Starting, val muted: Boolean = false,
+ val heard: String = "", val said: String = "", val level: Float = 0f, val engine: String = "",
+ val settings: VoiceSettings = VoiceSettings(), val error: String? = null)
+sealed interface VoiceInput {
+ data class Text(val generation: Long, val value: String, val final: Boolean) : VoiceInput
+ data class Level(val generation: Long, val value: Float) : VoiceInput
+ data class Failed(val generation: Long, val message: String) : VoiceInput
+}
+interface VoiceAudio {
+ suspend fun initialize(): String
+ suspend fun listen(generation: Long, events: (VoiceInput) -> Unit)
+ suspend fun stopListening()
+ suspend fun speak(id: Long, text: String, rate: Float, completed: (Long, String?) -> Unit)
+ suspend fun stopSpeaking()
+ suspend fun close()
+}
+
+/** Serial audio ownership: no late recognizer/TTS callback can submit or restart a retired call. */
+class VoiceSession(parent: CoroutineScope, private val audio: VoiceAudio, settings: VoiceSettings,
+ private val send: (String) -> Unit) {
+ private sealed interface Event {
+ data class Input(val value: VoiceInput) : Event
+ data class Submit(val generation: Long, val revision: Long) : Event
+ data class Reply(val value: String) : Event
+ data class Done(val id: Long, val error: String?) : Event
+ data class Mute(val value: Boolean) : Event
+ data class Settings(val value: VoiceSettings) : Event
+ data class Focus(val active: Boolean) : Event
+ data object Interrupt : Event
+ }
+ private val job = SupervisorJob(parent.coroutineContext[Job])
+ private val scope = CoroutineScope(parent.coroutineContext + job)
+ private val commands = Channel<Event>(64)
+ private val mutableState = MutableStateFlow(VoiceState(settings = settings))
+ val state = mutableState.asStateFlow()
+ private var generation = 0L; private var revision = 0L; private var utterance = 0L
+ private var silence: Job? = null
+ private val replies = ArrayDeque<String>()
+ init { scope.launch {
+ try {
+ val engine = audio.initialize()
+ mutableState.update { it.copy(engine = engine) }
+ listen()
+ for (event in commands) {
+ try { receive(event) }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (_: Exception) { fail("Couldn't use voice audio. End the call and check the microphone and installed voices.") }
+ }
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (error: Exception) { fail(if (error is VoiceUnavailable) error.message.orEmpty()
+ else "Couldn't start voice audio. Check the microphone and installed voices.") }
+ finally {
+ commands.close(); silence?.cancel(); replies.clear()
+ try { withContext(NonCancellable) { audio.close() } }
+ catch (_: Exception) { mutableState.update { it.copy(error = it.error ?: "Voice audio couldn't finish closing. Start a new call when Android releases the microphone.") } }
+ finally {
+ mutableState.update { it.copy(phase = VoicePhase.Ended, heard = "", said = "", level = 0f) }
+ job.cancel()
+ }
+ }
+ } }
+ private fun post(event: Event): Boolean = job.isActive && commands.trySend(event).isSuccess
+ fun speak(markdown: String): Boolean = post(Event.Reply(markdown))
+ fun mute(value: Boolean) { post(Event.Mute(value)) }
+ fun settings(value: VoiceSettings) { post(Event.Settings(value)) }
+ fun focus(active: Boolean) { post(Event.Focus(active)) }
+ fun interrupt() { post(Event.Interrupt) }
+ fun end() { job.cancel() }
+ suspend fun awaitEnd() { job.join() }
+
+ private suspend fun stopListening() {
+ generation++; revision++; silence?.cancel(); silence = null
+ audio.stopListening()
+ mutableState.update { it.copy(level = 0f) }
+ }
+ private suspend fun listen() {
+ mutableState.update { it.copy(phase = VoicePhase.Listening, heard = "", level = 0f) }
+ if (state.value.muted) return
+ generation++
+ audio.listen(generation) { post(Event.Input(it)) }
+ }
+ private suspend fun speakNext() {
+ val next = replies.removeFirstOrNull()
+ if (next == null) { listen(); return }
+ utterance++
+ mutableState.update { it.copy(phase = VoicePhase.Speaking, said = next, heard = "") }
+ audio.speak(utterance, next, state.value.settings.rate) { id, error -> post(Event.Done(id, error)) }
+ }
+ private suspend fun submit() {
+ val text = state.value.heard.trim()
+ stopListening()
+ if (text.isNotEmpty()) send(text)
+ listen() // Bot work never stops listening to the next utterance.
+ }
+ private suspend fun fail(message: String) {
+ stopListening(); utterance++; replies.clear(); audio.stopSpeaking()
+ mutableState.update { it.copy(phase = VoicePhase.Failed, error = message) }
+ }
+ private suspend fun receive(event: Event) {
+ if (state.value.phase == VoicePhase.Failed) return
+ when (event) {
+ is Event.Input -> when (val input = event.value) {
+ is VoiceInput.Text -> if (input.generation == generation && state.value.phase == VoicePhase.Listening && !state.value.muted) {
+ require(input.value.length <= 16 * 1024)
+ if (input.value != state.value.heard) {
+ mutableState.update { it.copy(heard = input.value) }; revision++; silence?.cancel()
+ val owner = generation; val version = revision
+ if (input.value.isNotBlank()) silence = scope.launch {
+ delay(state.value.settings.pauseMillis); post(Event.Submit(owner, version))
+ }
+ }
+ if (input.final) submit()
+ }
+ is VoiceInput.Level -> if (input.generation == generation && state.value.phase == VoicePhase.Listening && !state.value.muted)
+ mutableState.update { it.copy(level = if (input.value.isFinite()) input.value.coerceIn(0f, 1f) else 0f) }
+ is VoiceInput.Failed -> if (input.generation == generation) fail(input.message)
+ }
+ is Event.Submit -> if (event.generation == generation && event.revision == revision && state.value.phase == VoicePhase.Listening && !state.value.muted) submit()
+ is Event.Reply -> {
+ if (event.value.length > 256 * 1024) {
+ mutableState.update { it.copy(error = "This reply is too long to read aloud. Read it in chat.") }; return
+ }
+ val text = SpokenText.from(event.value)
+ if (text.isNotBlank()) {
+ if (replies.size >= 8) { mutableState.update { it.copy(error = "More replies are waiting in chat than voice can read. Open the conversation.") }; return }
+ replies.addLast(text)
+ if (state.value.phase == VoicePhase.Listening) { stopListening(); speakNext() }
+ }
+ }
+ is Event.Done -> if (event.id == utterance && state.value.phase == VoicePhase.Speaking) {
+ if (event.error != null) fail(event.error) else speakNext()
+ }
+ is Event.Mute -> {
+ mutableState.update { it.copy(muted = event.value) }
+ if (state.value.phase == VoicePhase.Listening) { stopListening(); listen() }
+ }
+ is Event.Settings -> mutableState.update { it.copy(settings = event.value) }
+ is Event.Focus -> if (!event.active) {
+ stopListening(); utterance++; replies.clear(); audio.stopSpeaking()
+ mutableState.update { it.copy(phase = VoicePhase.Interrupted, heard = "", said = "") }
+ } else if (state.value.phase == VoicePhase.Interrupted) {
+ if (replies.isEmpty()) listen() else speakNext()
+ }
+ Event.Interrupt -> if (state.value.phase == VoicePhase.Speaking) {
+ utterance++; replies.clear(); audio.stopSpeaking(); listen()
+ }
+ }
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt
new file mode 100644
index 00000000..de779cf6
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt
@@ -0,0 +1,25 @@
+package com.codync.android.core
+
+import kotlinx.serialization.Serializable
+
+/** Private summaries only: widget storage never contains chat text or credentials. */
+@Serializable data class WidgetBot(val id: String, val name: String, val status: String,
+ val unread: Int = 0, val avatarColor: String = "blue", val avatarShape: String = "blob")
+
+@Serializable data class WidgetFeed(val scope: String = "local", val computerId: String? = null,
+ val computerName: String = "", val bots: List<WidgetBot> = emptyList(), val botsAt: Long = 0,
+ val usage: UsageReport = UsageReport(), val usageAt: Long = 0)
+
+enum class WidgetKind { Provider, Bots, Team }
+
+/** The Team widget's four spots: the picked bots first (a deleted pick falls back), then the feed's order (who needs you). */
+fun teamSlots(bots: List<WidgetBot>, picks: List<String?>): List<WidgetBot?> {
+ val picked = List(4) { i -> picks.getOrNull(i)?.let { id -> bots.firstOrNull { it.id == id } } }
+ val queue = ArrayDeque(bots.filter { bot -> picked.none { it?.id == bot.id } })
+ return picked.map { it ?: queue.removeFirstOrNull() }
+}
+
+fun widgetBots(bots: List<Bot>): List<WidgetBot> = bots.filter { !it.hidden && !it.deleted }
+ .sortedWith(compareBy<Bot> { when (it.status) { "needsInput" -> 0; "working" -> 1; "error" -> 2; else -> 3 } }
+ .thenByDescending { it.pinned }.thenByDescending { it.lastAt }.thenBy { it.name })
+ .take(256).map { WidgetBot(it.id, it.name.take(256), it.status, it.unread, it.avatarColor, it.avatarShape) }
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/AgentSettingsTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/AgentSettingsTest.kt
new file mode 100644
index 00000000..5054db9c
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/AgentSettingsTest.kt
@@ -0,0 +1,31 @@
+package com.codync.android.core
+
+import org.junit.Assert.*
+import kotlinx.serialization.json.*
+import org.junit.Test
+
+class AgentSettingsTest {
+ @Test fun `agent default folds into one choice while an unknown saved model survives`() {
+ val catalog = WireJson.decodeFromString<AgentModels>("""{"models":[{"id":"default-id","name":"Default (recommended)","description":"Agent choice"},{"id":"on-host","name":"Host model"}],"currentModelId":"on-host","future":true}""")
+ val choices = catalog.options("removed-model")
+ assertEquals(listOf(null, "on-host", "removed-model"), choices.map { it.id })
+ assertEquals("Default (recommended)", choices.first().name)
+ assertNull(catalog.normalize("default-id"))
+ assertEquals("removed-model", catalog.normalize("removed-model"))
+ assertEquals("Default · Host model", catalog.copy(models = catalog.models.drop(1)).options(null).first().name)
+ assertEquals(listOf(ModelChoice(null, "Default")), AgentModels(emptyList()).options(null))
+ }
+
+ @Test fun `new bot defaults preserve host connectors and a nullable notification toggle turns off`() {
+ val draft = BotDraft(command = "stale custom command")
+ assertTrue(draft.isValid)
+ assertEquals(JsonNull, draft.body()["connectors"])
+ assertEquals(JsonNull, draft.body()["command"])
+ // An unset switch is left out: the host's booleans don't take null.
+ assertFalse("fastMode" in draft.body() || "notify" in draft.body())
+ assertFalse(draft.toggleNotifications().notify!!)
+ assertTrue(draft.toggleNotifications().toggleNotifications().notify!!)
+ assertFalse(draft.copy(id = "existing", name = " ").isValid)
+ assertEquals("private-agent", draft.copy(backend = "custom", command = "private-agent").body()["command"]?.jsonPrimitive?.content)
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/AgentSetupTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/AgentSetupTest.kt
new file mode 100644
index 00000000..3baabf55
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/AgentSetupTest.kt
@@ -0,0 +1,108 @@
+package com.codync.android.core
+
+import java.io.IOException
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.coroutines.test.*
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Test
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class AgentSetupTest {
+ private class Sink : TerminalSink {
+ var text = ""; var resets = 0; var enabled = false
+ override suspend fun write(bytes: ByteArray) { text += bytes.toString(Charsets.UTF_8) }
+ override fun reset() { resets++; text = "" }
+ override fun input(enabled: Boolean) { this.enabled = enabled }
+ }
+ private open class Transport : SetupTerminalTransport {
+ val start = CompletableDeferred<String>()
+ val closed = mutableListOf<String>()
+ val inputs = mutableListOf<String>()
+ val sizes = mutableListOf<Pair<Int, Int>>()
+ override suspend fun setup(cols: Int, rows: Int) = start.await()
+ override fun output(term: String) = flow<TerminalEvent> { awaitCancellation() }
+ override suspend fun input(term: String, bytes: ByteArray) { inputs.add(bytes.toString(Charsets.UTF_8)) }
+ override suspend fun resize(term: String, cols: Int, rows: Int) { sizes.add(cols to rows) }
+ override suspend fun close(term: String) { closed.add(term) }
+ }
+ @Test fun backBeforeTheSetupReplyClosesTheLateTerminalExactlyOnce() = runTest {
+ val transport = Transport()
+ val session = SetupTerminalSession(backgroundScope, transport)
+ runCurrent(); session.close()
+ assertTrue(transport.closed.isEmpty())
+ transport.start.complete("late-session"); runCurrent()
+ assertEquals(listOf("late-session"), transport.closed)
+ session.closeAndJoin()
+ assertEquals(listOf("late-session"), transport.closed)
+ }
+ @Test fun terminalInputIsOrderedAndAFullQueueStopsFurtherInput() = runTest {
+ val gate = CompletableDeferred<Unit>()
+ val transport = object : Transport() {
+ override suspend fun input(term: String, bytes: ByteArray) { super.input(term, bytes); gate.await() }
+ }
+ val session = SetupTerminalSession(backgroundScope, transport)
+ val sink = Sink(); session.attach(sink)
+ transport.start.complete("session"); runCurrent()
+ session.type("first".toByteArray()); runCurrent()
+ session.type("second".toByteArray()); runCurrent()
+ assertEquals(listOf("first"), transport.inputs)
+ gate.complete(Unit); runCurrent()
+ assertEquals(listOf("first", "second"), transport.inputs)
+ session.resized(90, 30); runCurrent()
+ assertEquals(listOf(90 to 30), transport.sizes)
+ // Saturation occurs before the sender can run; never silently lose a keystroke and continue.
+ repeat(66) { session.type("x".toByteArray()) }
+ assertTrue(requireNotNull(session.state.value.error).contains("queue"))
+ assertFalse(sink.enabled)
+ runCurrent()
+ assertEquals(listOf("first", "second"), transport.inputs)
+ session.closeAndJoin()
+ }
+ @Test fun reconnectResetsScrollbackAndReplaysTheExistingTerminal() = runTest {
+ var subscriptions = 0
+ val transport = object : Transport() {
+ override fun output(term: String) = flow {
+ subscriptions++
+ emit(TerminalEvent.Output("head".toByteArray()))
+ if (subscriptions == 1) { emit(TerminalEvent.Output("live".toByteArray())); throw IOException("Drop") }
+ emit(TerminalEvent.Exit(0))
+ }
+ }
+ val session = SetupTerminalSession(backgroundScope, transport)
+ val sink = Sink(); session.attach(sink); transport.start.complete("session"); runCurrent()
+ assertEquals("headlive", sink.text)
+ advanceTimeBy(1_000); runCurrent()
+ assertEquals("head", sink.text); assertEquals(2, sink.resets)
+ assertEquals(0, session.state.value.exitCode); assertFalse(sink.enabled)
+ session.type("after exit".toByteArray()); runCurrent(); assertTrue(transport.inputs.isEmpty())
+ val replacement = Sink(); session.detach(sink); session.attach(replacement); runCurrent()
+ assertEquals("head", replacement.text)
+ assertEquals(3, subscriptions)
+ session.closeAndJoin(); assertEquals(listOf("session"), transport.closed)
+ }
+ @Test fun anUnconfirmedInputIsNeverAutomaticallyRetried() = runTest {
+ val transport = object : Transport() {
+ override suspend fun input(term: String, bytes: ByteArray) { super.input(term, bytes); throw IOException("Reply lost") }
+ }
+ val session = SetupTerminalSession(backgroundScope, transport)
+ val sink = Sink(); session.attach(sink); transport.start.complete("session"); runCurrent()
+ session.type("maybe sent".toByteArray()); runCurrent()
+ session.type("later".toByteArray()); advanceTimeBy(5_000); runCurrent()
+ assertEquals(listOf("maybe sent"), transport.inputs)
+ assertFalse(sink.enabled); assertTrue(requireNotNull(session.state.value.error).contains("wasn't confirmed"))
+ session.closeAndJoin()
+ }
+ @Test fun authKeysRespectSavedNamesAndUnknownMethodsRemainAvailableForAnUpgrade() {
+ val auth = WireJson.decodeFromString<AgentAuth>("""{"signedIn":false,"methods":[{"id":"keys","name":"API key","kind":"envVar","vars":[{"name":"KEY","label":"Key","secret":true,"optional":false}]},{"id":"future","name":"New method","kind":"newKind"}],"savedEnv":["KEY"]}""")
+ val method = auth.methods.first()
+ assertTrue(method.complete(emptyMap(), auth.savedEnv))
+ assertFalse(method.complete(emptyMap(), emptyList()))
+ assertTrue(method.complete(mapOf("KEY" to "fixture-value"), emptyList()))
+ assertEquals("newKind", auth.methods.last().kind)
+ val output = TerminalEvent.decode(buildJsonObject { put("type", "output"); put("data", "aGk=") })
+ assertArrayEquals("hi".toByteArray(), (output as TerminalEvent.Output).bytes)
+ try { TerminalEvent.decode(buildJsonObject { put("type", "output"); put("data", "!") }); fail("Reject malformed bytes") } catch (_: IllegalArgumentException) {}
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/BotDestinationTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/BotDestinationTest.kt
new file mode 100644
index 00000000..64838de4
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/BotDestinationTest.kt
@@ -0,0 +1,22 @@
+package com.codync.android.core
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class BotDestinationTest {
+ private val base = "codync://bot/a-b?scope=local&computer=9ESVKkTXlLyIExxnW7-PIg"
+ @Test fun `links retain all three destination boundaries`() {
+ assertEquals(BotDestination("local", "9ESVKkTXlLyIExxnW7-PIg", "a-b"), BotDestination.parse(base, "codync"))
+ assertEquals("a b", BotDestination.parse(base.replace("/a-b?", "/a%20b?"), "codync").botId)
+ val scope = "a".repeat(64)
+ assertEquals(scope, BotDestination.parse(base.replace("scope=local", "scope=$scope"), "codync").scope)
+ }
+ @Test fun `missing duplicate and ambiguous destinations fail instead of choosing another account`() {
+ for (url in listOf(base.replace("scope=local&", ""), base + "&scope=local", base + "&computer=bad",
+ base.replace("computer=9ESVKkTXlLyIExxnW7-PIg", "computer=bad"), base.replace("/a-b?", "/a%2Fb?"),
+ base.replace("/a-b?", "/?"), base + "#fragment", base.replace("://bot/", "://other@bot/"),
+ base.replace("scope=local", "scope=other"))) {
+ assertFails<IllegalArgumentException> { BotDestination.parse(url, "codync") }
+ }
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/BotExchangeTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/BotExchangeTest.kt
new file mode 100644
index 00000000..c35d1632
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/BotExchangeTest.kt
@@ -0,0 +1,32 @@
+package com.codync.android.core
+
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Test
+
+class BotExchangeTest {
+ private fun notice(id: String, seq: Long, chat: String, source: String, target: String, status: String? = null, reply: String? = null, rev: Long = 1) =
+ Entry(id, seq, chat, rev = rev, kind = "notice", createdAt = seq * 1000, data = buildJsonObject {
+ put("botMessage", buildJsonObject { put("sourceBotId", source); put("targetBotId", target); put("text", "ask $id"); reply?.let { put("reply", it) } })
+ status?.let { put("status", it) }
+ })
+
+ @Test fun `structured notices become exchanges and plain notices stay plain`() {
+ val x = BotExchange.of(notice("a", 1, "miles", "miles", "dex", "completed", "done"))!!
+ assertTrue(x.isOutgoing); assertEquals("dex", x.peerId); assertEquals("Messaged", x.verb); assertEquals(BotExchange.Outcome.Done, x.outcome)
+ assertEquals("Message from", BotExchange.of(notice("b", 2, "dex", "miles", "dex"))!!.verb)
+ assertNull(BotExchange.of(Entry("c", 3, "miles", rev = 1, kind = "notice", data = buildJsonObject { put("text", "Routine ran") })))
+ }
+
+ @Test fun `the conversation merges fetched and live copies and keeps one peer`() {
+ val old = notice("a", 1, "miles", "miles", "dex", rev = 1)
+ val newer = notice("a", 1, "miles", "miles", "dex", "completed", "ok", rev = 2)
+ val other = notice("b", 2, "miles", "miles", "ana")
+ val conversation = BotExchange.conversation(listOf(old, other), listOf(newer), "dex")
+ assertEquals(1, conversation.size); assertEquals(BotExchange.Outcome.Done, conversation.single().outcome)
+ val rows = BotConversationRow.build(conversation)
+ assertEquals(listOf("sep-a", "a-request", "a-reply"), rows.map { it.id })
+ val pending = BotConversationRow.build(BotExchange.conversation(listOf(old), emptyList(), "dex"))
+ assertTrue(pending.last() is BotConversationRow.Status)
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/BotSnapshotTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/BotSnapshotTest.kt
new file mode 100644
index 00000000..6c08ac0d
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/BotSnapshotTest.kt
@@ -0,0 +1,44 @@
+package com.codync.android.core
+
+import java.io.IOException
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Test
+
+class BotSnapshotTest {
+ private fun header(rev: Long) = buildJsonObject { put("type", "hello"); put("rev", rev) }
+ private fun bot(id: String, rev: Long, deleted: Boolean = false) = buildJsonObject {
+ put("type", "bot"); put("rev", rev)
+ put("bot", buildJsonObject { put("id", id); put("name", id); put("rev", rev); put("deleted", deleted) })
+ }
+
+ @Test fun `a roster waits for catch-up and cancels its subscription at the advertised head`() = runBlocking {
+ var cancelled = false
+ val stream = flow {
+ try {
+ emit(header(8)); emit(bot("first", 2)); emit(bot("removed", 3)); emit(bot("removed", 4, true))
+ emit(buildJsonObject { put("type", "usage"); put("rev", 8) })
+ emit(bot("last", 7))
+ emit(buildJsonObject { put("type", "entry"); put("rev", 8) })
+ fail("The finite snapshot must close its subscription before later live events")
+ } finally { cancelled = true }
+ }
+ val bots = botSnapshot(stream)
+ assertEquals(listOf("first", "last"), bots.map { it.id })
+ assertTrue(cancelled)
+ }
+
+ @Test fun `a new empty host finishes without waiting for another event`() = runBlocking {
+ assertTrue(botSnapshot(flowOf(header(0))).isEmpty())
+ }
+
+ @Test fun `an incomplete or resyncing snapshot is an error rather than an empty roster`() {
+ assertThrows(IllegalStateException::class.java) { runBlocking { botSnapshot(flowOf(header(8), bot("partial", 2))) } }
+ assertThrows(IOException::class.java) { runBlocking {
+ botSnapshot(flowOf(header(8), buildJsonObject { put("type", "resync") }))
+ } }
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt
new file mode 100644
index 00000000..08843c9e
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt
@@ -0,0 +1,205 @@
+package com.codync.android.core
+
+import java.util.concurrent.CopyOnWriteArrayList
+import java.util.concurrent.atomic.AtomicReference
+import java.io.IOException
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.flow.take
+import kotlinx.coroutines.flow.toList
+import kotlinx.coroutines.flow.onEach
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.long
+import kotlinx.serialization.json.put
+import okhttp3.Response
+import okhttp3.WebSocket
+import okhttp3.WebSocketListener
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ChannelIntegrationTest {
+ private val server = MockWebServer()
+ private val sockets = CopyOnWriteArrayList<WebSocket>()
+ private val hostSeed = ByteArray(32) { 1 }
+ private val hostKey = RelayCrypto.signingPublic(hostSeed)
+ private val cid = RelayCrypto.computerId(hostKey)
+ private val pairBody = AtomicReference<JsonObject>()
+ private val cancelled = AtomicReference<Long>()
+
+ private fun computer(): Computer = Computer(cid, "Computer", hostKey.base64Url(), urls = listOf(server.url("/").toString()))
+ private fun identity(): DeviceIdentity = DeviceIdentity(ByteArray(32) { 3 }, ByteArray(32) { 12 })
+
+ private fun enqueueHost(forgeSignature: Boolean = false, holdCalls: Boolean = false, burst: Int = 0, welcomeDelay: Long = 0,
+ snapshotHead: Int = 5) {
+ server.enqueue(MockResponse().withWebSocketUpgrade(object : WebSocketListener() {
+ private lateinit var opener: FrameOpener
+ private lateinit var sealer: FrameSealer
+ override fun onOpen(webSocket: WebSocket, response: Response) { sockets.add(webSocket) }
+ override fun onMessage(webSocket: WebSocket, text: String) {
+ val wire = Json.parseToJsonElement(text).jsonObject
+ if (wire.text("t") == "hello") {
+ if (welcomeDelay > 0) Thread.sleep(welcomeDelay)
+ val dk = requireNotNull(wire.text("dk")).decodeBase64Url(32)
+ val ek = requireNotNull(wire.text("ek")).decodeBase64Url(32)
+ val nonce = requireNotNull(wire.text("n")).decodeBase64Url(32)
+ assertTrue(RelayCrypto.verify(dk, RelayCrypto.hs1Input(cid.decodeBase64Url(16), dk, ek, nonce),
+ requireNotNull(wire.text("sig")).decodeBase64Url(64)))
+ val hostEphemeral = ByteArray(32) { 5 }
+ val ekH = RelayCrypto.agreementPublic(hostEphemeral)
+ val transcript = RelayCrypto.transcriptHash(cid.decodeBase64Url(16), dk, ek, nonce, ekH)
+ val keys = RelayCrypto.channelKeys(RelayCrypto.sharedSecret(hostEphemeral, ek), transcript)
+ opener = FrameOpener(keys.d2h, RelayCrypto.MAX_OUTBOUND)
+ sealer = FrameSealer(keys.h2d)
+ val signature = RelayCrypto.sign(hostSeed, transcript)
+ if (forgeSignature) signature[0] = (signature[0].toInt() xor 1).toByte()
+ webSocket.send(buildJsonObject { put("t", "welcome"); put("ek", ekH.base64Url()); put("sig", signature.base64Url()) }.toString())
+ return
+ }
+ if (wire.text("t") != "f") return
+ val inner = opener.open(Frame(wire.getValue("c").jsonPrimitive.long, requireNotNull(wire.text("d")).decodeBase64Url())) ?: return
+ val request = Json.parseToJsonElement(inner.toString(Charsets.UTF_8)).jsonObject
+ val id = request.getValue("id").jsonPrimitive.long
+ if (request["cancel"]?.jsonPrimitive?.booleanOrNull == true) {
+ cancelled.set(id)
+ return
+ }
+ if (holdCalls) return
+ if (request.text("sub") == "events") {
+ assertEquals("android", request.getValue("b").jsonObject.text("client"))
+ if (burst > 0) {
+ repeat(burst) { index -> send(webSocket, buildJsonObject {
+ put("id", id); put("ev", buildJsonObject { put("type", "future"); put("index", index) })
+ }) }
+ return
+ }
+ send(webSocket, buildJsonObject { put("id", id); put("ev", buildJsonObject { put("type", "hello"); put("rev", snapshotHead) }) })
+ send(webSocket, buildJsonObject { put("id", id); put("ev", buildJsonObject {
+ put("type", "bot"); put("rev", 4); put("bot", buildJsonObject { put("id", "bot-1"); put("name", "Reviewer"); put("rev", 4) })
+ }) })
+ } else if (request.text("m") == "pair") {
+ pairBody.set(request.getValue("b").jsonObject)
+ send(webSocket, buildJsonObject { put("id", id); put("ok", buildJsonObject { put("computerId", cid); put("name", "Paired computer") }) })
+ webSocket.close(4100, "paired")
+ } else {
+ send(webSocket, buildJsonObject { put("id", id); put("ok", buildJsonObject { put("computerId", cid); put("signKey", hostKey.base64Url()) }) })
+ }
+ }
+ private fun send(socket: WebSocket, inner: JsonObject) {
+ sealer.seal(inner.toString().toByteArray()).forEach { frame ->
+ socket.send(buildJsonObject { put("t", "f"); put("c", frame.counter); put("d", frame.data.base64Url()) }.toString())
+ }
+ }
+ }))
+ }
+
+ @After fun shutdown() {
+ sockets.forEach { it.close(1000, null) }
+ server.shutdown()
+ }
+
+ @Test fun `initial roster uses the current event protocol and releases the subscription`() = runBlocking {
+ enqueueHost(snapshotHead = 4)
+ val channel = HostConnector.connect(computer(), identity())
+ try {
+ val bots = HostClient.bots(channel)
+ assertEquals(listOf("Reviewer"), bots.map { it.name })
+ withTimeout(2_000) { while (cancelled.get() == null) delay(10) }
+ } finally { channel.close() }
+ }
+
+ @Test fun `pairing sends the Android platform and returns the pinned computer`() = runBlocking {
+ enqueueHost()
+ val pinned = computer()
+ val result = withTimeout(5_000) { HostConnector.pair(Pairing(pinned, ByteArray(16) { 8 }.base64Url()), identity(), "Android phone") }
+ assertEquals(cid, result.id)
+ assertEquals("Paired computer", result.name)
+ assertEquals("android", pairBody.get().text("platform"))
+ }
+
+ @Test fun `encrypted RPC and event subscriptions preserve host payloads`() = runBlocking {
+ enqueueHost()
+ val connected = withTimeout(5_000) { HostConnector.connect(computer(), identity()) }
+ try {
+ val hello = connected.call("hello")
+ assertEquals(cid, hello.jsonObject.text("computerId"))
+ val events = withTimeout(5_000) { connected.events().take(2).toList() }
+ assertEquals("hello", events.first().text("type"))
+ assertEquals("Reviewer", HostClient.decodeBot(events.last())?.name)
+ } finally { connected.close() }
+ }
+
+ @Test fun `a forged welcome never permits an encrypted request`() = runBlocking {
+ enqueueHost(forgeSignature = true)
+ var rejected = false
+ try { withTimeout(5_000) { HostConnector.connect(computer(), identity()) } }
+ catch (_: SecurityException) { rejected = true }
+ assertTrue(rejected)
+ }
+
+ @Test fun `an uncertain call timeout cancels its response without replaying the mutation`() = runBlocking {
+ enqueueHost(holdCalls = true)
+ val connected = withTimeout(5_000) { HostConnector.connect(computer(), identity()) }
+ try {
+ var timedOut = false
+ try { connected.call("runRoutine", timeoutMillis = 100) }
+ catch (_: IOException) { timedOut = true }
+ assertTrue(timedOut)
+ assertTrue(currentCoroutineContext().isActive)
+ assertTrue(connected.state.value is LinkState.Ready)
+ withTimeout(5_000) { while (cancelled.get() == null) kotlinx.coroutines.delay(10) }
+ assertEquals(1L, cancelled.get())
+ } finally { connected.close() }
+ }
+
+ @Test fun `deleted bots use the actual host tombstone format`() {
+ val tombstone = Json.parseToJsonElement("""{"type":"bot","rev":6,"bot":{"id":"bot-1","deleted":true,"rev":6}}""").jsonObject
+ val bot = requireNotNull(HostClient.decodeBot(tombstone))
+ assertTrue(bot.deleted)
+ assertEquals(6L, bot.rev)
+ assertFails<IllegalArgumentException> {
+ HostClient.decodeBot(Json.parseToJsonElement("""{"type":"bot","bot":{"id":"broken"}}""").jsonObject)
+ }
+ }
+
+ @Test fun `cancelling the owner still cancels an in-flight request`() = runBlocking {
+ enqueueHost(holdCalls = true)
+ val connected = HostConnector.connect(computer(), identity())
+ try {
+ var cancelledByOwner = false
+ try { withTimeout(100) { connected.call("hello", timeoutMillis = 5_000) } }
+ catch (_: kotlinx.coroutines.TimeoutCancellationException) { cancelledByOwner = true }
+ assertTrue(cancelledByOwner)
+ withTimeout(5_000) { while (cancelled.get() == null) delay(10) }
+ assertEquals(1L, cancelled.get())
+ } finally { connected.close() }
+ }
+
+ @Test fun `a slow consumer receives catch-up larger than both bounded queues without a disconnect`() = runBlocking {
+ enqueueHost(burst = 600)
+ val connected = HostConnector.connect(computer(), identity())
+ try {
+ val events = withTimeout(8_000) { connected.events().onEach { delay(2) }.take(600).toList() }
+ assertEquals((0 until 600).map(Int::toLong), events.map { it.getValue("index").jsonPrimitive.long })
+ assertEquals(cid, connected.call("hello").jsonObject.text("computerId"))
+ } finally { connected.close() }
+ }
+
+ @Test fun `direct-only waits for a cold handshake beyond the relay fallback budget`() = runBlocking {
+ enqueueHost(welcomeDelay = 1800)
+ val connected = withTimeout(5_000) { HostConnector.connect(computer().copy(route = ConnectionRoute.DirectOnly), identity()) }
+ try { assertEquals(cid, connected.call("hello").jsonObject.text("computerId")) }
+ finally { connected.close() }
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
new file mode 100644
index 00000000..85004dfc
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt
@@ -0,0 +1,91 @@
+package com.codync.android.core
+
+import java.util.concurrent.TimeUnit
+import kotlinx.coroutines.*
+import kotlinx.serialization.json.*
+import okhttp3.OkHttpClient
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import org.junit.Assert.*
+import org.junit.Test
+
+class CloudClientTest {
+ private val identity = DeviceIdentity(ByteArray(32) { 3 }, ByteArray(32) { 12 })
+ private val hostKey = RelayCrypto.signingPublic(ByteArray(32) { 7 })
+ private val id = RelayCrypto.computerId(hostKey)
+
+ @Test fun `account access commits before revealing then pins the compared host key`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ val expiresAt = System.currentTimeMillis() + 60_000
+ val hostNonce = ByteArray(32) { 5 }
+ server.enqueue(MockResponse().setBody("""{"requestId":"r","expiresAt":$expiresAt}"""))
+ server.enqueue(MockResponse().setBody("""{"requestId":"r","computerId":"$id","status":"pending"}"""))
+ server.enqueue(MockResponse().setBody("""{"requestId":"r","computerId":"$id","status":"pending","hostNonce":"${hostNonce.base64Url()}"}"""))
+ server.enqueue(MockResponse().setBody("{}"))
+ val client = CloudClient(server.url("/").toString(), identity, { "session" }, OkHttpClient(), 1, Unit)
+ val ticket = client.requestAccess(id, hostKey.base64Url())
+ assertEquals(hostKey.base64Url(), ticket.signKey)
+ val commitRequest = server.takeRequest()
+ assertEquals("/v1/computers/$id/access-requests", commitRequest.path)
+ assertEquals("Bearer session", commitRequest.getHeader("Authorization"))
+ assertTrue(requireNotNull(commitRequest.getHeader("Codync-Sig")).contains("kid=${identity.publicKey}"))
+ val commit = Json.parseToJsonElement(commitRequest.body.readUtf8()).jsonObject
+ assertEquals(setOf("commit"), commit.keys)
+ repeat(2) { assertEquals("/v1/access-requests/r", server.takeRequest().path) }
+ val revealRequest = server.takeRequest()
+ assertEquals("/v1/access-requests/r/reveal", revealRequest.path)
+ val nonce = Json.parseToJsonElement(revealRequest.body.readUtf8()).jsonObject.getValue("nonce").jsonPrimitive.content.decodeBase64Url(32)
+ assertEquals(commit.text("commit"), RelayCrypto.sasCommit(identity.deviceKey, nonce).base64Url())
+ assertEquals(RelayCrypto.sasCode(hostKey, identity.deviceKey, nonce, hostNonce), ticket.code)
+ assertNotEquals(commitRequest.getHeader("Codync-Sig"), revealRequest.getHeader("Codync-Sig"))
+ } finally { server.shutdown() }
+ }
+
+ @Test fun `account registration proves the Android device key and revocation is never retried`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ server.enqueue(MockResponse().setResponseCode(403).setBody("""{"error":{"code":"deviceRevoked"}}"""))
+ val client = CloudClient(server.url("/").toString(), identity, { "session" }, OkHttpClient(), 1, Unit)
+ val error = try { client.registerDevice("Samsung"); error("Expected revocation") } catch (error: CloudError) { error }
+ assertEquals(403, error.status)
+ assertFalse(error.isTransient)
+ val request = server.takeRequest()
+ assertEquals("/v1/devices", request.path)
+ assertEquals("""{"name":"Samsung","platform":"android"}""", request.body.readUtf8())
+ assertNotNull(request.getHeader("Codync-Sig"))
+ assertEquals(1, server.requestCount)
+ } finally { server.shutdown() }
+ }
+
+ @Test fun `mismatched host identity cannot start an access request`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ val client = CloudClient(server.url("/").toString(), identity, { "session" }, OkHttpClient(), 1, Unit)
+ try { client.requestAccess("bad", hostKey.base64Url()); error("Expected identity rejection") }
+ catch (_: IllegalArgumentException) { }
+ assertEquals(0, server.requestCount)
+ assertEquals("expired", AccessStatus("r", "futureStatus").state)
+ } finally { server.shutdown() }
+ }
+
+ @Test fun `cancelling a nonce exchange cancels the HTTP call and withdraws the request`() = runBlocking {
+ val server = MockWebServer()
+ server.start()
+ try {
+ server.enqueue(MockResponse().setBody("""{"requestId":"r","expiresAt":${System.currentTimeMillis() + 60_000}}"""))
+ server.enqueue(MockResponse().setBody("""{"requestId":"r","status":"pending"}"""))
+ server.enqueue(MockResponse().setBody("{}"))
+ val client = CloudClient(server.url("/").toString(), identity, { "session" }, OkHttpClient(), 60_000, Unit)
+ val request = launch { client.requestAccess(id, hostKey.base64Url()) }
+ withContext(Dispatchers.IO) { server.takeRequest(5, TimeUnit.SECONDS); server.takeRequest(5, TimeUnit.SECONDS) }
+ request.cancelAndJoin()
+ val withdrawal = server.takeRequest(5, TimeUnit.SECONDS)
+ assertEquals("DELETE", withdrawal?.method)
+ assertEquals("/v1/access-requests/r", withdrawal?.path)
+ } finally { server.shutdown() }
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/CompatibilityTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/CompatibilityTest.kt
new file mode 100644
index 00000000..dd97dcb2
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/CompatibilityTest.kt
@@ -0,0 +1,15 @@
+package com.codync.android.core
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class CompatibilityTest {
+ @Test fun `each side names the oldest version of the other`() {
+ assertNull(VersionMismatch.check("2.17.5-dev", null, "9.0.0"))
+ assertEquals(VersionMismatch.UpdateApp("2.18.0"), VersionMismatch.check("2.17.5-dev", "2.18.0", "2.18.0"))
+ assertEquals(VersionMismatch.UpdateHost("2.11.9", "2.12.0"), VersionMismatch.check("2.17.5", "2.11.9", "2.3.0"))
+ assertNull(VersionMismatch.check("2.17.5", "2.17.5", "2.3.0"))
+ assertTrue(AppVersion.isBelow("2.9.3", "2.14.1"))
+ assertFalse(AppVersion.isBelow("garbled", "2.14.1"))
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ConnectionsTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ConnectionsTest.kt
new file mode 100644
index 00000000..e5015936
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ConnectionsTest.kt
@@ -0,0 +1,119 @@
+package com.codync.android.core
+
+import java.io.IOException
+import kotlinx.coroutines.*
+import kotlinx.coroutines.flow.*
+import kotlinx.coroutines.test.*
+import org.junit.Assert.*
+import org.junit.Test
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class ConnectionsTest {
+ private open class Transport : AppConnectionTransport {
+ val foreground = MutableStateFlow(true)
+ var starts = 0; var polls = 0; var submissions = 0
+ var plan = ComposioConnect("redirect", "https://example.com/sign-in", "connection")
+ var answer = ComposioConnectionState("connection", "active")
+ override suspend fun awaitActive() { foreground.first { it } }
+ override suspend fun start(): ComposioConnect { starts++; return plan }
+ override suspend fun state(id: String): ComposioConnectionState { polls++; return answer }
+ override suspend fun submit(mode: String, fields: Map<String, String>): ComposioConnectionState { submissions++; return answer }
+ }
+ private fun rejected(block: () -> Unit) {
+ try { block(); fail("Unsupported input must be rejected") } catch (_: IllegalArgumentException) {} catch (_: IllegalStateException) {}
+ }
+ @Test fun authenticationMetadataRejectsUnsafeLinksAndUnsupportedFields() {
+ rejected { ComposioConnect("redirect", "https://user:[email protected]", "connection").checked() }
+ rejected { ComposioConnect("redirect", "javascript:alert(1)", "connection").checked() }
+ rejected { ComposioConnect("redirect", "https://example.com", null).checked() }
+ rejected { ComposioConnect("future").checked() }
+ val field = ComposioField("key", "API key", secret = true, required = true)
+ rejected { ComposioConnect("needsFields", mode = "KEY", fields = listOf(field, field)).checked() }
+ val plan = ComposioConnect("needsFields", mode = "KEY", fields = listOf(field, ComposioField("optional", "Optional")))
+ assertFalse(plan.complete(emptyMap()))
+ assertEquals(mapOf("key" to " fixture secret "), plan.submitted(mapOf("key" to " fixture secret ", "optional" to "")))
+ rejected { plan.submitted(mapOf("key" to "fixture", "unknown" to "value")) }
+ }
+ @Test fun replacementCredentialsPreserveBlankFieldsAndExactWhitespace() {
+ val connector = InstalledConnector("fixture", "Fixture", kind = "local", keys = listOf("KEY", "OTHER"))
+ assertEquals(mapOf("KEY" to " fixture value "), credentialReplacements(connector, mapOf("KEY" to " fixture value ", "OTHER" to "")))
+ rejected { credentialReplacements(connector, mapOf("unknown" to "fixture")) }
+ rejected { credentialReplacements(connector, mapOf("KEY" to "é".repeat(33_000))) }
+ assertTrue(ConnectionRequest("connection", "pending", "Fixture", "bot", connectorId = "fixture").canConnect)
+ assertFalse(ConnectionRequest("future", "pending", "Fixture", "bot").canConnect)
+ assertTrue(ConnectionRequest("agent", "pending", "Claude", "bot", backend = "claude").canConnect)
+ assertFalse(ConnectionRequest("agent", "pending", "Claude", "bot").canConnect)
+ assertFalse(ConnectionRequest("login", "future", "Fixture", "bot").canConnect)
+ }
+ @Test fun browserSignInPausesReadsInBackgroundAndReusesItsOriginalConnection() = runTest {
+ val transport = Transport()
+ val session = AppConnectionSession(backgroundScope, transport)
+ runCurrent(); assertEquals(1, transport.starts)
+ transport.foreground.value = false
+ advanceTimeBy(10_000); runCurrent(); assertEquals(0, transport.polls)
+ transport.foreground.value = true
+ runCurrent(); assertTrue(session.state.value.connected)
+ assertEquals(1, transport.polls); assertEquals(1, transport.starts)
+ session.close(); advanceTimeBy(10_000); runCurrent(); assertEquals(1, transport.polls)
+ }
+ @Test fun unknownStatusesNeverLookConnectedAndRecoverableReadErrorsCanRecover() = runTest {
+ val transport = object : Transport() {
+ override suspend fun state(id: String): ComposioConnectionState {
+ polls++
+ if (polls == 1) throw IOException("Temporary read error")
+ return ComposioConnectionState(id, if (polls == 2) "future-status" else "active")
+ }
+ }
+ val session = AppConnectionSession(backgroundScope, transport)
+ runCurrent(); advanceTimeBy(4_000); runCurrent()
+ assertFalse(session.state.value.connected); assertEquals("future-status", session.state.value.status)
+ advanceTimeBy(2_000); runCurrent(); assertTrue(session.state.value.connected)
+ assertEquals(1, transport.starts); session.close()
+ }
+ @Test fun anotherConnectionCannotCompleteThisSignInAndPollingHasADeadline() = runTest {
+ val wrong = Transport().apply { answer = ComposioConnectionState("other", "active") }
+ val session = AppConnectionSession(backgroundScope, wrong)
+ runCurrent(); advanceTimeBy(2_000); runCurrent()
+ assertFalse(session.state.value.connected); assertNotNull(session.state.value.error); session.close()
+ val pending = Transport().apply { answer = ComposioConnectionState("connection", "initiated") }
+ val waiting = AppConnectionSession(backgroundScope, pending)
+ runCurrent(); advanceTimeBy(600_000); runCurrent()
+ assertFalse(waiting.state.value.connected); assertTrue(requireNotNull(waiting.state.value.error).contains("Timed out"))
+ assertTrue(pending.polls <= 300); waiting.close()
+ }
+ @Test fun anUnconfirmedKeySubmissionIsNeverAutomaticallyRetried() = runTest {
+ val transport = object : Transport() {
+ override suspend fun submit(mode: String, fields: Map<String, String>): ComposioConnectionState {
+ submissions++; throw IOException("Uncertain delivery")
+ }
+ }.apply { plan = ComposioConnect("needsFields", mode = "KEY", fields = listOf(ComposioField("key", "Key", required = true))) }
+ val session = AppConnectionSession(backgroundScope, transport)
+ runCurrent(); session.submit(mapOf("key" to "fixture")); runCurrent()
+ advanceTimeBy(20_000); runCurrent()
+ assertEquals(1, transport.submissions); assertEquals(0, transport.polls)
+ assertFalse(session.state.value.connected); assertNotNull(session.state.value.error); session.close()
+ }
+ @Test fun retiringAnAccountCancelsAnInFlightBrowserRead() = runTest {
+ val pending = CompletableDeferred<ComposioConnectionState>()
+ var cancelled = false
+ val transport = object : Transport() {
+ override suspend fun state(id: String): ComposioConnectionState {
+ try { return pending.await() } finally { cancelled = true }
+ }
+ }
+ val parent = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler))
+ val session = AppConnectionSession(parent, transport)
+ runCurrent(); advanceTimeBy(2_000); runCurrent(); parent.cancel(); runCurrent()
+ pending.complete(ComposioConnectionState("connection", "active")); runCurrent()
+ assertTrue(cancelled); assertFalse(session.state.value.connected)
+ }
+ @Test fun restoringAnExistingConnectionNeverStartsAnotherSignIn() = runTest {
+ val transport = Transport()
+ val session = AppConnectionSession(backgroundScope, transport, "connection")
+ runCurrent(); assertEquals(0, transport.starts)
+ advanceTimeBy(2_000); runCurrent()
+ assertTrue(session.state.value.connected)
+ assertEquals("connection", session.state.value.connectionId)
+ assertEquals(1, transport.polls); assertEquals(0, transport.starts); session.close()
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ConnectorOAuthTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ConnectorOAuthTest.kt
new file mode 100644
index 00000000..54c05826
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ConnectorOAuthTest.kt
@@ -0,0 +1,31 @@
+package com.codync.android.core
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class ConnectorOAuthTest {
+ @Test fun aPendingStateHashAcceptsItsCallbackOnlyOnTheOriginalComputerWithinItsDeadline() {
+ val plan = ConnectorSignIn("https://provider.example/authorize?state=fixture-state", "app")
+ val pending = PendingConnectorOAuth.create(plan, "connector", "computer", 1000)
+ assertFalse(pending.toString().contains("fixture-state"))
+ val back = OAuthReturn.parse("codync://oauth?state=fixture-state&code=fixture-code", "codync")
+ pending.validate(back, "computer", 2000)
+ for ((callback, computer, now) in listOf(Triple(back.copy(state = "other"), "computer", 2000L),
+ Triple(back, "other-computer", 2000L), Triple(back, "computer", pending.expiresAt))) {
+ try { pending.validate(callback, computer, now); fail("Wrong or expired callback must be rejected") }
+ catch (_: IllegalArgumentException) { }
+ }
+ }
+ @Test fun callbackParsingRejectsRepeatedFieldsMixedResultsAndOtherDestinations() {
+ val cancelled = OAuthReturn.parse("codync://oauth?state=fixture&error=access_denied&error_description=User+cancelled", "codync")
+ assertEquals("User cancelled", cancelled.error)
+ assertNull(cancelled.code)
+ for (value in listOf("codync://bot/id?state=s&code=c", "codync://oauth/path?state=s&code=c",
+ "codync://oauth?state=s&state=x&code=c", "codync://oauth?state=s&code=c&code=x", "codync://oauth?state=s&code=c&error=bad",
+ "codync://oauth?state=s&code=c#fragment", "codync://oauth?code=c")) {
+ try { OAuthReturn.parse(value, "codync"); fail("Malformed return must be rejected") } catch (_: IllegalArgumentException) { }
+ }
+ try { PendingConnectorOAuth.create(ConnectorSignIn("http://provider.example?state=s", "app"), "c", "host", 1000); fail() }
+ catch (_: IllegalArgumentException) { }
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt
new file mode 100644
index 00000000..f359d99f
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ConversationTest.kt
@@ -0,0 +1,42 @@
+package com.codync.android.core
+
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Test
+
+class ConversationTest {
+ private fun entry(kind: String, final: Boolean = false) = Entry("e", 1, "b", rev = 1, kind = kind,
+ data = buildJsonObject { put("text", "message"); put("final", final) })
+
+ @Test fun `chat shows final replies permissions notices and users without narration`() {
+ assertTrue(entry("user").isChat)
+ assertTrue(entry("permission").isChat)
+ assertTrue(entry("notice").isChat)
+ assertTrue(entry("agent", true).isChat)
+ for (kind in listOf("agent", "thought", "tool", "plan")) assertFalse(entry(kind).isChat)
+ }
+
+ @Test fun `malformed known events fail before a checkpoint while unknown events are ignored`() {
+ assertFails<IllegalArgumentException> { MirrorEvent.decode(buildJsonObject { put("type", "entry"); put("entry", buildJsonObject { put("id", "broken") }) }) }
+ assertEquals(MirrorEvent.Ignored, MirrorEvent.decode(buildJsonObject { put("type", "future"); put("rev", 999) }))
+ }
+
+ @Test fun `templates preserve portable settings and exclude identity and runtime flags`() {
+ val bot = Bot("identity", "Reviewer", description = "Review carefully", model = "chosen", connectors = listOf("c"),
+ skills = listOf("s"), pinned = true, hidden = true, managedWorkspace = true, cwd = "/host/workspace", rev = 77)
+ val template = WireJson.parseToJsonElement(BotDraft.from(bot).template()).jsonObject
+ for (key in listOf("id", "pinned", "hidden", "rev", "status", "autoName", "createdAt")) assertFalse(key in template)
+ assertEquals("", template.getValue("cwd").jsonPrimitive.content)
+ assertEquals("chosen", template.getValue("model").jsonPrimitive.content)
+ assertEquals(listOf(JsonPrimitive("c")), template.getValue("connectors").jsonArray.toList())
+ assertEquals(JsonNull, BotDraft.from(bot).copy(model = null).body()["model"])
+ }
+
+ @Test fun `malformed rendered fields cannot enter the mirror`() {
+ for (data in listOf("{\"text\":{}}", "{\"final\":[]}", "{\"options\":[{}]}",
+ "{\"reactions\":[{}]}", "{\"thread\":{\"count\":-1}}", "{\"attachments\":[{\"id\":\"id\",\"name\":\"file\",\"size\":-1}]}")) {
+ val value = WireJson.parseToJsonElement("""{"id":"e","botId":"b","seq":1,"rev":1,"kind":"user","data":$data}""").jsonObject
+ assertFails<IllegalArgumentException> { Entry.decode(value) }
+ }
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/HostFilesTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/HostFilesTest.kt
new file mode 100644
index 00000000..c76bbcc5
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/HostFilesTest.kt
@@ -0,0 +1,49 @@
+package com.codync.android.core
+
+import java.nio.file.Files
+import java.util.Base64
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Test
+
+class HostFilesTest {
+ @Test fun `uploads stream bounded ordered chunks including an empty file`() = runBlocking {
+ val root = Files.createTempDirectory("codync-files").toFile()
+ try {
+ for (size in listOf(0, HostFiles.CHUNK_BYTES + 13)) {
+ val source = root.resolve("source").apply { writeBytes(ByteArray(size) { (it % 255).toByte() }) }
+ var offset = 0L
+ var calls = 0
+ val files = HostFiles { method, body, timeout ->
+ assertEquals("upload", method); assertEquals(60_000, timeout)
+ assertEquals(offset, body.getValue("offset").jsonPrimitive.long)
+ val bytes = Base64.getDecoder().decode(body.getValue("data").jsonPrimitive.content)
+ assertTrue(bytes.size <= HostFiles.CHUNK_BYTES)
+ for (i in bytes.indices) assertEquals(((offset + i) % 255).toByte(), bytes[i])
+ offset += bytes.size; calls++
+ assertEquals(offset == size.toLong(), body.getValue("done").jsonPrimitive.boolean)
+ JsonObject(emptyMap())
+ }
+ files.upload("bot", "upload", OutgoingFile(source.path, "source", size.toLong()))
+ assertEquals(size.toLong(), offset)
+ assertEquals(if (size == 0) 1 else 2, calls)
+ }
+ } finally { root.deleteRecursively() }
+ }
+
+ @Test fun `truncated downloads cannot publish a partial cache file`() = runBlocking {
+ val root = Files.createTempDirectory("codync-files").toFile()
+ try {
+ var calls = 0
+ val files = HostFiles { _, _, _ ->
+ calls++
+ buildJsonObject { put("size", 4); put("data", if (calls == 1) "YWI=" else "") }
+ }
+ val destination = root.resolve("saved")
+ assertFails<IllegalArgumentException> { files.download("bot", Attachment("id", "file", 4), destination) }
+ assertFalse(destination.exists())
+ assertFalse(root.resolve("saved.partial").exists())
+ } finally { root.deleteRecursively() }
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/HostInteropTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/HostInteropTest.kt
new file mode 100644
index 00000000..932021e9
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/HostInteropTest.kt
@@ -0,0 +1,76 @@
+package com.codync.android.core
+
+import java.io.File
+import java.security.SecureRandom
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertArrayEquals
+import kotlinx.serialization.json.*
+import java.util.UUID
+import kotlinx.coroutines.delay
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+
+/** Opt-in live acceptance. Inputs and the cleanup public key stay in private temporary files. */
+class HostInteropTest {
+ @Test fun `pair hello and sync work against a real host on the requested route`() = runBlocking<Unit> {
+ val path = System.getenv("CODYNC_ANDROID_PAIRING_FILE")
+ assumeTrue("No live host pairing was requested", path != null)
+ // Real hosts emit their own environment's scheme (codync-dev:// from a development build).
+ val link = File(requireNotNull(path)).readText()
+ val parsed = Pairing.parse(link, link.trim().substringBefore("://"))
+ val relay = System.getenv("CODYNC_ANDROID_TEST_ROUTE") == "relay"
+ val pairing = if (relay) parsed.copy(computer = parsed.computer.copy(route = ConnectionRoute.CloudflareFirst, urls = emptyList())) else parsed
+ val random = SecureRandom()
+ val identity = DeviceIdentity(ByteArray(32).also(random::nextBytes), ByteArray(32).also(random::nextBytes))
+ val cleanup = System.getenv("CODYNC_ANDROID_CLEANUP_KEY_FILE")
+ requireNotNull(cleanup) { "Live acceptance requires a cleanup key file" }
+ File(cleanup).writeText(identity.publicKey)
+ val paired = withTimeout(30_000) { HostConnector.pair(pairing, identity, "Android protocol acceptance") }
+ val target = paired.copy(route = if (relay) ConnectionRoute.CloudflareFirst else ConnectionRoute.DirectOnly,
+ urls = if (relay) emptyList() else paired.urls)
+ val channel = withTimeout(30_000) { HostConnector.connect(target, identity) }
+ try {
+ assertEquals(if (relay) HostRoute.Relay else HostRoute.Direct, channel.route)
+ val hello = HostClient.hello(channel, target)
+ assertEquals(pairing.computer.id, hello.id)
+ HostClient.bots(channel)
+ System.getenv("CODYNC_ANDROID_FILE_TEST_BOT")?.let { bot ->
+ val root = kotlin.io.path.createTempDirectory("codync-live-files").toFile()
+ try {
+ val bytes = ByteArray(HostFiles.CHUNK_BYTES + 13) { (it % 255).toByte() }
+ val source = root.resolve("acceptance.bin").apply { writeBytes(bytes) }
+ val upload = UUID.randomUUID().toString()
+ HostFiles(channel).upload(bot, upload, OutgoingFile(source.path, source.name, source.length()))
+ val nonce = UUID.randomUUID().toString()
+ val body = buildJsonObject { put("botId", bot); put("text", ""); put("clientNonce", nonce); put("attachments", JsonArray(listOf(JsonPrimitive(upload)))) }
+ val result = channel.call("send", body)
+ val entry = Entry.decode(result.jsonObject.getValue("entry").jsonObject)
+ val attachment = WireJson.decodeFromJsonElement<Attachment>(entry.data.getValue("attachments").jsonArray.single())
+ assertEquals(source.length(), attachment.size)
+ val duplicate = channel.call("send", body)
+ assertEquals(entry.id, duplicate.jsonObject.getValue("entry").jsonObject.getValue("id").jsonPrimitive.content)
+ val saved = root.resolve("download")
+ HostFiles(channel).download(bot, attachment, saved)
+ assertArrayEquals(bytes, saved.readBytes())
+ withTimeout(20_000) {
+ var answered = false
+ while (true) {
+ val history = channel.call("history", buildJsonObject { put("botId", bot); put("limit", 100) })
+ val entries = history.jsonObject.getValue("entries").jsonArray.map { Entry.decode(it.jsonObject) }
+ val card = entries.firstOrNull { it.kind == "permission" && it.status == "pending" }
+ if (card != null && !answered) {
+ val option = card.data.getValue("options").jsonArray.first().jsonObject.getValue("optionId").jsonPrimitive.content
+ channel.call("respondPermission", buildJsonObject { put("entryId", card.id); put("optionId", option) })
+ answered = true
+ }
+ if (answered && entries.any { it.seq > entry.seq && it.kind == "agent" && it.isChat && it.text.startsWith("Done:") }) break
+ delay(100)
+ }
+ }
+ } finally { root.deleteRecursively() }
+ }
+ } finally { channel.close() }
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/MailboxTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/MailboxTest.kt
new file mode 100644
index 00000000..9de6848c
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/MailboxTest.kt
@@ -0,0 +1,59 @@
+package com.codync.android.core
+
+import java.io.IOException
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Test
+
+class MailboxTest {
+ private class Relay : ChannelSocket {
+ val incoming = Channel<String>(16)
+ val blobs = mutableListOf<String>()
+ var enqueueError: String? = null
+ init { incoming.trySend("""{"t":"presence","online":false}""") }
+ override suspend fun receive(): String = incoming.receive()
+ override suspend fun send(text: String) {
+ val message = WireJson.parseToJsonElement(text).jsonObject
+ val response = when (message.text("t")) {
+ "mbox.put" -> { blobs.add(message.getValue("d").jsonPrimitive.content)
+ buildJsonObject { put("t", if (enqueueError == null) "mbox.ok" else "mbox.err"); put("nonce", message.getValue("nonce")); enqueueError?.let { put("code", it) } } }
+ "mbox.list" -> buildJsonObject { put("t", "mbox.items"); put("items", JsonArray(emptyList())) }
+ "mbox.cancel" -> buildJsonObject { put("t", "mbox.gone"); put("nonce", message.getValue("nonce")); put("state", "delivering") }
+ else -> return
+ }
+ incoming.send(response.toString())
+ }
+ override fun close(code: Int) { incoming.close() }
+ }
+ private suspend fun connect(relay: Relay): EncryptedChannel {
+ val key = RelayCrypto.signingPublic(ByteArray(32) { 1 })
+ val computer = Computer(RelayCrypto.computerId(key), "Computer", key.base64Url(), RelayCrypto.agreementPublic(ByteArray(32) { 2 }).base64Url())
+ val channel = EncryptedChannel(relay, HostRoute.Relay, computer, DeviceIdentity(ByteArray(32) { 3 }, ByteArray(32) { 4 }), false)
+ return channel.start()
+ }
+ @Test fun `offline mailbox retries use fresh seals without claiming a cancellation succeeded`() = runBlocking {
+ val relay = Relay()
+ val channel = connect(relay)
+ try {
+ assertTrue(channel.state.value is LinkState.ComputerOffline)
+ val send = PendingSend("stable", "bot", text = "message", createdAt = 1)
+ withTimeout(3_000) { channel.enqueue(send); channel.enqueue(send) }
+ assertEquals(2, relay.blobs.size)
+ assertNotEquals(relay.blobs[0], relay.blobs[1])
+ val queued = channel.queued()
+ assertTrue(queued.getValue("items").jsonArray.isEmpty())
+ assertEquals("delivering", channel.cancelQueued(send.nonce))
+ } finally { channel.close() }
+ }
+ @Test fun `relay rejections remain explicit for host online races and limits`() = runBlocking {
+ val relay = Relay().apply { enqueueError = "hostOnline" }
+ val channel = connect(relay)
+ try {
+ try { channel.enqueue(PendingSend("stable", "bot", text = "message", createdAt = 1)); fail("Expected hostOnline") }
+ catch (failure: IOException) { assertEquals("hostOnline", failure.message) }
+ } finally { channel.close() }
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ManagementTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ManagementTest.kt
new file mode 100644
index 00000000..9372513b
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ManagementTest.kt
@@ -0,0 +1,43 @@
+package com.codync.android.core
+
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Test
+
+class ManagementTest {
+ @Test fun `group edits preserve agent settings and member order in existing host contracts`() {
+ val roster = listOf(Bot("a", "Ada"), Bot("b", "Grace"))
+ val draft = GroupDraft(members = listOf("b", "a", "b"), pinned = true)
+ val payload = draft.body(roster)
+ assertEquals("Grace, Ada", payload.getValue("name").jsonPrimitive.content)
+ assertEquals(listOf(JsonPrimitive("b"), JsonPrimitive("a")), payload.getValue("members").jsonArray.toList())
+ assertEquals("group", payload.getValue("kind").jsonPrimitive.content)
+ for (key in listOf("backend", "cwd", "connectors", "skills", "permission", "model", "notify", "hidden")) assertFalse(key in payload)
+ val existing = Bot("group", "Team", kind = "group", members = listOf("a"), pinned = true)
+ assertEquals("group", GroupDraft.from(existing).body(roster).getValue("id").jsonPrimitive.content)
+ }
+
+ @Test fun `unavailable members and nested groups cannot silently change a saved roster`() {
+ for (members in listOf(emptyList(), listOf("missing"), listOf("nested"), listOf("deleted"))) {
+ assertFails<IllegalArgumentException> { GroupDraft(members = members).body(listOf(
+ Bot("nested", "Team", kind = "group"), Bot("deleted", "Gone", deleted = true))) }
+ }
+ }
+
+ @Test fun `memory decodes profiles history and future kinds without discarding facts`() {
+ val memory = MemoryListing.decode(WireJson.parseToJsonElement("""{"facts":[
+ {"id":"profile","title":"Android","content":"Works on Android","createdAt":1,"kind":"profile","pinned":true},
+ {"id":"log","content":"Reviewed a release","createdAt":2,"kind":"future","extra":true}],"total":5,"nextOffset":2}"""))
+ assertEquals(2, memory.facts.size)
+ assertEquals("future", memory.facts.last().kind)
+ assertEquals(2, memory.nextOffset)
+ assertEquals(true, memory.facts.first().pinned)
+ assertFails<IllegalArgumentException> { MemoryListing.decode(WireJson.parseToJsonElement("""{"facts":[{"id":"","content":"fact","createdAt":0,"kind":"profile"}]}""")) }
+ }
+
+ @Test fun `memory history keeps its cursor`() {
+ val detail = WireJson.decodeFromJsonElement<MemoryDetail>(WireJson.parseToJsonElement("""{"fact":{"id":"a","content":"x"},
+ "history":{"result":"v2","history_cursor":3},"timeline":{"result":"t"}}"""))
+ assertEquals(3, detail.history.cursor)
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/MarkdownBlocksTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/MarkdownBlocksTest.kt
new file mode 100644
index 00000000..b7027281
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/MarkdownBlocksTest.kt
@@ -0,0 +1,20 @@
+package com.codync.android.core
+
+import com.codync.android.core.MarkdownBlocks.Block
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class MarkdownBlocksTest {
+ /** Tables, rules and nested lists, as agents write them (the iOS test's case). */
+ @Test fun `tables rules and nesting split like iOS`() {
+ val blocks = MarkdownBlocks.parse("| Name | Size |\n|---|:-:|\n| a | 1 |\n---\n- top\n - inner\n| not a table")
+ assertEquals(listOf(Block.Table(listOf("Name", "Size"), listOf(listOf("a", "1"))), Block.Rule,
+ Block.Bullet("top", "•", 0), Block.Bullet("inner", "◦", 1), Block.Paragraph("| not a table")), blocks)
+ }
+
+ @Test fun `headings quotes ordered items and fences`() {
+ val blocks = MarkdownBlocks.parse("## Plan\n1. read\n> note\n```kotlin\nval x = 1\n```\ntext\nmore")
+ assertEquals(listOf(Block.Heading("Plan", 2), Block.Bullet("read", "1.", 0), Block.Quote("note"),
+ Block.Code("val x = 1", "kotlin"), Block.Paragraph("text\nmore")), blocks)
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/MarketTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/MarketTest.kt
new file mode 100644
index 00000000..a02d5c50
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/MarketTest.kt
@@ -0,0 +1,26 @@
+package com.codync.android.core
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class MarketTest {
+ @Test fun catalogPagesDeduplicateAndRevealOnlyOnRequest() {
+ val page = CatalogPage<String>().append((1..25).map(Int::toString)) { it }
+ assertEquals(12, page.visible.size)
+ assertTrue(page.hasHidden)
+ val next = page.append(listOf("2", "26", "26")) { it }
+ assertEquals(26, next.items.size)
+ assertEquals(12, next.visible.size)
+ assertEquals(24, next.reveal().visible.size)
+ assertEquals(26, next.reveal().reveal().visible.size)
+ assertFalse(next.reveal().reveal().hasHidden)
+ }
+ @Test fun connectorInputsRetainHostDefaultsAndUnknownAuthorizationDoesNotClaimSignIn() {
+ val input = WireJson.decodeFromString<MarketInput>("""{"name":"REGION","required":true,"default":"provided-by-host","future":true}""")
+ val option = InstallOption("local", "npm", "On computer", listOf(input))
+ assertTrue(option.complete(emptyMap()))
+ assertFalse(option.complete(mapOf("REGION" to "")))
+ assertTrue(InstalledConnector("c", "Connector", kind = "remote", auth = "signedOut").needsSignIn)
+ assertFalse(InstalledConnector("c", "Connector", kind = "remote", auth = "future").needsSignIn)
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/PairingQrTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingQrTest.kt
new file mode 100644
index 00000000..26bf7b6e
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingQrTest.kt
@@ -0,0 +1,52 @@
+package com.codync.android.core
+
+import com.google.zxing.BarcodeFormat
+import com.google.zxing.EncodeHintType
+import com.google.zxing.qrcode.QRCodeWriter
+import java.net.URLEncoder
+import java.nio.ByteBuffer
+import org.junit.Assert.*
+import org.junit.Test
+
+class PairingQrTest {
+ private fun code(): String {
+ val keys = vectors().getValue("keys") as kotlinx.serialization.json.JsonObject
+ val fields = mapOf("v" to "3", "id" to requireNotNull(keys.text("computerId")), "name" to "Acceptance computer",
+ "sk" to requireNotNull(keys.text("hostSignPub")), "bk" to requireNotNull(keys.text("hostBoxPub")),
+ "code" to ByteArray(16) { 8 }.base64Url(), "urls" to "http://192.168.1.2:19222")
+ return "codync://pair?" + fields.entries.joinToString("&") { "${it.key}=${URLEncoder.encode(it.value, "UTF-8")}" }
+ }
+ private fun pixels(value: String, size: Int = 512): ByteArray {
+ val matrix = QRCodeWriter().encode(value, BarcodeFormat.QR_CODE, size, size, mapOf(EncodeHintType.CHARACTER_SET to "UTF-8"))
+ return ByteArray(size * size) { if (matrix[it % size, it / size]) 0 else 255.toByte() }
+ }
+
+ @Test fun `bundled QR decoding accepts every rotation mirrored and inverted pairing images`() {
+ val value = code(); val decoder = PairingQr("codync"); var image = pixels(value)
+ repeat(4) {
+ assertEquals(PairingScan.Found(value), decoder.decode(image, 512, 512))
+ image = ByteArray(image.size) { index -> image[(511 - index % 512) * 512 + index / 512] }
+ }
+ assertEquals(PairingScan.Found(value), decoder.decode(ByteArray(image.size) { image[it / 512 * 512 + 511 - it % 512] }, 512, 512))
+ assertEquals(PairingScan.Found(value), decoder.decode(ByteArray(image.size) { (255 - (image[it].toInt() and 255)).toByte() }, 512, 512))
+ }
+
+ @Test fun `unrelated obsolete and malformed QR codes never become a pairing request`() {
+ val decoder = PairingQr("codync")
+ assertNull(decoder.decode(pixels("https://example.test"), 512, 512))
+ for (value in listOf("codync://pair?v=2", code() + "&code=duplicate")) assertTrue(decoder.decode(pixels(value), 512, 512) is PairingScan.Invalid)
+ val obsolete = decoder.decode(pixels("codync://pair?v=2"), 512, 512) as PairingScan.Invalid
+ assertTrue(obsolete.message.contains("Update Codync"))
+ assertNull(decoder.decode(ByteArray(128 * 128) { 127 }, 128, 128))
+ }
+
+ @Test fun `padded strided image planes preserve pixels and the caller buffer position`() {
+ val raw = ByteArray(36) { 99 }; raw[5] = 1; raw[7] = 2; raw[9] = 3; raw[17] = 4; raw[19] = 5; raw[21] = 6
+ val buffer = ByteBuffer.wrap(raw).apply { position(5); limit(22) }
+ assertArrayEquals(byteArrayOf(1, 2, 3, 4, 5, 6), PairingQr.luminance(buffer, 3, 2, 12, 2))
+ assertEquals(5, buffer.position()); assertEquals(22, buffer.limit())
+ assertFails<IllegalArgumentException> { PairingQr.luminance(buffer, 4, 2, 12, 2) }
+ assertFails<IllegalArgumentException> { PairingQr.luminance(buffer, 3, 2, 2, 2) }
+ assertFails<IllegalArgumentException> { PairingQr.luminance(buffer, Int.MAX_VALUE, Int.MAX_VALUE, 12, 1) }
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt
new file mode 100644
index 00000000..91e06e26
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt
@@ -0,0 +1,56 @@
+package com.codync.android.core
+
+import java.net.URLEncoder
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class PairingTest {
+ private val fixture = vectors()
+ private val keys = fixture.getValue("keys").let { it as kotlinx.serialization.json.JsonObject }
+ private val params = linkedMapOf(
+ "v" to "3", "id" to requireNotNull(keys.text("computerId")), "name" to "Fixture computer",
+ "sk" to requireNotNull(keys.text("hostSignPub")), "bk" to requireNotNull(keys.text("hostBoxPub")),
+ "code" to ByteArray(16) { 8 }.base64Url(), "urls" to "http://192.168.1.2:19222,https://example.test:19222",
+ "cloud" to "https://cloud.example.test",
+ )
+ private fun link(fields: Map<String, String> = params): String = "codync://pair?" + fields.entries.joinToString("&") {
+ "${it.key}=${URLEncoder.encode(it.value, "UTF-8")}" }
+
+ @Test fun `a valid pairing preserves pins direct candidates relay and name`() {
+ val pairing = Pairing.parse(" ${link()} \n", "codync")
+ assertEquals(params["id"], pairing.computer.id)
+ assertEquals(params["name"], pairing.computer.name)
+ assertEquals(2, pairing.computer.urls.size)
+ assertEquals(params["cloud"], pairing.computer.cloud)
+ assertEquals(fixture.getValue("pairing").let { it as kotlinx.serialization.json.JsonObject }.text("offerId"), pairing.offerId)
+ }
+
+ @Test fun `Codync Dev and Codync only accept their own pairing links`() {
+ val dev = link().replace("codync://", "codync-dev://")
+ assertEquals(params["id"], Pairing.parse(dev, "codync-dev").computer.id)
+ assertFails<IllegalArgumentException> { Pairing.parse(dev, "codync") }
+ assertFails<IllegalArgumentException> { Pairing.parse(link(), "codync-dev") }
+ }
+
+ @Test fun `altered pins damaged keys obsolete links and duplicate fields are rejected`() {
+ for (fields in listOf(params + ("id" to "invalid"), params + ("sk" to "invalid"), params + ("bk" to "invalid"),
+ params + ("code" to "invalid"), params + ("v" to "2"), params + ("cloud" to "http://example.test"),
+ params + ("cloud" to "https://user:[email protected]"))) {
+ assertFails<IllegalArgumentException> { Pairing.parse(link(fields), "codync") }
+ }
+ assertFails<IllegalArgumentException> { Pairing.parse(link() + "&sk=" + params["sk"], "codync") }
+ assertFails<IllegalArgumentException> { Pairing.parse("https://example.test/?v=3", "codync") }
+ }
+
+ @Test fun `unsafe direct endpoints are removed and at least one route must remain`() {
+ val pairing = Pairing.parse(link(params + ("urls" to "javascript:alert(1),http://user:[email protected]")), "codync")
+ assertEquals(emptyList<String>(), pairing.computer.urls)
+ assertFails<IllegalArgumentException> { Pairing.parse(link(params + ("urls" to "ftp://host.test") - "cloud"), "codync") }
+ }
+
+ @Test fun `strict base64url refuses padding noncanonical bits and wrong lengths`() {
+ for (value in listOf("AA=", "AB", "A", "+A", "AA ")) assertFails<IllegalArgumentException> { value.decodeBase64Url() }
+ assertFails<IllegalArgumentException> { "AA".decodeBase64Url(32) }
+ }
+}
+
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/RelayVectorsTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/RelayVectorsTest.kt
new file mode 100644
index 00000000..85d44ace
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/RelayVectorsTest.kt
@@ -0,0 +1,159 @@
+package com.codync.android.core
+
+import java.io.File
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.boolean
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.long
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+internal fun vectors(): JsonObject = Json.parseToJsonElement(File(System.getProperty("codync.vectors")).readText()).jsonObject
+internal fun JsonObject.bytes(key: String): ByteArray = getValue(key).jsonPrimitive.content.decodeBase64Url()
+
+class RelayVectorsTest {
+ private val fixture = vectors()
+ private val keys = fixture.getValue("keys").jsonObject
+ private val hs = fixture.getValue("handshake").jsonObject
+
+ @Test fun `keys and identifiers match the shared vectors`() {
+ assertArrayEquals(keys.bytes("hostSignPub"), RelayCrypto.signingPublic(keys.bytes("hostSignSeed")))
+ assertArrayEquals(keys.bytes("deviceSignPub"), RelayCrypto.signingPublic(keys.bytes("deviceSignSeed")))
+ assertArrayEquals(keys.bytes("hostBoxPub"), RelayCrypto.agreementPublic(keys.bytes("hostBoxPriv")))
+ assertEquals(keys.text("computerId"), RelayCrypto.computerId(keys.bytes("hostSignPub")))
+ val pairing = fixture.getValue("pairing").jsonObject
+ assertEquals(pairing.text("offerId"), RelayCrypto.offerId(pairing.bytes("code")))
+ }
+
+ @Test fun `handshake signatures and both channel keys match upstream`() {
+ val cid = requireNotNull(keys.text("computerId")).decodeBase64Url(16)
+ val input = RelayCrypto.hs1Input(cid, keys.bytes("deviceSignPub"), hs.bytes("deviceEphPub"), hs.bytes("n"))
+ assertArrayEquals(hs.bytes("hs1SignInput"), input)
+ assertArrayEquals(hs.bytes("hs1Sig"), RelayCrypto.sign(keys.bytes("deviceSignSeed"), input))
+ val transcript = RelayCrypto.transcriptHash(cid, keys.bytes("deviceSignPub"), hs.bytes("deviceEphPub"), hs.bytes("n"), hs.bytes("hostEphPub"))
+ assertArrayEquals(hs.bytes("transcriptHash"), transcript)
+ assertArrayEquals(hs.bytes("hs2Sig"), RelayCrypto.sign(keys.bytes("hostSignSeed"), transcript))
+ assertTrue(RelayCrypto.verify(keys.bytes("hostSignPub"), transcript, hs.bytes("hs2Sig")))
+ val secret = RelayCrypto.sharedSecret(hs.bytes("deviceEphPriv"), hs.bytes("hostEphPub"))
+ assertArrayEquals(hs.bytes("sharedSecret"), secret)
+ val derived = RelayCrypto.channelKeys(secret, transcript)
+ assertArrayEquals(hs.bytes("prk"), derived.prk)
+ assertArrayEquals(hs.bytes("kD2H"), derived.d2h)
+ assertArrayEquals(hs.bytes("kH2D"), derived.h2d)
+ val identity = DeviceIdentity(keys.bytes("deviceSignSeed"), fixture.getValue("push").jsonObject.bytes("pushPriv"))
+ val computer = Computer(requireNotNull(keys.text("computerId")), "Fixture", requireNotNull(keys.text("hostSignPub")))
+ val handshake = Handshake(computer, identity, hs.bytes("deviceEphPriv"), hs.bytes("n"))
+ assertEquals(hs.text("hs1Sig"), handshake.hello(false).text("sig"))
+ val actual = handshake.finish(hs.bytes("hostEphPub"), hs.bytes("hs2Sig"))
+ assertArrayEquals(derived.h2d, actual.h2d)
+ }
+
+ @Test fun `every upstream encrypted frame is byte identical`() {
+ fixture.getValue("frames").jsonArray.forEach { element ->
+ val frame = element.jsonObject
+ val key = hs.bytes(if (frame.text("dir") == "d2h") "kD2H" else "kH2D")
+ val counter = frame.getValue("c").jsonPrimitive.long
+ val final = frame.getValue("final").jsonPrimitive.boolean
+ val message = requireNotNull(frame.text("message")).toByteArray()
+ val encrypted = RelayCrypto.sealFrame(key, counter, final, message)
+ assertArrayEquals(frame.bytes("d"), encrypted)
+ val opened = RelayCrypto.openFrame(key, counter, encrypted)
+ assertEquals(final, opened.first)
+ assertArrayEquals(message, opened.second)
+ }
+ }
+
+ @Test fun `signed HTTP requests match the canonical authority path and body bytes`() {
+ val request = fixture.getValue("requestSig").jsonObject
+ val identity = DeviceIdentity(keys.bytes("deviceSignSeed"), ByteArray(32) { 12 })
+ val url = ("https://" + request.text("authority") + request.text("pathAndQuery")).toHttpUrl()
+ val header = RequestSigner.header(identity, requireNotNull(request.text("method")), url,
+ timestamp = request.getValue("ts").jsonPrimitive.long, nonce = request.bytes("nonce"))
+ assertEquals(request.text("header"), "Codync-Sig: $header")
+ val changed = RequestSigner.header(identity, "GET", url, byteArrayOf(1), request.getValue("ts").jsonPrimitive.long, request.bytes("nonce"))
+ assertFalse(header == changed)
+ }
+
+ @Test fun `sealed notifications open with the existing push identity`() {
+ val push = fixture.getValue("push").jsonObject
+ val opened = RelayCrypto.openPush(requireNotNull(push.text("sealed")), requireNotNull(keys.text("computerId")), push.bytes("pushPriv"))
+ assertEquals(push.text("plaintext"), opened.toString(Charsets.UTF_8))
+ }
+
+ @Test fun `account commit and six digit code match upstream SAS vectors`() {
+ val sas = fixture.getValue("sas").jsonObject
+ assertArrayEquals(sas.bytes("commit"), RelayCrypto.sasCommit(keys.bytes("deviceSignPub"), sas.bytes("deviceNonce")))
+ assertEquals(sas.text("code"), RelayCrypto.sasCode(keys.bytes("hostSignPub"), keys.bytes("deviceSignPub"),
+ sas.bytes("deviceNonce"), sas.bytes("hostNonce")))
+ assertFails<IllegalArgumentException> { RelayCrypto.sasCode(ByteArray(31), ByteArray(32), ByteArray(32), ByteArray(32)) }
+ }
+
+ @Test fun `mailbox key derivation remains compatible with the shared vector`() {
+ val mailbox = fixture.getValue("mailbox").jsonObject
+ val secret = RelayCrypto.sharedSecret(mailbox.bytes("ephPriv"), keys.bytes("hostBoxPub"))
+ assertArrayEquals(mailbox.bytes("sharedSecret"), secret)
+ val cid = requireNotNull(keys.text("computerId")).decodeBase64Url(16)
+ val dk = keys.bytes("deviceSignPub")
+ val ephemeral = mailbox.bytes("ephPub")
+ val prk = RelayCrypto.extract(RelayCrypto.label("codync/mbox/v1") + cid + dk + ephemeral, secret)
+ val key = RelayCrypto.expand(prk, "codync/mbox-key/v1")
+ assertArrayEquals(mailbox.bytes("key"), key)
+ val plain = requireNotNull(mailbox.text("plaintext")).toByteArray()
+ val ct = RelayCrypto.crypt(true, key, ByteArray(12), dk + requireNotNull(mailbox.text("clientNonce")).toByteArray(), plain)
+ assertArrayEquals(mailbox.bytes("ciphertext"), ct)
+ assertArrayEquals(mailbox.bytes("sig"), RelayCrypto.sign(keys.bytes("deviceSignSeed"), RelayCrypto.label("codync/mbox/v1") + cid + ephemeral + ct))
+ val identity = DeviceIdentity(keys.bytes("deviceSignSeed"), ByteArray(32) { 12 })
+ val computer = Computer(requireNotNull(keys.text("computerId")), "Fixture", requireNotNull(keys.text("hostSignPub")),
+ boxKey = requireNotNull(keys.text("hostBoxPub")))
+ val sealed = RelayCrypto.sealMailbox(plain, computer, identity, requireNotNull(mailbox.text("clientNonce")), mailbox.bytes("ephPriv"))
+ assertEquals(mailbox.text("blob"), sealed)
+ assertFalse(RelayCrypto.sealMailbox(plain, computer, identity, "new-attempt") == RelayCrypto.sealMailbox(plain, computer, identity, "new-attempt"))
+ }
+
+ @Test fun `all zero agreement keys and forged host signatures are rejected`() {
+ assertFails<SecurityException> { RelayCrypto.sharedSecret(hs.bytes("deviceEphPriv"), ByteArray(32)) }
+ val signature = hs.bytes("hs2Sig").apply { this[0] = (this[0].toInt() xor 1).toByte() }
+ assertFalse(RelayCrypto.verify(keys.bytes("hostSignPub"), hs.bytes("transcriptHash"), signature))
+ }
+
+ @Test fun `reassembly preserves message boundaries and rejects replay`() {
+ val key = hs.bytes("kD2H")
+ val message = ByteArray(RelayCrypto.CHUNK_SIZE + 17) { (it % 251).toByte() }
+ val sealer = FrameSealer(key)
+ val opener = FrameOpener(key)
+ val frames = sealer.seal(message)
+ assertEquals(2, frames.size)
+ assertEquals(null, opener.open(frames[0]))
+ assertArrayEquals(message, opener.open(frames[1]))
+ val second = sealer.seal(byteArrayOf(3)).single()
+ assertArrayEquals(byteArrayOf(3), opener.open(second))
+ assertFails<IllegalArgumentException> { opener.open(second) }
+ }
+
+ @Test fun `bad tags oversize messages invalid flags and skipped counters are rejected`() {
+ val key = hs.bytes("kD2H")
+ val frame = FrameSealer(key).seal(byteArrayOf(1, 2, 3)).single()
+ assertFails<IllegalArgumentException> { FrameOpener(key).open(frame.copy(counter = 1)) }
+ val corrupt = frame.data.copyOf().apply { this[lastIndex] = (this[lastIndex].toInt() xor 1).toByte() }
+ assertFails<SecurityException> { FrameOpener(key).open(frame.copy(data = corrupt)) }
+ assertFails<IllegalArgumentException> { FrameOpener(key, limit = 2).open(frame) }
+ assertFails<IllegalArgumentException> { FrameSealer(key).seal(ByteArray(RelayCrypto.MAX_OUTBOUND + 1)) }
+ val malformed = RelayCrypto.crypt(true, key, ByteArray(12), RelayCrypto.label("codync/frame/v1") + 0L.bigEndian(), byteArrayOf(2))
+ assertFails<IllegalArgumentException> { RelayCrypto.openFrame(key, 0, malformed) }
+ }
+}
+
+internal inline fun <reified T : Throwable> assertFails(block: () -> Unit) {
+ try { block() } catch (error: Throwable) {
+ if (error is T) return
+ throw AssertionError("Expected ${T::class.simpleName}, got ${error::class.simpleName}", error)
+ }
+ throw AssertionError("Expected ${T::class.simpleName}")
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/RoutineTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/RoutineTest.kt
new file mode 100644
index 00000000..77335fe5
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/RoutineTest.kt
@@ -0,0 +1,35 @@
+package com.codync.android.core
+
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Test
+
+class RoutineTest {
+ @Test fun `editing unsupported schedules preserves every trigger field`() {
+ val original = WireJson.parseToJsonElement("""[{"type":"event","source":"github","event":"*","filters":{"repo":"org/project"},"future":true},{"type":"interval","seconds":5400}]""").jsonArray.map { it.jsonObject }
+ val schedule = RoutineScheduleDraft(kind = "interval", original = original).forMobileEditor()
+ val payload = RoutineDraft(name = "Updated name", instruction = "Keep my schedule", schedule = schedule).body("bot")
+ assertEquals("keep", payload.getValue("schedule").jsonObject.getValue("kind").jsonPrimitive.content)
+ assertEquals(JsonArray(original), payload.getValue("schedule").jsonObject.getValue("original"))
+ assertFalse("enabled" in payload)
+ assertFalse("id" in payload)
+ assertEquals(JsonPrimitive("3600"), payload.getValue("timeoutSeconds"))
+ }
+
+ @Test fun `mobile cron fields preserve the exact host expression and zone`() {
+ val draft = RoutineScheduleDraft(calendarStyle = "days", expression = "5 23 * * 1,3,6", zone = "Asia/Taipei")
+ assertEquals("custom", draft.forMobileEditor().calendarStyle)
+ assertEquals(draft.expression, draft.forMobileEditor().expression)
+ assertEquals(draft.zone, draft.forMobileEditor().zone)
+ }
+
+ @Test fun `routine status reflects active recovery and failed runs before the schedule`() {
+ val routine = Routine("r", "b", "Morning", "Report", emptyList(), true, triggerDescriptions = listOf("Every day"))
+ val failed = RoutineRun("old", "r", "b", "failed")
+ val active = RoutineRun("now", "r", "b", "recovering")
+ assertEquals("Resuming after restart", RoutineListing(listOf(routine), listOf(failed, active)).summary(routine))
+ assertEquals("Last run failed", RoutineListing(listOf(routine), listOf(failed)).summary(routine))
+ assertEquals("Schedule needs attention", RoutineListing(emptyList(), emptyList()).summary(routine.copy(lastError = "invalid schedule")))
+ assertEquals("Every day", RoutineListing(emptyList(), emptyList()).summary(routine))
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/UsageDestinationTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/UsageDestinationTest.kt
new file mode 100644
index 00000000..ca605013
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/UsageDestinationTest.kt
@@ -0,0 +1,19 @@
+package com.codync.android.core
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class UsageDestinationTest {
+ private val query = "scope=local&computer=AAAAAAAAAAAAAAAAAAAAAA"
+ @Test fun usageLinksRetainTheirAccountAndComputerScope() {
+ val destination = UsageDestination.parse("codync://usage?$query", "codync")
+ assertEquals("local", destination.scope)
+ assertEquals("AAAAAAAAAAAAAAAAAAAAAA", destination.computerId)
+ }
+ @Test fun incompleteAmbiguousOrForeignLinksAreRejected() {
+ for (value in listOf("codync://usage", "codync://usage/path?$query", "codync://usage?$query&scope=local",
+ "codync://usage?$query#other", "https://usage?$query")) {
+ assertTrue(value, runCatching { UsageDestination.parse(value, "codync") }.isFailure)
+ }
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/UsageResetTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/UsageResetTest.kt
new file mode 100644
index 00000000..49a88c2f
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/UsageResetTest.kt
@@ -0,0 +1,20 @@
+package com.codync.android.core
+
+import java.time.ZonedDateTime
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class UsageResetTest {
+ private val now = ZonedDateTime.parse("2026-10-17T22:25:00+08:00[Asia/Taipei]").toInstant().toEpochMilli()
+ private fun at(text: String) = ZonedDateTime.parse(text).toInstant().toEpochMilli()
+
+ @Test fun `Claude Code reset texts read as the next such moment`() {
+ assertEquals(at("2026-10-18T01:10:00+08:00[Asia/Taipei]"), UsageWindow.parseReset("Oct 18 at 1:10am (Asia/Taipei)", now))
+ assertEquals(at("2026-10-24T12:00:00+08:00[Asia/Taipei]"), UsageWindow.parseReset("Oct 24 at 12pm (Asia/Taipei)", now))
+ // A bare time already past today is tomorrow; a date long past is next year.
+ assertEquals(at("2026-10-18T07:30:00+08:00[Asia/Taipei]"), UsageWindow.parseReset("7:30am (Asia/Taipei)", now))
+ assertEquals(at("2027-01-02T09:00:00+08:00[Asia/Taipei]"), UsageWindow.parseReset("Jan 2 at 9am (Asia/Taipei)", now))
+ assertNull(UsageWindow.parseReset("soon", now))
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/UsageTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/UsageTest.kt
new file mode 100644
index 00000000..661a1cc3
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/UsageTest.kt
@@ -0,0 +1,29 @@
+package com.codync.android.core
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class UsageTest {
+ @Test fun `unknown providers and missing windows remain distinct from zero consumption`() {
+ val report = UsageReport.decode(WireJson.parseToJsonElement("""{"providers":[{"id":"future","name":"Future agent","source":"future-source","windows":[{"id":"unknown","label":"Monthly"},{"id":"zero","label":"Daily","percent":0}]}]}"""))
+ val provider = report.providers.single()
+ assertEquals("future-source", provider.sourceLabel)
+ assertNull(provider.updatedAt)
+ assertNull(provider.windows.first().reportedPercent)
+ assertNull(provider.windows.first().barFraction)
+ assertEquals("zero", provider.tightest?.id)
+ assertEquals(0.0, provider.windows.last().reportedPercent!!, 0.0)
+ assertTrue(UsageReport.decode(WireJson.parseToJsonElement("{}" )).providers.isEmpty())
+ }
+
+ @Test fun `bars clamp drawing but retain the reported value and stale timestamp`() {
+ val window = UsageWindow("session", "Session", 103.5)
+ assertEquals(1f, window.barFraction!!, 0f)
+ assertEquals(103.5, window.reportedPercent!!, 0.0)
+ assertNull(window.copy(percent = Double.NaN).barFraction)
+ val provider = UsageProvider("codex", "Codex", listOf(window, window.copy(id = "week", percent = 15.0)), "sessions", 1)
+ assertEquals(1L, provider.updatedAt)
+ assertEquals("session", provider.tightest?.id)
+ assertEquals("Codex sessions", provider.sourceLabel)
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/VoiceTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/VoiceTest.kt
new file mode 100644
index 00000000..193a88af
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/VoiceTest.kt
@@ -0,0 +1,113 @@
+package com.codync.android.core
+
+import kotlinx.coroutines.*
+import kotlinx.coroutines.test.*
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Test
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class VoiceTest {
+ @Test fun voiceDurationShowsElapsedTimeAndRejectsInvalidHostValues() {
+ assertEquals("00:16", callDuration(16)); assertEquals("61:05", callDuration(3_665))
+ val entry = buildJsonObject { put("id", "call"); put("seq", 1); put("rev", 1); put("botId", "bot"); put("kind", "notice")
+ putJsonObject("data") { put("text", "Voice chat"); put("callSeconds", -1) } }
+ assertTrue(runCatching { Entry.decode(entry) }.isFailure)
+ }
+ private class Audio : VoiceAudio {
+ var generation = 0L; var input: ((VoiceInput) -> Unit)? = null
+ var closed = 0; var stops = 0; var speakerStops = 0
+ var failedInit = false; var failedClose = false
+ val spoken = mutableListOf<Pair<Long, String>>()
+ var done: ((Long, String?) -> Unit)? = null
+ override suspend fun initialize(): String { if (failedInit) error("Fixture unavailable"); return "Fixture local engine" }
+ override suspend fun listen(generation: Long, events: (VoiceInput) -> Unit) { this.generation = generation; input = events }
+ override suspend fun stopListening() { stops++ }
+ override suspend fun speak(id: Long, text: String, rate: Float, completed: (Long, String?) -> Unit) { spoken.add(id to text); done = completed }
+ override suspend fun stopSpeaking() { speakerStops++ }
+ override suspend fun close() { closed++; if (failedClose) error("Fixture close failure") }
+ fun text(value: String, final: Boolean = false, owner: Long = generation) { input?.invoke(VoiceInput.Text(owner, value, final)) }
+ }
+ @Test fun markdownBecomesSpeechAndChunksKeepSurrogatePairsIntact() {
+ val text = SpokenText.from("# Title\n\n**Hello**, [friend](https://example.com) and `code`.\n```sh\nsecret command\n```\n| A | B |\n|---|---|\n| one | two |")
+ assertEquals("Title\nHello, friend and code.\nA, B\none, two", text)
+ val value = "abc🐈def🐈ghi"
+ val chunks = SpokenText.chunks(value, 4)
+ assertEquals(value, chunks.joinToString(""))
+ assertTrue(chunks.all { it.length <= 4 && !it.last().isHighSurrogate() && !it.first().isLowSurrogate() })
+ }
+ @Test fun unchangedPartialResultsDoNotDelaySubmissionAndLateFinalsCannotResend() = runTest {
+ val audio = Audio(); val sent = mutableListOf<String>()
+ val session = VoiceSession(backgroundScope, audio, VoiceSettings(), sent::add)
+ runCurrent(); val original = audio.generation
+ audio.text(" first utterance "); runCurrent(); advanceTimeBy(1_000)
+ audio.text(" first utterance "); runCurrent(); advanceTimeBy(500); runCurrent()
+ assertEquals(listOf("first utterance"), sent)
+ audio.text("first utterance", final = true, owner = original); runCurrent()
+ assertEquals(listOf("first utterance"), sent)
+ audio.text("second utterance", final = true); runCurrent()
+ assertEquals(listOf("first utterance", "second utterance"), sent)
+ assertEquals(VoicePhase.Listening, session.state.value.phase)
+ session.end(); runCurrent(); session.awaitEnd(); assertEquals(1, audio.closed)
+ }
+ @Test fun muteAndAudioInterruptionDiscardPartialSpeechAndRespectMuteOnReturn() = runTest {
+ val audio = Audio(); val sent = mutableListOf<String>()
+ val session = VoiceSession(backgroundScope, audio, VoiceSettings(), sent::add)
+ runCurrent(); val original = audio.generation
+ audio.text("Never send this"); runCurrent(); session.mute(true); runCurrent()
+ audio.text("Never send this", true, original); advanceTimeBy(3_000); runCurrent()
+ assertTrue(sent.isEmpty()); assertTrue(session.state.value.muted)
+ session.focus(false); runCurrent(); assertEquals(VoicePhase.Interrupted, session.state.value.phase)
+ session.focus(true); runCurrent(); assertTrue(session.state.value.muted)
+ session.mute(false); runCurrent(); audio.text("After unmute", true); runCurrent()
+ assertEquals(listOf("After unmute"), sent)
+ session.end(); runCurrent(); session.awaitEnd()
+ }
+ @Test fun repliesPauseTheMicrophoneAndStalePlaybackCompletionCannotRestartIt() = runTest {
+ val audio = Audio(); val session = VoiceSession(backgroundScope, audio, VoiceSettings()) { fail("Playback audio must not submit text") }
+ runCurrent(); val recognition = audio.generation
+ session.speak("**First** reply"); runCurrent()
+ assertEquals(VoicePhase.Speaking, session.state.value.phase)
+ audio.text("Playback echo", true, recognition); runCurrent()
+ session.speak("Second reply"); runCurrent()
+ val first = audio.spoken.single().first
+ audio.done?.invoke(first, null); runCurrent()
+ assertEquals(listOf("First reply", "Second reply"), audio.spoken.map { it.second })
+ session.interrupt(); runCurrent(); val resumed = audio.generation
+ audio.done?.invoke(audio.spoken.last().first, null); runCurrent()
+ assertEquals(resumed, audio.generation)
+ session.end(); runCurrent(); session.awaitEnd()
+ audio.done?.invoke(first, null); runCurrent(); assertEquals(VoicePhase.Ended, session.state.value.phase)
+ }
+ @Test fun initializationFailureAndParentCancellationReleaseAudioExactlyOnce() = runTest {
+ val unavailable = Audio().apply { failedInit = true }
+ val failed = VoiceSession(backgroundScope, unavailable, VoiceSettings()) { fail("Failed call cannot send") }
+ runCurrent(); failed.awaitEnd(); assertNotNull(failed.state.value.error); assertEquals(1, unavailable.closed)
+ val owner = Job(backgroundScope.coroutineContext[Job]); val parent = CoroutineScope(backgroundScope.coroutineContext + owner)
+ val audio = Audio(); val session = VoiceSession(parent, audio, VoiceSettings()) { fail("Retired call cannot send") }
+ runCurrent(); owner.cancel(); runCurrent(); session.awaitEnd()
+ audio.text("Late callback", true); runCurrent(); assertEquals(1, audio.closed)
+ }
+ @Test fun aFailedAudioCloseStillEndsTheCallAndRejectsLateRecognition() = runTest {
+ val audio = Audio().apply { failedClose = true }
+ val session = VoiceSession(backgroundScope, audio, VoiceSettings()) { fail("Ended call cannot send") }
+ runCurrent(); session.end(); runCurrent(); session.awaitEnd()
+ assertEquals(VoicePhase.Ended, session.state.value.phase)
+ assertNotNull(session.state.value.error); assertEquals(1, audio.closed)
+ audio.text("Late recognition", true); runCurrent()
+ assertFalse(session.speak("A late reply")); assertEquals(1, audio.closed)
+ }
+ @Test fun replyGateIgnoresHistoryOtherBotsThreadsAndAlreadyFinalizedReplies() {
+ fun entry(id: String, rev: Long, bot: String = "active", thread: String? = null, final: Boolean = true) = Entry(
+ id, rev, bot, thread, rev, "agent", data = buildJsonObject { put("text", id); put("final", final) })
+ val old = entry("old", 5); val streaming = entry("streaming", 9, final = false)
+ val gate = VoiceReplyGate("active", 10, listOf(old, streaming))
+ val values = listOf(entry("old", 20), entry("streaming", 21), entry("reply", 22),
+ entry("thread", 23, thread = "root"), entry("other", 24, bot = "other"), entry("history", 6))
+ assertEquals(listOf("streaming", "reply"), gate.observe(values))
+ assertTrue(gate.observe(values).isEmpty())
+ val permission = Entry("approval", 25, "active", rev = 25, kind = "permission", data = buildJsonObject { put("status", "pending") })
+ assertEquals(1, gate.observe(values + permission).size)
+ assertTrue(gate.observe(values + permission).isEmpty())
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt
new file mode 100644
index 00000000..73f6c3db
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt
@@ -0,0 +1,19 @@
+package com.codync.android.core
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class WidgetFeedTest {
+ @Test fun attentionSortingExcludesDeletedAndHiddenBots() {
+ val bots = listOf(Bot("idle", "Idle"), Bot("hidden", "Hidden", hidden = true),
+ Bot("deleted", "Deleted", deleted = true), Bot("working", "Working", status = "working"),
+ Bot("approval", "Approval", status = "needsInput"))
+ assertEquals(listOf("approval", "working", "idle"), widgetBots(bots).map { it.id })
+ }
+
+ @Test fun `team spots keep picks, skip deleted ones and fill the rest in feed order`() {
+ val bots = listOf(WidgetBot("a", "A", "needsInput"), WidgetBot("b", "B", "working"), WidgetBot("c", "C", "idle"))
+ assertEquals(listOf("c", "a", "b", null), teamSlots(bots, listOf("c", "gone", null, null)).map { it?.id })
+ assertEquals(listOf("a", "b", "c", null), teamSlots(bots, emptyList()).map { it?.id })
+ }
+}
diff --git a/apps/android/design/build.gradle.kts b/apps/android/design/build.gradle.kts
new file mode 100644
index 00000000..b09dae0d
--- /dev/null
+++ b/apps/android/design/build.gradle.kts
@@ -0,0 +1,32 @@
+plugins {
+ alias(libs.plugins.android.library)
+ alias(libs.plugins.kotlin.compose)
+}
+
+android {
+ namespace = "com.codync.android.design"
+ compileSdk = 37
+ defaultConfig.minSdk = 29
+ buildFeatures.compose = true
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+}
+android.testOptions.unitTests.all {
+ it.systemProperty("codync.orbs", rootProject.file("../ios/Kit/Tests/CodyncKitTests/Fixtures/thinking-orbs-golden.json").absolutePath)
+}
+kotlin.compilerOptions.jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
+
+dependencies {
+ implementation(platform(libs.compose.bom))
+ implementation(libs.compose.ui)
+ implementation(libs.compose.foundation)
+ implementation(libs.compose.material3)
+ implementation(libs.lifecycle.compose)
+ implementation(libs.activity.compose)
+ api(libs.backdrop)
+ testImplementation(libs.junit)
+ testImplementation(libs.serialization.json)
+ api(libs.kyant.shapes)
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/CharacterAvatar.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/CharacterAvatar.kt
new file mode 100644
index 00000000..9427b812
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/CharacterAvatar.kt
@@ -0,0 +1,174 @@
+package com.codync.android.design
+
+import android.animation.ValueAnimator
+import android.graphics.Path
+import android.graphics.RectF
+import android.graphics.Region
+import androidx.compose.animation.core.*
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.*
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.material3.Text
+import androidx.compose.runtime.*
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.semantics.clearAndSetSemantics
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import androidx.lifecycle.compose.LocalLifecycleOwner
+import kotlin.math.*
+
+object AvatarPalette {
+ val colors = linkedMapOf("black" to 0xFF2B2B2B, "brown" to 0xFF936439, "red" to 0xFFFF263C,
+ "orange" to 0xFFFF6700, "yellow" to 0xFFFF9800, "green" to 0xFF00C972, "cyan" to 0xFF00BCA6,
+ "blue" to 0xFF1084FE, "violet" to 0xFF9159FE, "magenta" to 0xFFFF309B, "gray" to 0xFF777777)
+ val shapes = listOf("blob", "pebble", "squircle", "tablet", "wedge", "hex", "cloud", "teardrop")
+ fun tint(id: String): Color = Color(colors[id] ?: colors.getValue("blue"))
+}
+
+data class AvatarFace(val shape: String, val color: String, val status: String = "idle")
+
+/** Static system-widget drawing uses the same mask, palette and eyes as the app. */
+fun characterAvatarBitmap(shape: String, color: String, pixels: Int, ink: Int, highlight: Int? = null): android.graphics.Bitmap {
+ require(pixels in 1..256)
+ val bitmap = android.graphics.Bitmap.createBitmap(pixels, pixels, android.graphics.Bitmap.Config.ARGB_8888)
+ val canvas = android.graphics.Canvas(bitmap)
+ val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)
+ val cells = 9
+ val step = pixels / cells.toFloat()
+ val half = pixels / 2.0
+ val lx = sin(-.7) * .8; val ly = .55; val lz = cos(-.7) * .5 + .6
+ val ll = sqrt(lx * lx + ly * ly + lz * lz)
+ for ((row, col) in avatarDots(shape, cells)) {
+ if (col in listOf(3, 6) && row in listOf(3, 4)) continue
+ val x = (col + .5f) * step; val y = (row + .5f) * step
+ val u = (x - half) / half; val v = (half - y) / half
+ val z = sqrt(max(.2, 1.0 - u * u - v * v))
+ val shade = .3 + .7 * max(0.0, (u * lx + v * ly + z * lz) / (sqrt(u * u + v * v + z * z) * ll))
+ val radius = (step * .42 * (.55 + .45 * shade)).toFloat()
+ paint.color = ink; paint.alpha = ((.4 + .4 * shade) * 255).roundToInt().coerceIn(0, 255)
+ canvas.drawCircle(x, y, radius, paint)
+ if (shade > .6) {
+ paint.color = highlight ?: (AvatarPalette.colors[color] ?: AvatarPalette.colors.getValue("blue")).toInt()
+ paint.alpha = (((shade - .6) / .4) * 255).roundToInt().coerceIn(0, 255)
+ canvas.drawCircle(x, y, radius, paint)
+ }
+ }
+ return bitmap
+}
+
+/** Port of CodyncKit's dotted character; the accompanying name/status supplies accessibility text. */
+@Composable fun CharacterAvatar(shape: String, color: String, size: Dp = 40.dp, status: String = "idle", monochrome: Color? = null,
+ highlight: Color? = null) {
+ val owner = LocalLifecycleOwner.current
+ var active by remember(owner) { mutableStateOf(owner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) }
+ DisposableEffect(owner) {
+ val observer = LifecycleEventObserver { _, _ -> active = owner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) }
+ owner.lifecycle.addObserver(observer)
+ onDispose { owner.lifecycle.removeObserver(observer) }
+ }
+ val time = if (active && status in listOf("working", "needsInput") && ValueAnimator.areAnimatorsEnabled()) {
+ val transition = rememberInfiniteTransition(label = "Character activity")
+ val seconds by transition.animateFloat(0f, 3600f, infiniteRepeatable(tween(3_600_000, easing = LinearEasing)), label = "Character light and eyes")
+ seconds.toDouble()
+ } else 0.0
+ val cells = if (size < 18.dp) 7 else if (size < 28.dp) 9 else 13
+ val dots = remember(shape, cells) { avatarDots(shape, cells) }
+ val ink = monochrome ?: Palette.text
+ val tint = monochrome ?: highlight ?: AvatarPalette.tint(color)
+ Canvas(Modifier.size(size).clearAndSetSemantics { }) {
+ val step = this.size.width / cells
+ val half = this.size.width / 2
+ val glance = if (status == "working" && time > 0) (sin(time * 2 * PI / 3.2) * 1.4).roundToInt() else 0
+ val eyes = (when (cells) { 7 -> listOf(2, 4); 9 -> listOf(3, 6); else -> listOf(4, 8) }).map { it + glance }
+ val eyeRows = when (cells) { 7 -> listOf(2, 3); 9 -> listOf(3, 4); else -> listOf(4, 5, 6) }
+ val blinking = time > 0 && (time / 4.7) % 1 < 0.035
+ val yaw = if (status == "working" && time > 0) time * 1.4 else -0.7
+ val lx = sin(yaw) * .8; val ly = .55; val lz = cos(yaw) * .5 + .6
+ val ll = sqrt(lx * lx + ly * ly + lz * lz)
+ for ((row, col) in dots) {
+ if (col in eyes && row in if (blinking) eyeRows.takeLast(1) else eyeRows) continue
+ val center = Offset((col + .5f) * step, (row + .5f) * step)
+ val u = (center.x - half) / half; val v = (half - center.y) / half
+ val z = sqrt(max(.2, 1.0 - u * u - v * v))
+ val nl = sqrt(u * u + v * v + z * z)
+ var shade = .3 + .7 * max(0.0, (u * lx + v * ly + z * lz) / (nl * ll))
+ if (status == "needsInput") shade *= .6 + .4 * (.5 + .5 * sin(sqrt((u * u + v * v).toDouble()) * 9 - time * 5))
+ val radius = (step * .42 * (.55 + .45 * shade)).toFloat()
+ val alpha = if (cells < 13) .4 + .4 * shade else .2 + .4 * min(1.0, shade / .7)
+ drawCircle(ink.copy(alpha = alpha.toFloat()), radius, center)
+ if (shade > .6) drawCircle(tint.copy(alpha = ((shade - .6) / .4).toFloat().coerceIn(0f, 1f)), radius, center)
+ }
+ }
+}
+
+@Composable fun GroupAvatar(faces: List<AvatarFace>, size: Dp = 40.dp) {
+ Box(Modifier.size(size).clearAndSetSemantics { }) {
+ fun side(fraction: Float) = size * fraction
+ @Composable fun place(index: Int, fraction: Float, align: Alignment) {
+ val face = faces[index]
+ Box(Modifier.align(align)) { CharacterAvatar(face.shape, face.color, side(fraction), face.status) }
+ }
+ when (faces.size) {
+ 0 -> Symbol("person.2", Modifier.align(Alignment.Center), size = size * 0.4f, tint = Palette.secondary)
+ 1 -> place(0, 1f, Alignment.Center)
+ 2 -> { place(1, .66f, Alignment.TopEnd); place(0, .66f, Alignment.BottomStart) }
+ 3 -> { place(0, .55f, Alignment.TopCenter); place(1, .55f, Alignment.BottomStart); place(2, .55f, Alignment.BottomEnd) }
+ else -> {
+ place(0, .5f, Alignment.TopStart); place(1, .5f, Alignment.TopEnd); place(2, .5f, Alignment.BottomStart)
+ if (faces.size == 4) place(3, .5f, Alignment.BottomEnd)
+ else Box(Modifier.size(size * .5f).align(Alignment.BottomEnd), contentAlignment = Alignment.Center) {
+ Text("+${faces.size - 3}", style = Type.system(size.value * 0.24f, FontWeight.Bold), color = Palette.secondary)
+ }
+ }
+ }
+ }
+}
+
+/** Integer mask is computed once per shape/grid, never in the animation loop. */
+private fun avatarDots(shape: String, cells: Int): List<Pair<Int, Int>> {
+ val path = avatarPath(shape)
+ val region = Region().apply { setPath(path, Region(-100, -100, 1100, 1100)) }
+ return buildList { for (row in 0 until cells) for (col in 0 until cells)
+ if (region.contains(((col + .5) * 1000 / cells).toInt(), ((row + .5) * 1000 / cells).toInt())) add(row to col) }
+}
+
+private fun avatarPath(shape: String): Path = Path().apply {
+ fillType = Path.FillType.WINDING
+ when (shape) {
+ "pebble" -> addOval(RectF(0f, 100f, 1000f, 900f), Path.Direction.CW)
+ "squircle" -> addRoundRect(RectF(40f, 40f, 960f, 960f), 300f, 300f, Path.Direction.CW)
+ "tablet" -> addRoundRect(RectF(140f, 0f, 860f, 1000f), 220f, 220f, Path.Direction.CW)
+ "wedge" -> { moveTo(500f, 40f); quadTo(900f, 400f, 980f, 860f); quadTo(500f, 1040f, 20f, 860f); quadTo(100f, 400f, 500f, 40f); close() }
+ "hex" -> {
+ for (i in 0 until 6) {
+ val angle = i * PI / 3 - PI / 2
+ val x = (500 + cos(angle) * 490).toFloat(); val y = (500 + sin(angle) * 490).toFloat()
+ if (i == 0) moveTo(x, y) else lineTo(x, y)
+ }
+ close()
+ val stroke = Path()
+ android.graphics.Paint().apply { style = android.graphics.Paint.Style.STROKE; strokeWidth = 80f; strokeJoin = android.graphics.Paint.Join.ROUND }.getFillPath(this, stroke)
+ op(stroke, Path.Op.UNION)
+ }
+ "cloud" -> {
+ addOval(RectF(0f, 300f, 550f, 850f), Path.Direction.CW)
+ addOval(RectF(450f, 300f, 1000f, 850f), Path.Direction.CW)
+ addOval(RectF(180f, 80f, 820f, 720f), Path.Direction.CW)
+ addRoundRect(RectF(100f, 500f, 900f, 850f), 150f, 150f, Path.Direction.CW)
+ }
+ "teardrop" -> { moveTo(500f, 0f); cubicTo(620f, 200f, 940f, 380f, 940f, 620f)
+ arcTo(RectF(60f, 180f, 940f, 1060f), 0f, 180f); cubicTo(60f, 380f, 380f, 200f, 500f, 0f); close() }
+ else -> { for (i in 0..64) {
+ val angle = i / 64.0 * 2 * PI; val radius = .46 + .035 * sin(angle * 3 + .6)
+ val x = (500 + cos(angle) * 1000 * radius).toFloat(); val y = (500 + sin(angle) * 1000 * radius).toFloat()
+ if (i == 0) moveTo(x, y) else lineTo(x, y)
+ }; close() }
+ }
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Chrome.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Chrome.kt
new file mode 100644
index 00000000..d22b247a
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Chrome.kt
@@ -0,0 +1,161 @@
+package com.codync.android.design
+
+import androidx.activity.compose.PredictiveBackHandler
+import androidx.compose.animation.core.Animatable
+import androidx.compose.animation.core.animateDpAsState
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.RowScope
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.selection.selectable
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveableStateHolder
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.heading
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.dp
+import com.kyant.shapes.Capsule
+import kotlinx.coroutines.CancellationException
+import kotlin.math.roundToInt
+
+// Codync's screen chrome, as CodyncUI `Chrome.swift` has it: headers, back buttons, the tab bar
+// and the push navigation of a `NavigationStack`.
+
+/** A modal's title row: title, optional trailing actions, and a close button. */
+@Composable fun ModalHeader(title: String, trailing: @Composable RowScope.() -> Unit = {}) =
+ ModalHeader({ Text(title, style = Type.body.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis) }, trailing)
+
+@Composable fun ModalHeader(title: @Composable RowScope.() -> Unit, trailing: @Composable RowScope.() -> Unit = {}) {
+ val dismiss = LocalDismissModal.current
+ Row(Modifier.fillMaxWidth().height(56.dp).padding(start = 20.dp, end = 12.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Row(Modifier.weight(1f).semantics(mergeDescendants = true) { heading() }, verticalAlignment = Alignment.CenterVertically) { title() }
+ trailing()
+ IconButton("Close", "xmark", action = dismiss)
+ }
+}
+
+/** A full screen's top bar: leading, centered title, trailing. */
+@Composable fun ScreenHeader(leading: @Composable RowScope.() -> Unit = {}, title: @Composable () -> Unit = {},
+ trailing: @Composable RowScope.() -> Unit = {}) {
+ Box(Modifier.fillMaxWidth().height(52.dp).background(Palette.background).padding(horizontal = 12.dp), contentAlignment = Alignment.Center) {
+ Box(Modifier.semantics(mergeDescendants = true) { heading() }) { title() }
+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ leading()
+ Spacer(Modifier.weight(1f))
+ trailing()
+ }
+ }
+}
+
+/** The back button for a pushed screen. */
+@Composable fun BackButton(action: () -> Unit) = IconButton("Back", "chevron.left", action = action)
+
+/** A page's title row: the close button on a modal's first page, a back button once pushed in it. */
+@Composable fun PageHeader(title: String, pop: (() -> Unit)? = null, trailing: @Composable RowScope.() -> Unit = {}) {
+ if (pop != null) ScreenHeader({ BackButton(pop) },
+ { Text(title, style = Type.body.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis) }, trailing)
+ else ModalHeader(title, trailing)
+}
+
+/** One tab of the system tab bar. */
+class TabItem<T>(val value: T, val title: String, val systemImage: String, val iconSize: Dp = 28.dp)
+
+/** The iOS 26 tab bar: a floating glass capsule whose selection pill slides between tabs. */
+@Composable fun <T> GlassTabBar(selection: T, tabs: List<TabItem<T>>, select: (T) -> Unit, modifier: Modifier = Modifier) {
+ val index = tabs.indexOfFirst { it.value == selection }.coerceAtLeast(0)
+ val pill by animateDpAsState(TAB_WIDTH * index, Motion.layout(), label = "Tab selection")
+ Box(modifier.glass(Capsule()).padding(4.dp)) {
+ Box(Modifier.offset(x = pill).size(TAB_WIDTH, 54.dp).clip(Capsule()).background(Palette.text.copy(alpha = 0.07f)))
+ Row {
+ for (tab in tabs) {
+ val on = tab.value == selection
+ Column(Modifier.size(TAB_WIDTH, 54.dp).clip(Capsule()).selectable(on, role = Role.Tab) { select(tab.value) },
+ horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
+ Symbol(tab.systemImage, size = tab.iconSize, height = 28.dp, tint = Palette.text)
+ Text(tab.title, style = Type.system(10f).medium, color = Palette.text, maxLines = 1)
+ }
+ }
+ }
+ }
+}
+
+private val TAB_WIDTH = 90.dp
+
+/**
+ * `NavigationStack`: the top screen slides in from the right over the one below, which drifts
+ * left and dims; the system back gesture drags it away like the iOS edge swipe.
+ */
+@Composable fun <T : Any> NavStack(stack: List<T>, key: (T) -> Any, pop: () -> Unit, modifier: Modifier = Modifier,
+ content: @Composable (T) -> Unit) {
+ val holder = rememberSaveableStateHolder()
+ var shown by remember { mutableStateOf(stack) }
+ val away = remember { Animatable(0f) }
+ LaunchedEffect(stack) {
+ when {
+ stack.size > shown.size -> { shown = stack; away.snapTo(1f); away.animateTo(0f, Motion.present()) }
+ stack.size < shown.size -> {
+ if (away.value < 1f) away.animateTo(1f, Motion.present())
+ shown = stack; away.snapTo(0f)
+ }
+ else -> shown = stack
+ }
+ }
+ PredictiveBackHandler(enabled = stack.size > 1 && stack == shown) { events ->
+ try {
+ events.collect { away.snapTo(it.progress * 0.9f) }
+ away.animateTo(1f, Motion.layout())
+ pop()
+ } catch (cancelled: CancellationException) {
+ away.animateTo(0f, Motion.layout())
+ throw cancelled
+ }
+ }
+ BoxWithConstraints(modifier.fillMaxSize()) {
+ val width = with(LocalDensity.current) { maxWidth.toPx() }
+ val below = shown.getOrNull(shown.size - 2)
+ if (below != null && away.value > 0f) Box(Modifier.fillMaxSize()
+ .offset { IntOffset((-0.3f * width * (1f - away.value)).roundToInt(), 0) }) {
+ holder.SaveableStateProvider(key(below)) { content(below) }
+ Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.12f * (1f - away.value))))
+ }
+ val top = shown.lastOrNull() ?: return@BoxWithConstraints
+ Box(Modifier.fillMaxSize().offset { IntOffset((width * away.value).roundToInt(), 0) }
+ .graphicsLayer { shadowElevation = if (away.value > 0f) 16f else 0f }) {
+ holder.SaveableStateProvider(key(top)) { content(top) }
+ }
+ }
+}
+
+/** A tappable row that dims while pressed (`Button { } .buttonStyle(.plain)`). */
+@Composable fun Modifier.plainButton(enabled: Boolean = true, role: Role = Role.Button, action: () -> Unit): Modifier {
+ val (source, pressed) = rememberPress()
+ return clickable(source, null, enabled = enabled, role = role, onClick = action).graphicsLayer { alpha = if (pressed) 0.6f else 1f }
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/CodyncTheme.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/CodyncTheme.kt
new file mode 100644
index 00000000..889170d7
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/CodyncTheme.kt
@@ -0,0 +1,71 @@
+package com.codync.android.design
+
+import androidx.compose.foundation.isSystemInDarkTheme
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.darkColorScheme
+import androidx.compose.material3.lightColorScheme
+import androidx.compose.material3.LocalContentColor
+import androidx.compose.material3.LocalTextStyle
+import androidx.compose.material3.Typography
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.ui.graphics.Color
+
+/** Keep these pairs aligned with CodyncKit/Design/Theme.swift. */
+val botMessageBackground: Color
+ @Composable get() = if (isSystemInDarkTheme()) Color(0xFF15263E) else Color(0xFFEAF2FF)
+
+@Composable
+fun CodyncTheme(content: @Composable () -> Unit) {
+ val dark = isSystemInDarkTheme()
+ val colors = if (dark) darkColorScheme(
+ primary = Color.White,
+ onPrimary = Color.Black,
+ secondary = Color.White,
+ onSecondary = Color.Black,
+ tertiary = Color.White,
+ onTertiary = Color.Black,
+ background = Color(0xFF0A0A0A),
+ onBackground = Color(0xFFF2F2F2),
+ surface = Color(0xFF141414),
+ onSurface = Color(0xFFF2F2F2),
+ onSurfaceVariant = Color(0xFF9A9A9A),
+ surfaceVariant = Color(0xFF1C1C1C),
+ surfaceContainer = Color(0xFF1C1C1C),
+ surfaceContainerLow = Color(0xFF141414),
+ surfaceContainerHigh = Color(0xFF1C1C1C),
+ surfaceContainerHighest = Color(0xFF3A3A3A),
+ surfaceTint = Color.Transparent,
+ error = Color(0xFFF0A7A7),
+ ) else lightColorScheme(
+ primary = Color.Black,
+ onPrimary = Color.White,
+ secondary = Color.Black,
+ onSecondary = Color.White,
+ tertiary = Color.Black,
+ onTertiary = Color.White,
+ background = Color.White,
+ onBackground = Color(0xFF141414),
+ surface = Color(0xFFF4F4F4),
+ onSurface = Color(0xFF141414),
+ onSurfaceVariant = Color(0xFF6B6B6B),
+ surfaceVariant = Color(0xFFF0F0F0),
+ surfaceContainer = Color(0xFFF0F0F0),
+ surfaceContainerLow = Color(0xFFF4F4F4),
+ surfaceContainerHigh = Color(0xFFF0F0F0),
+ surfaceContainerHighest = Color(0xFFE2E2E2),
+ surfaceTint = Color.Transparent,
+ error = Color(0xFFC23A2B),
+ )
+ val type = Typography(
+ headlineLarge = Type.largeTitle, headlineMedium = Type.title, headlineSmall = Type.title2,
+ titleLarge = Type.title3.semibold, titleMedium = Type.headline, titleSmall = Type.subheadline.medium,
+ bodyLarge = Type.body, bodyMedium = Type.subheadline, bodySmall = Type.footnote,
+ labelLarge = Type.subheadline.medium, labelMedium = Type.caption.medium, labelSmall = Type.caption2.medium,
+ )
+ CompositionLocalProvider(LocalDark provides dark) {
+ MaterialTheme(colorScheme = colors, typography = type) {
+ CompositionLocalProvider(LocalTextStyle provides Type.body, LocalContentColor provides Palette.text, content = content)
+ }
+ }
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Controls.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Controls.kt
new file mode 100644
index 00000000..c0faaa56
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Controls.kt
@@ -0,0 +1,320 @@
+package com.codync.android.design
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.animateColorAsState
+import androidx.compose.animation.core.LinearEasing
+import androidx.compose.animation.core.RepeatMode
+import androidx.compose.animation.core.animateDpAsState
+import androidx.compose.animation.core.animateFloat
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.infiniteRepeatable
+import androidx.compose.animation.core.rememberInfiniteTransition
+import androidx.compose.animation.core.tween
+import androidx.compose.animation.expandVertically
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.shrinkVertically
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ColumnScope
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.RowScope
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.selection.selectable
+import androidx.compose.foundation.selection.toggleable
+import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.LocalContentColor
+import androidx.compose.material3.LocalTextStyle
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.getValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.rotate
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.graphics.isSpecified
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.heading
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.semantics.stateDescription
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+
+// Codync's own controls, as CodyncUI `Controls.swift` draws them. Anything with a background
+// fill gets no border line.
+
+/** Shrinks to 98% in 50 ms while pressed (Grok's press). */
+@Composable fun Modifier.pressScale(pressed: Boolean): Modifier {
+ val scale by animateFloatAsState(if (pressed) Motion.PRESS_SCALE else 1f, Motion.press(), label = "Press")
+ return graphicsLayer { scaleX = scale; scaleY = scale }
+}
+
+/** Plain icon button that lights up on press. Icon-only, labelled for TalkBack. */
+@Composable fun IconButton(title: String, systemImage: String, modifier: Modifier = Modifier, enabled: Boolean = true,
+ tint: Color = Color.Unspecified, action: () -> Unit) {
+ val (source, pressed) = rememberPress()
+ Box(modifier.size(36.dp).pressScale(pressed).clip(RoundedRectangle(10.dp))
+ .background(Palette.text.copy(alpha = if (pressed) 0.14f else 0f))
+ .clickable(source, null, enabled = enabled, role = Role.Button, onClick = action)
+ .semantics { contentDescription = title }
+ .graphicsLayer { alpha = if (enabled) 1f else 0.35f }, contentAlignment = Alignment.Center) {
+ Symbol(systemImage, size = 21.dp, tint = if (tint.isSpecified) tint else Palette.secondary)
+ }
+}
+
+/** A filled capsule button: `.buttonStyle(.primary)` (accent) or `.secondary`. */
+@Composable fun PrimaryButton(title: String, modifier: Modifier = Modifier, enabled: Boolean = true, action: () -> Unit) =
+ PrimaryButton(action, modifier, enabled) { Text(title, maxLines = 1) }
+
+@Composable fun SecondaryButton(title: String, modifier: Modifier = Modifier, enabled: Boolean = true, action: () -> Unit) =
+ SecondaryButton(action, modifier, enabled) { Text(title, maxLines = 1) }
+
+/** `.buttonStyle(.primary)` around any label (the label sets its own font and frame). */
+@Composable fun PrimaryButton(action: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, label: @Composable () -> Unit) =
+ StyledButton(Palette.accentFill, Palette.onAccent, modifier, enabled, action, label)
+
+@Composable fun SecondaryButton(action: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, label: @Composable () -> Unit) =
+ StyledButton(Palette.bubbleUser, Palette.text, modifier, enabled, action, label)
+
+@Composable private fun StyledButton(fill: Color, ink: Color, modifier: Modifier, enabled: Boolean, action: () -> Unit, label: @Composable () -> Unit) {
+ val (source, pressed) = rememberPress()
+ Box(modifier.pressScale(pressed).graphicsLayer { alpha = if (enabled) (if (pressed) 0.85f else 1f) else 0.4f }
+ .clip(Capsule()).background(fill)
+ .clickable(source, null, enabled = enabled, role = Role.Button, onClick = action)
+ .padding(horizontal = 18.dp, vertical = 11.dp), contentAlignment = Alignment.Center) {
+ CompositionLocalProvider(LocalTextStyle provides Type.body.medium, LocalContentColor provides ink) { label() }
+ }
+}
+
+/** The text-only button iOS draws in the tint color (`Button(_:) .plain` links). */
+@Composable fun LinkButton(title: String, modifier: Modifier = Modifier, enabled: Boolean = true, color: Color = Palette.text,
+ style: TextStyle = Type.body, action: () -> Unit) {
+ val (source, pressed) = rememberPress()
+ Text(title, modifier.clickable(source, null, enabled = enabled, role = Role.Button, onClick = action)
+ .graphicsLayer { alpha = if (!enabled) 0.4f else if (pressed) 0.5f else 1f }, style = style, color = color)
+}
+
+/** On/off switch: label on the left, a flat capsule track on the right. */
+@Composable fun CodyncSwitch(checked: Boolean, onChange: (Boolean) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true,
+ label: @Composable RowScope.() -> Unit) {
+ val track by animateColorAsState(if (checked) Palette.accentFill else Palette.bubbleUser, Motion.hover(), label = "Track")
+ val knob by animateDpAsState(if (checked) 14.dp else 0.dp, Motion.hover(), label = "Knob")
+ val knobInk = if (checked) Palette.onAccent else Color.White
+ Row(modifier.toggleable(checked, enabled = enabled, role = Role.Switch, onValueChange = onChange)
+ .graphicsLayer { alpha = if (enabled) 1f else 0.4f },
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ label()
+ Spacer(Modifier.weight(1f))
+ Box(Modifier.size(34.dp, 20.dp).clip(Capsule()).background(track).padding(2.dp)) {
+ Box(Modifier.offset(x = knob).size(16.dp).clip(Capsule()).background(knobInk))
+ }
+ }
+}
+
+/** Loading indicator: a thin arc that turns. */
+@Composable fun Spinner(size: Dp = 14.dp, modifier: Modifier = Modifier, color: Color = Palette.secondary) {
+ val turn by rememberInfiniteTransition(label = "Spinner").animateFloat(0f, 360f,
+ infiniteRepeatable(tween(800, easing = LinearEasing), RepeatMode.Restart), label = "Turn")
+ val width = with(LocalDensity.current) { maxOf(1.5.dp, size / 9).toPx() }
+ Canvas(modifier.size(size).rotate(turn).semantics { contentDescription = "Loading" }) {
+ drawArc(color, 0f, 252f, false, style = Stroke(width, cap = StrokeCap.Round))
+ }
+}
+
+/** Picks one of a few values side by side: the replacement for `.segmented`. */
+@Composable fun <T> SegmentedChoice(selection: T, options: List<Pair<T, String>>, select: (T) -> Unit, modifier: Modifier = Modifier) {
+ BoxWithConstraints(modifier.fillMaxWidth().clip(Capsule()).background(Palette.bubbleUser).padding(3.dp)) {
+ val index = options.indexOfFirst { it.first == selection }.coerceAtLeast(0)
+ val segment = (maxWidth - 2.dp * (options.size - 1)) / options.size
+ val thumb by animateDpAsState((segment + 2.dp) * index, Motion.morph(), label = "Thumb")
+ Box(Modifier.offset(x = thumb).width(segment).height(36.dp).clip(Capsule()).background(Palette.background))
+ Row(horizontalArrangement = Arrangement.spacedBy(2.dp)) {
+ for ((id, label) in options) {
+ val on = id == selection
+ Box(Modifier.width(segment).height(36.dp).clip(Capsule())
+ .selectable(on, role = Role.Tab) { select(id) }, contentAlignment = Alignment.Center) {
+ Text(label, style = Type.subheadline.medium, color = if (on) Palette.text else Palette.secondary, maxLines = 1)
+ }
+ }
+ }
+ }
+}
+
+/** One choice per row with a checkmark: the replacement for `.inline` pickers. */
+@Composable fun <T> ChoiceList(selection: T, options: List<Triple<T, String, String?>>, select: (T) -> Unit, modifier: Modifier = Modifier) {
+ Column(modifier, verticalArrangement = Arrangement.spacedBy(14.dp)) {
+ for ((id, label, detail) in options) {
+ Row(Modifier.fillMaxWidth().selectable(id == selection, role = Role.RadioButton) { select(id) },
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(label, style = Type.body, color = Palette.text)
+ if (!detail.isNullOrEmpty()) Text(detail, style = Type.subheadline, color = Palette.secondary)
+ }
+ Symbol("checkmark", size = 15.dp, tint = Palette.text, modifier = Modifier.graphicsLayer { alpha = if (id == selection) 1f else 0f })
+ }
+ }
+ }
+}
+
+/** Shows the current choice in a pill with a chevron and opens the menu: `ChoicePicker`. */
+@Composable fun <T> ChoicePicker(selection: T, options: List<Pair<T, String>>, select: (T) -> Unit, modifier: Modifier = Modifier,
+ fill: Color = Color.Transparent, label: String? = null) {
+ val current = options.firstOrNull { it.first == selection }?.second ?: "Choose"
+ DropdownMenu({ options.map { (id, text) -> MenuItem(text, selected = id == selection) { select(id) } } }, modifier,
+ label = label?.let { "$it: $current" }) {
+ Row(Modifier.then(if (fill == Color.Transparent) Modifier.outline() else Modifier).pill(fill),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(current, style = Type.body, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Symbol("chevron.down", size = 13.dp, tint = Palette.secondary)
+ }
+ }
+}
+
+/** A scrolling page of cards: the replacement for `Form` / grouped `List`. */
+@Composable fun CardForm(modifier: Modifier = Modifier, padding: PaddingValues = PaddingValues(20.dp),
+ content: @Composable ColumnScope.() -> Unit) {
+ Column(modifier.fillMaxSize().background(Palette.background).verticalScroll(rememberScrollState()).padding(padding),
+ verticalArrangement = Arrangement.spacedBy(32.dp)) {
+ CompositionLocalProvider(LocalTextStyle provides Type.body, LocalContentColor provides Palette.text) { content() }
+ }
+}
+
+/** The rows of a `CardSection`, split by inset hairlines. */
+class CardRows internal constructor() {
+ internal val rows = mutableListOf<@Composable () -> Unit>()
+ fun row(content: @Composable () -> Unit) { rows += content }
+}
+
+/**
+ * A titled group of rows: the replacement for `Section`. A small bold heading over a filled,
+ * rounded group whose rows are split by inset hairlines (ChatGPT's desktop settings).
+ */
+@Composable fun CardSection(title: String? = null, footer: String? = null, modifier: Modifier = Modifier,
+ accessory: @Composable RowScope.() -> Unit = {}, rows: CardRows.() -> Unit) {
+ val list = CardRows().apply(rows).rows
+ Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ if (title != null) Row(Modifier.padding(start = 2.dp), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(title, Modifier.weight(1f).semantics { heading() }, style = Type.system(15f).semibold, color = Palette.text)
+ accessory()
+ }
+ if (list.isNotEmpty()) Column(Modifier.fillMaxWidth().clip(RoundedRectangle(16.dp)).background(Palette.surface)) {
+ for ((index, row) in list.withIndex()) {
+ Box(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 14.dp).heightIn(min = 32.dp),
+ contentAlignment = Alignment.CenterStart) {
+ CompositionLocalProvider(LocalTextStyle provides Type.body, LocalContentColor provides Palette.text) { row() }
+ }
+ if (index < list.lastIndex) Hairline(Modifier.padding(horizontal = 16.dp))
+ }
+ }
+ if (footer != null) Text(footer, Modifier.padding(horizontal = 2.dp), style = Type.caption.copy(lineHeight = Type.caption.lineHeight * 1.12f),
+ color = Palette.secondary)
+ }
+}
+
+/** A 1-pixel separator line in the border color. */
+@Composable fun Hairline(modifier: Modifier = Modifier) {
+ val px = with(LocalDensity.current) { 1f.toDp() }
+ Box(modifier.fillMaxWidth().height(px).background(Palette.border))
+}
+
+/** Label on the left, value on the right: the replacement for `LabeledContent`. */
+@Composable fun ValueRow(label: String, modifier: Modifier = Modifier, detail: String? = null, value: @Composable () -> Unit) {
+ Row(modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
+ Text(label, style = Type.body, color = Palette.text)
+ if (detail != null) Text(detail, style = Type.caption.copy(lineHeight = Type.caption.lineHeight * 1.12f), color = Palette.secondary)
+ }
+ CompositionLocalProvider(LocalContentColor provides Palette.secondary, LocalTextStyle provides Type.body.copy(color = Palette.secondary)) { value() }
+ }
+}
+
+@Composable fun ValueRow(label: String, value: String, modifier: Modifier = Modifier, detail: String? = null) =
+ ValueRow(label, modifier, detail) { Text(value, style = Type.body, color = Palette.secondary) }
+
+/** A search box: the replacement for `.searchable`. */
+@Composable fun SearchField(text: String, onChange: (String) -> Unit, modifier: Modifier = Modifier, prompt: String = "Search") {
+ Row(modifier.fillMaxWidth().clip(Capsule()).background(Palette.bubbleAgent).padding(horizontal = 14.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol("magnifyingglass", size = 19.dp, tint = Palette.secondary)
+ PlainTextField(text, onChange, Modifier.weight(1f), prompt, singleLine = true, imeAction = ImeAction.Search)
+ if (text.isNotEmpty()) Box(Modifier.clickable(role = Role.Button) { onChange("") }.semantics { contentDescription = "Clear search" }) {
+ Symbol("xmark.circle.fill", size = 18.dp, tint = Palette.tertiary)
+ }
+ }
+}
+
+/** `TextField(...).textFieldStyle(.plain)`: no chrome, a placeholder in the secondary ink. */
+@Composable fun PlainTextField(text: String, onChange: (String) -> Unit, modifier: Modifier = Modifier, prompt: String = "",
+ singleLine: Boolean = false, style: TextStyle = Type.body, minLines: Int = 1, maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE,
+ imeAction: ImeAction = ImeAction.Default, enabled: Boolean = true, keyboard: KeyboardOptions = KeyboardOptions(imeAction = imeAction),
+ actions: KeyboardActions = KeyboardActions.Default) {
+ BasicTextField(text, onChange, modifier, enabled = enabled, singleLine = singleLine, minLines = minLines, maxLines = maxLines,
+ textStyle = style.copy(color = Palette.text), cursorBrush = SolidColor(Palette.accent), keyboardOptions = keyboard, keyboardActions = actions,
+ decorationBox = { field ->
+ Box(contentAlignment = Alignment.CenterStart) {
+ // A centered field centers its placeholder too.
+ if (text.isEmpty()) Text(prompt, if (style.textAlign == TextAlign.Center) Modifier.fillMaxWidth() else Modifier, style = style,
+ color = Palette.tertiary, maxLines = if (singleLine) 1 else Int.MAX_VALUE)
+ field()
+ }
+ })
+}
+
+/** A row that expands to show more: the replacement for `DisclosureGroup`. */
+@Composable fun Disclosure(expanded: Boolean, toggle: () -> Unit, modifier: Modifier = Modifier, label: @Composable RowScope.() -> Unit,
+ content: @Composable ColumnScope.() -> Unit) {
+ val turn by animateFloatAsState(if (expanded) 90f else 0f, Motion.layout(), label = "Chevron")
+ Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Row(Modifier.fillMaxWidth().clickable(role = Role.Button, onClick = toggle)
+ .semantics { stateDescription = if (expanded) "Expanded" else "Collapsed" },
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, content = label)
+ Symbol("chevron.right", Modifier.rotate(turn), size = 13.dp, tint = Palette.secondary)
+ }
+ AnimatedVisibility(expanded, enter = fadeIn(Motion.fade()) + expandVertically(Motion.layoutSize),
+ exit = fadeOut(Motion.fade()) + shrinkVertically(Motion.layoutSize)) { Column(content = content) }
+ }
+}
+
+/** The value pill: a filled rounded box, no border. */
+@Composable fun Modifier.pill(fill: Color = Palette.background) =
+ clip(RoundedRectangle(10.dp)).background(fill).padding(horizontal = 12.dp, vertical = 7.dp)
+
+/** An outlined value pill, like ChatGPT's settings dropdowns (outline or fill, never both). */
+@Composable fun Modifier.outline() = border(1.dp, Palette.border, RoundedRectangle(10.dp))
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Dialog.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Dialog.kt
new file mode 100644
index 00000000..461037c1
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Dialog.kt
@@ -0,0 +1,85 @@
+package com.codync.android.design
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.core.Animatable
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.platform.LocalFocusManager
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.paneTitle
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+
+/** A button in a Codync dialog. */
+class DialogAction(val title: String, val destructive: Boolean = false, val action: () -> Unit)
+
+/**
+ * A centered card over a dimmed screen with the actions and Cancel: the replacement for
+ * `confirmationDialog` and `alert`.
+ */
+@Composable fun CodyncDialog(title: String, isPresented: Boolean, onDismiss: () -> Unit, message: String? = null,
+ cancel: String? = "Cancel", actions: () -> List<DialogAction>) {
+ val shown = remember { Animatable(0f) }
+ var mounted by remember { mutableStateOf(isPresented) }
+ val focus = LocalFocusManager.current
+ LaunchedEffect(isPresented) {
+ if (isPresented) { mounted = true; focus.clearFocus(); shown.animateTo(1f, Motion.layout()) }
+ else { shown.animateTo(0f, Motion.fade()); mounted = false }
+ }
+ if (!mounted) return
+ val dismiss by rememberUpdatedState(onDismiss)
+ BackHandler(isPresented && cancel != null) { dismiss() }
+ Overlay {
+ Box(Modifier.fillMaxSize().graphicsLayer { alpha = shown.value }.background(Color.Black.copy(alpha = 0.35f))
+ .clickable(remember { MutableInteractionSource() }, null) { if (cancel != null) dismiss() }
+ .padding(24.dp), contentAlignment = Alignment.Center) {
+ Column(Modifier.widthIn(max = 320.dp).fillMaxWidth()
+ .graphicsLayer { val s = 0.96f + 0.04f * shown.value; scaleX = s; scaleY = s; shadowElevation = 24f; shape = RoundedRectangle(22.dp); clip = true }
+ .background(Palette.bubbleAgent).clickable(remember { MutableInteractionSource() }, null) {}
+ .semantics { paneTitle = title }.padding(18.dp),
+ verticalArrangement = Arrangement.spacedBy(14.dp), horizontalAlignment = Alignment.CenterHorizontally) {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp), horizontalAlignment = Alignment.CenterHorizontally) {
+ Text(title, style = Type.headline, color = Palette.text, textAlign = TextAlign.Center)
+ if (!message.isNullOrEmpty()) Text(message, style = Type.subheadline, color = Palette.secondary, textAlign = TextAlign.Center)
+ }
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ for (action in actions()) DialogButton(action.title, action.destructive, prominent = true) { dismiss(); action.action() }
+ if (cancel != null) DialogButton(cancel, destructive = false, prominent = false) { dismiss() }
+ }
+ }
+ }
+ }
+}
+
+@Composable private fun DialogButton(title: String, destructive: Boolean, prominent: Boolean, action: () -> Unit) {
+ val (source, pressed) = rememberPress()
+ Box(Modifier.fillMaxWidth().pressScale(pressed).graphicsLayer { alpha = if (pressed) 0.85f else 1f }.clip(Capsule())
+ .background(if (destructive) Palette.danger else if (prominent) Palette.accentFill else Palette.bubbleUser)
+ .clickable(source, null, role = Role.Button, onClick = action).padding(vertical = 12.dp), contentAlignment = Alignment.Center) {
+ Text(title, style = Type.body.medium, color = if (destructive) Color.White else if (prominent) Palette.onAccent else Palette.text)
+ }
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/DrawnSymbols.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/DrawnSymbols.kt
new file mode 100644
index 00000000..0a3f2af6
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/DrawnSymbols.kt
@@ -0,0 +1,61 @@
+package com.codync.android.design
+
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.geometry.RoundRect
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.ColorFilter
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.PathOperation
+import androidx.compose.ui.graphics.drawscope.DrawScope
+import androidx.compose.ui.graphics.drawscope.scale
+import androidx.compose.ui.graphics.drawscope.translate
+import androidx.compose.ui.graphics.painter.Painter
+
+/**
+ * The tab bar's two symbols, drawn here because no icon set has their shapes: overlapping speech
+ * bubbles and a stack of cards. Original drawings in each symbol's proportions.
+ */
+internal class DrawnSymbol(private val width: Float, private val height: Float, private val shape: () -> Path) : Painter() {
+ private var tint: ColorFilter? = null
+ private val path by lazy(shape)
+
+ override val intrinsicSize = Size.Unspecified
+
+ override fun applyColorFilter(colorFilter: ColorFilter?): Boolean { tint = colorFilter; return true }
+
+ override fun DrawScope.onDraw() {
+ val unit = minOf(size.width / width, size.height / height)
+ val dx = (size.width - width * unit) / 2; val dy = (size.height - height * unit) / 2
+ translate(dx, dy) { scale(unit, unit, Offset.Zero) { drawPath(path, Color.Black, colorFilter = tint) } }
+ }
+}
+
+private fun round(left: Float, top: Float, right: Float, bottom: Float, radius: Float, bottomRadius: Float = radius) = Path().apply {
+ addRoundRect(RoundRect(Rect(left, top, right, bottom), CornerRadius(radius), CornerRadius(radius),
+ CornerRadius(bottomRadius), CornerRadius(bottomRadius)))
+}
+
+private fun tail(vararg points: Float) = Path().apply {
+ moveTo(points[0], points[1])
+ for (i in 2 until points.size step 2) lineTo(points[i], points[i + 1])
+ close()
+}
+
+private fun union(a: Path, b: Path) = Path().apply { op(a, b, PathOperation.Union) }
+
+/** `bubble.left.and.bubble.right.fill`: the right bubble in front, cut out of the left one. */
+internal val Bubbles = DrawnSymbol(34.5f, 27.5f) {
+ val back = union(round(1f, 1f, 26f, 19.8f, 6f), tail(6.6f, 18f, 6.6f, 23.9f, 7.6f, 24.4f, 12.6f, 18f))
+ val front = union(round(12.8f, 6.9f, 33.5f, 22.6f, 5.5f), tail(21.6f, 22f, 27f, 26.6f, 28.2f, 26f, 28.2f, 22f))
+ val gap = union(round(11.3f, 5.4f, 35f, 24.1f, 7f), tail(20.4f, 23f, 27f, 28.4f, 29.7f, 27f, 29.7f, 23f))
+ union(Path().apply { op(back, gap, PathOperation.Difference) }, front)
+}
+
+/** `rectangle.stack.fill`: a card with two narrower ones peeking out above it. */
+internal val CardStack = DrawnSymbol(26f, 27.4f) {
+ val stack = union(round(1f, 7.2f, 25f, 26.4f, 4.6f), round(3.7f, 3.9f, 22.3f, 5.8f, 1.7f, 0.3f))
+ union(stack, round(6f, 1f, 20f, 2.6f, 1.3f, 0.3f))
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Glass.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Glass.kt
new file mode 100644
index 00000000..bccbd71b
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Glass.kt
@@ -0,0 +1,105 @@
+package com.codync.android.design
+
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.interaction.collectIsPressedAsState
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxScope
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.staticCompositionLocalOf
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.drawscope.ContentDrawScope
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.graphics.isSpecified
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.DpOffset
+import androidx.compose.ui.unit.dp
+import com.kyant.backdrop.Backdrop
+import com.kyant.backdrop.backdrops.emptyBackdrop
+import com.kyant.backdrop.backdrops.layerBackdrop
+import com.kyant.backdrop.backdrops.rememberLayerBackdrop
+import com.kyant.backdrop.drawBackdrop
+import com.kyant.backdrop.drawPlainBackdrop
+import com.kyant.backdrop.effects.blur
+import com.kyant.backdrop.effects.lens
+import com.kyant.backdrop.effects.vibrancy
+import com.kyant.backdrop.highlight.Highlight
+import com.kyant.backdrop.shadow.Shadow
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import com.kyant.shapes.RoundedRectangularShape
+import kotlin.math.min
+
+/** What Liquid Glass above refracts: the nearest `GlassStage`'s content. */
+val LocalBackdrop = staticCompositionLocalOf<Backdrop> { emptyBackdrop() }
+
+/**
+ * Content with glass chrome floating over it (iOS 26 bars over scroll content). `content` is
+ * recorded so `chrome`'s glass can refract and blur it; chrome itself is never recorded.
+ */
+@Composable fun GlassStage(modifier: Modifier = Modifier, chrome: @Composable BoxScope.() -> Unit = {},
+ content: @Composable BoxScope.() -> Unit) {
+ val ground = Palette.background
+ val onDraw: ContentDrawScope.() -> Unit = remember(ground) { { drawRect(ground); drawContent() } }
+ val backdrop = rememberLayerBackdrop(onDraw = onDraw)
+ Box(modifier) {
+ Box(Modifier.fillMaxSize().layerBackdrop(backdrop), content = content)
+ CompositionLocalProvider(LocalBackdrop provides backdrop) { Box(Modifier.fillMaxSize(), content = chrome) }
+ }
+}
+
+/** How strongly glass frosts what's behind it. */
+enum class GlassStyle { Regular, Clear, Menu }
+
+/**
+ * iOS 26 Liquid Glass: blurred, refracted at the rim, lit along the edge, lifted by a soft shadow.
+ * `pressed` swells it the way `.glassEffect(.regular.interactive())` does.
+ */
+@Composable fun Modifier.glass(shape: RoundedRectangularShape = Capsule(), style: GlassStyle = GlassStyle.Regular,
+ tint: Color = Color.Unspecified, pressed: Boolean = false, shadow: Boolean = true): Modifier {
+ val backdrop = LocalBackdrop.current
+ val dark = LocalDark.current
+ val surface = when {
+ tint.isSpecified -> tint
+ style == GlassStyle.Clear -> if (dark) Color(0x33000000) else Color(0x33FFFFFF)
+ style == GlassStyle.Menu -> if (dark) Color(0xB8262626) else Color(0xC7FAFAFA)
+ dark -> Color(0xA8222222)
+ else -> Color(0xC2FFFFFF)
+ }
+ val blurRadius = if (style == GlassStyle.Menu) 22.dp else 4.dp
+ val swell by animateFloatAsState(if (pressed) 1.06f else 1f, Motion.layout(), label = "Glass press")
+ return graphicsLayer { scaleX = swell; scaleY = swell }.drawBackdrop(
+ backdrop = backdrop,
+ shape = { shape },
+ effects = {
+ vibrancy()
+ blur(blurRadius.toPx())
+ val rim = min(size.minDimension * 0.3f, 18.dp.toPx())
+ lens(rim, rim * 2f)
+ },
+ highlight = { Highlight(width = 0.75.dp, alpha = if (dark) 0.45f else 0.8f) },
+ shadow = if (!shadow) null else {
+ { Shadow(radius = 18.dp, offset = DpOffset(0.dp, 4.dp), color = Color.Black.copy(alpha = if (dark) 0.32f else 0.09f)) }
+ },
+ onDrawSurface = { drawRect(surface) },
+ )
+}
+
+/** A plain frosted layer over the stage (a context menu's backdrop): blur and a tint, no rim. */
+@Composable fun Modifier.frost(radius: Dp, tint: Color): Modifier {
+ val backdrop = LocalBackdrop.current
+ return drawPlainBackdrop(backdrop, shape = { RoundedRectangle(0.dp) }, effects = { blur(radius.toPx()) },
+ onDrawSurface = { drawRect(tint) })
+}
+
+/** Tracks a press for glass that swells under the finger. */
+@Composable fun rememberPress(): Pair<MutableInteractionSource, Boolean> {
+ val source = remember { MutableInteractionSource() }
+ val pressed by source.collectIsPressedAsState()
+ return source to pressed
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Menus.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Menus.kt
new file mode 100644
index 00000000..e494be1f
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Menus.kt
@@ -0,0 +1,301 @@
+package com.codync.android.design
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.core.Animatable
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.togetherWith
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.combinedClickable
+import androidx.compose.foundation.gestures.awaitEachGesture
+import androidx.compose.foundation.gestures.awaitFirstDown
+import androidx.compose.foundation.gestures.awaitLongPressOrCancellation
+import androidx.compose.foundation.gestures.drag
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.input.pointer.positionChange
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxScope
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.semantics.onLongClick
+import androidx.compose.ui.semantics.onClick
+import androidx.compose.ui.input.pointer.changedToUp
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.TransformOrigin
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.hapticfeedback.HapticFeedbackType
+import androidx.compose.ui.layout.boundsInRoot
+import androidx.compose.ui.layout.layout
+import androidx.compose.ui.layout.onGloballyPositioned
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.LocalHapticFeedback
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.semantics.selected
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.dp
+import com.kyant.shapes.RoundedRectangle
+import kotlinx.coroutines.launch
+import kotlin.math.abs
+import kotlin.math.roundToInt
+
+/** One row in a menu: an action, a choice when `selected` is set, or a submenu with `children`. */
+class MenuItem(
+ val title: String,
+ val icon: String? = null,
+ val selected: Boolean? = null,
+ val destructive: Boolean = false,
+ val divider: Boolean = false,
+ val enabled: Boolean = true,
+ val children: List<MenuItem>? = null,
+ val action: () -> Unit = {},
+)
+
+/** A row of emoji above a message's menu (Slack's quick reactions). */
+class ReactionPick(val emoji: List<String>, val chosen: List<String>, val toggle: (String) -> Unit)
+
+/** A button that opens the system-style glass menu, growing out of the button. */
+@Composable fun DropdownMenu(items: () -> List<MenuItem>, modifier: Modifier = Modifier, enabled: Boolean = true,
+ label: String? = null, content: @Composable BoxScope.() -> Unit) {
+ var anchor by remember { mutableStateOf(Rect.Zero) }
+ var open by remember { mutableStateOf(false) }
+ Box(modifier.onGloballyPositioned { anchor = it.boundsInRoot() }
+ .clickable(enabled = enabled, role = Role.Button, interactionSource = null, indication = null) { open = true }
+ .then(if (label != null) Modifier.semantics { contentDescription = label } else Modifier),
+ contentAlignment = Alignment.Center, content = content)
+ MenuOverlay(open, { open = false }, anchor, items, cover = true)
+}
+
+/** Long-press then move: the row leaves its menu and follows the finger, as iOS list rows reorder. */
+class ContextDrag(val start: () -> Unit, val move: (Float) -> Unit, val end: () -> Unit)
+
+/**
+ * Long-press opens the menu under a lifted copy of the content; `reactions` adds the emoji row.
+ * With `reorder`, moving the finger after the long press closes the menu and drags the content instead.
+ */
+@Composable fun Modifier.contextActions(reactions: ReactionPick? = null, enabled: Boolean = true, onClick: (() -> Unit)? = null,
+ preview: (@Composable () -> Unit)? = null, reorder: ContextDrag? = null, items: () -> List<MenuItem>): Modifier {
+ var anchor by remember { mutableStateOf(Rect.Zero) }
+ var open by remember { mutableStateOf(false) }
+ val haptics = LocalHapticFeedback.current
+ if (preview != null) ContextOverlay(open, { open = false }, anchor, reactions, items, preview)
+ else MenuOverlay(open, { open = false }, anchor, items, cover = false, reactions = reactions)
+ val tap by rememberUpdatedState(onClick)
+ val hold = {
+ haptics.performHapticFeedback(HapticFeedbackType.LongPress)
+ open = true
+ }
+ val gestures = if (reorder == null) Modifier.combinedClickable(enabled = enabled, onClick = { tap?.invoke() },
+ onLongClickLabel = "Actions", onLongClick = hold)
+ // One gesture for tap, hold and drag: a click detector would swallow the move after the hold.
+ else Modifier.semantics {
+ if (enabled) { onClick { tap?.invoke(); true }; onLongClick("Actions") { hold(); true } }
+ }.pointerInput(reorder, enabled) {
+ if (!enabled) return@pointerInput
+ awaitEachGesture {
+ val down = awaitFirstDown()
+ val held = awaitLongPressOrCancellation(down.id)
+ if (held == null) {
+ val up = currentEvent.changes.firstOrNull { it.id == down.id }
+ if (up != null && up.changedToUp() && !up.isConsumed) { up.consume(); tap?.invoke() }
+ return@awaitEachGesture
+ }
+ hold()
+ var moved = 0f
+ var started = false
+ drag(held.id) { change ->
+ val step = change.positionChange().y
+ moved += step
+ if (!started && abs(moved) > viewConfiguration.touchSlop) { started = true; open = false; reorder.start() }
+ if (started) { reorder.move(step); change.consume() }
+ }
+ if (started) reorder.end()
+ }
+ }
+ return onGloballyPositioned { anchor = it.boundsInRoot() }.then(gestures)
+}
+
+/** The menu panel and its placement around `anchor`. `cover`: grow over the anchor (pull-down menus). */
+@Composable private fun MenuOverlay(open: Boolean, close: () -> Unit, anchor: Rect, items: () -> List<MenuItem>, cover: Boolean,
+ reactions: ReactionPick? = null) {
+ val shown = remember { Animatable(0f) }
+ var mounted by remember { mutableStateOf(false) }
+ LaunchedEffect(open) {
+ if (open) { mounted = true; shown.animateTo(1f, Motion.layout()) }
+ else { shown.animateTo(0f, Motion.fade()); mounted = false }
+ }
+ if (!mounted) return
+ BackHandler(open, close)
+ Overlay {
+ BoxWithConstraints(Modifier.fillMaxSize()) {
+ Box(Modifier.fillMaxSize().clickable(remember { MutableInteractionSource() }, null, onClick = close))
+ val density = LocalDensity.current
+ val width = with(density) { maxWidth.toPx() }
+ val height = with(density) { maxHeight.toPx() }
+ MenuPlacement(anchor, width, height, cover, shown.value) {
+ MenuPanel(items(), close, reactions)
+ }
+ }
+ }
+}
+
+/** Puts the panel by its anchor: aligned to the anchor's side of the screen, below it (or above). */
+@Composable private fun MenuPlacement(anchor: Rect, width: Float, height: Float, cover: Boolean, shown: Float,
+ leading: Boolean = false, content: @Composable () -> Unit) {
+ val density = LocalDensity.current
+ val margin = with(density) { 12.dp.toPx() }
+ val gap = with(density) { 8.dp.toPx() }
+ var origin by remember { mutableStateOf(TransformOrigin.Center) }
+ Box(Modifier.layout { measurable, constraints ->
+ val placeable = measurable.measure(constraints.copy(minWidth = 0, minHeight = 0))
+ val third = width / 3
+ val x = when {
+ leading || anchor.center.x < third -> anchor.left
+ anchor.center.x > width - third -> anchor.right - placeable.width
+ else -> anchor.center.x - placeable.width / 2f
+ }.coerceIn(margin, (width - margin - placeable.width).coerceAtLeast(margin))
+ val below = if (cover) anchor.top else anchor.bottom + gap
+ val y = if (below + placeable.height <= height - margin) below
+ else (if (cover) anchor.bottom else anchor.top - gap) - placeable.height
+ val top = y.coerceIn(margin, (height - margin - placeable.height).coerceAtLeast(margin))
+ origin = TransformOrigin(((anchor.center.x - x) / placeable.width).coerceIn(0f, 1f),
+ if (top >= anchor.center.y) 0f else 1f)
+ layout(constraints.maxWidth, constraints.maxHeight) { placeable.place(x.roundToInt(), top.roundToInt()) }
+ }.graphicsLayer {
+ alpha = shown.coerceIn(0f, 1f)
+ val scale = 0.55f + 0.45f * shown
+ scaleX = scale; scaleY = scale
+ transformOrigin = origin
+ }) { content() }
+}
+
+private val MenuShape = RoundedRectangle(26.dp)
+
+/** The glass panel of rows. A submenu replaces the rows, with its parent as a back row. */
+@Composable private fun MenuPanel(items: List<MenuItem>, close: () -> Unit, reactions: ReactionPick?) {
+ var submenu by remember { mutableStateOf<MenuItem?>(null) }
+ Column(Modifier.width(250.dp).glass(MenuShape, GlassStyle.Menu).clip(MenuShape).padding(vertical = 10.dp)) {
+ if (reactions != null) ReactionRow(reactions, close)
+ AnimatedContent(submenu, transitionSpec = { fadeIn(Motion.fade()) togetherWith fadeOut(Motion.fade()) }, label = "Submenu") { open ->
+ Column(Modifier.heightIn(max = 520.dp).verticalScroll(rememberScrollState())) {
+ if (open != null) {
+ MenuRow(MenuItem(open.title, icon = "chevron.left"), bold = true) { submenu = null }
+ MenuDivider()
+ }
+ for ((index, item) in (open?.children ?: items).withIndex()) {
+ if (item.divider && index > 0) MenuDivider()
+ MenuRow(item) {
+ if (item.children != null) submenu = item else { close(); item.action() }
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable private fun MenuDivider() {
+ Box(Modifier.padding(horizontal = 26.dp, vertical = 8.dp).fillMaxWidth().height(1.dp).background(Palette.text.copy(alpha = 0.1f)))
+}
+
+@Composable private fun MenuRow(item: MenuItem, bold: Boolean = false, tap: () -> Unit) {
+ val ink = when {
+ !item.enabled -> Palette.text.copy(alpha = 0.3f)
+ item.destructive -> Color(0xFFFF3B30)
+ else -> Palette.text
+ }
+ val (source, pressed) = rememberPress()
+ Row(Modifier.fillMaxWidth().heightIn(min = 42.dp)
+ .padding(horizontal = 10.dp).clip(RoundedRectangle(14.dp))
+ .background(if (pressed) Palette.text.copy(alpha = 0.08f) else Color.Transparent)
+ .clickable(source, null, enabled = item.enabled, role = Role.Button, onClick = tap)
+ .semantics { if (item.selected != null) selected = item.selected }
+ .padding(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 4.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(13.dp)) {
+ val leading = when {
+ item.selected == true -> "checkmark"
+ item.selected == false -> null
+ else -> item.icon
+ }
+ Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) {
+ if (leading != null) Symbol(leading, size = 21.dp, tint = ink)
+ }
+ Text(item.title, Modifier.weight(1f), style = if (bold) Type.body.semibold else Type.body, color = ink,
+ maxLines = 2, overflow = TextOverflow.Ellipsis)
+ if (item.children != null) Symbol("chevron.right", size = 16.dp, tint = Palette.secondary)
+ }
+}
+
+@Composable private fun ReactionRow(reactions: ReactionPick, close: () -> Unit) {
+ Row(Modifier.fillMaxWidth().padding(horizontal = 14.dp).padding(bottom = 6.dp), horizontalArrangement = Arrangement.SpaceBetween) {
+ for (emoji in reactions.emoji) {
+ val chosen = emoji in reactions.chosen
+ Box(Modifier.size(38.dp).clip(RoundedRectangle(19.dp))
+ .background(if (chosen) Palette.text.copy(alpha = 0.12f) else Color.Transparent)
+ .clickable(role = Role.Button) { close(); reactions.toggle(emoji) }
+ .semantics { contentDescription = emoji; selected = chosen }, contentAlignment = Alignment.Center) {
+ Text(emoji, style = Type.title3)
+ }
+ }
+ }
+}
+
+/** The long-press menu: the app blurred and dimmed, a lifted copy of the row, the menu under it. */
+@Composable private fun ContextOverlay(open: Boolean, close: () -> Unit, anchor: Rect, reactions: ReactionPick?,
+ items: () -> List<MenuItem>, preview: @Composable () -> Unit) {
+ val shown = remember { Animatable(0f) }
+ var mounted by remember { mutableStateOf(false) }
+ LaunchedEffect(open) {
+ if (open) { mounted = true; shown.animateTo(1f, Motion.layout()) }
+ else { shown.animateTo(0f, Motion.fade()); mounted = false }
+ }
+ if (!mounted) return
+ BackHandler(open, close)
+ Overlay {
+ val density = LocalDensity.current
+ BoxWithConstraints(Modifier.fillMaxSize()) {
+ val height = with(density) { maxHeight.toPx() }
+ val width = with(density) { maxWidth.toPx() }
+ Box(Modifier.fillMaxSize().graphicsLayer { alpha = shown.value }
+ .frost(14.dp, Color.Black.copy(alpha = if (LocalDark.current) 0.3f else 0.14f))
+ .clickable(remember { MutableInteractionSource() }, null, onClick = close))
+ // The lifted row: a rounded card in place, swelling slightly.
+ Box(Modifier.offset { IntOffset(anchor.left.roundToInt(), anchor.top.roundToInt()) }
+ .size(with(density) { anchor.width.toDp() }, with(density) { anchor.height.toDp() })
+ .graphicsLayer { val s = 1f + 0.02f * shown.value; scaleX = s; scaleY = s }
+ .clip(RoundedRectangle(16.dp)).background(Palette.background)) { preview() }
+ MenuPlacement(anchor, width, height, cover = false, shown = shown.value, leading = true) { MenuPanel(items(), close, reactions) }
+ }
+ }
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Motion.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Motion.kt
new file mode 100644
index 00000000..a04cef16
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Motion.kt
@@ -0,0 +1,40 @@
+package com.codync.android.design
+
+import androidx.compose.animation.core.CubicBezierEasing
+import androidx.compose.animation.core.FiniteAnimationSpec
+import androidx.compose.animation.core.Spring
+import androidx.compose.animation.core.spring
+import androidx.compose.animation.core.tween
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.IntSize
+
+/** Grok Bot's motion, as CodyncKit `Motion` has it, so both phones feel the same. */
+object Motion {
+ private val ease = CubicBezierEasing(0.25f, 0.1f, 0.25f, 1f)
+ private val morphEase = CubicBezierEasing(0.22f, 1f, 0.36f, 1f)
+
+ /** Hover and selection fills, tabs, chips, switch knob: `.12s ease`. */
+ fun <T> hover(): FiniteAnimationSpec<T> = tween(120, easing = ease)
+ /** A view switched in: `opacity .12s`. */
+ fun <T> fade(): FiniteAnimationSpec<T> = tween(120, easing = ease)
+ /** Press feedback lands almost at once: 50 ms. */
+ fun <T> press(): FiniteAnimationSpec<T> = tween(50, easing = ease)
+ /** Icon and glyph swaps: `.2s cubic-bezier(.22,1,.36,1)`. */
+ fun <T> morph(): FiniteAnimationSpec<T> = tween(200, easing = morphEase)
+ /** Size and layout changes: SwiftUI's critically damped 0.3 s spring. */
+ fun <T> layout(): FiniteAnimationSpec<T> = spring(Spring.DampingRatioNoBouncy, stiffness = 440f)
+ /** A slightly slower spring for a new chat message and its scroll (0.42 s). */
+ fun <T> conversation(): FiniteAnimationSpec<T> = spring(Spring.DampingRatioNoBouncy, stiffness = 224f)
+ /** UIKit's push and sheet presentation: a 0.5 s critically damped spring. */
+ fun <T> present(): FiniteAnimationSpec<T> = spring(Spring.DampingRatioNoBouncy, stiffness = 158f)
+
+ /** SwiftUI's `.spring(duration:bounce:)`. */
+ fun <T> spring(duration: Float, bounce: Float = 0f): FiniteAnimationSpec<T> =
+ androidx.compose.animation.core.spring(1f - bounce, (2 * Math.PI / duration).let { (it * it).toFloat() })
+
+ val layoutOffset = spring(Spring.DampingRatioNoBouncy, stiffness = 440f, visibilityThreshold = IntOffset(1, 1))
+ val layoutSize = spring(Spring.DampingRatioNoBouncy, stiffness = 440f, visibilityThreshold = IntSize(1, 1))
+
+ /** `--ui-press-scale`. */
+ const val PRESS_SCALE = 0.98f
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Overlay.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Overlay.kt
new file mode 100644
index 00000000..ae65ba53
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Overlay.kt
@@ -0,0 +1,50 @@
+package com.codync.android.design
+
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.currentCompositionLocalContext
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.key
+import androidx.compose.runtime.mutableStateListOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.runtime.staticCompositionLocalOf
+import androidx.compose.ui.Modifier
+
+/**
+ * Sheets, menus and dialogs draw in the app's own window, above everything, so their glass can
+ * refract what's under them (a system popup window can't see the app's layers).
+ */
+class OverlayHost internal constructor() {
+ internal val entries = mutableStateListOf<Entry>()
+
+ internal class Entry(val content: @Composable () -> Unit)
+}
+
+private val LocalOverlayHost = staticCompositionLocalOf<OverlayHost?> { null }
+
+/** The app root: content, then every open overlay in the order it opened. */
+@Composable fun OverlayRoot(content: @Composable () -> Unit) {
+ val host = remember { OverlayHost() }
+ CompositionLocalProvider(LocalOverlayHost provides host) {
+ Box(Modifier.fillMaxSize()) {
+ content()
+ for (entry in host.entries) key(entry) { entry.content() }
+ }
+ }
+}
+
+/** Draws `content` on top of the app while this stays composed, keeping the caller's locals. */
+@Composable fun Overlay(content: @Composable () -> Unit) {
+ val host = requireNotNull(LocalOverlayHost.current) { "Overlay needs an OverlayRoot" }
+ val locals by rememberUpdatedState(currentCompositionLocalContext)
+ val latest by rememberUpdatedState(content)
+ val entry = remember { OverlayHost.Entry { CompositionLocalProvider(locals) { latest() } } }
+ DisposableEffect(entry) {
+ host.entries.add(entry)
+ onDispose { host.entries.remove(entry) }
+ }
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Palette.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Palette.kt
new file mode 100644
index 00000000..a55dd7ca
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Palette.kt
@@ -0,0 +1,42 @@
+package com.codync.android.design
+
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.ReadOnlyComposable
+import androidx.compose.runtime.staticCompositionLocalOf
+import androidx.compose.ui.graphics.Color
+
+/** Whether the dark half of each color pair applies; `CodyncTheme` sets it from the system. */
+val LocalDark = staticCompositionLocalOf { false }
+
+private fun hex(value: Long) = Color(0xFF000000 or value)
+
+@Composable @ReadOnlyComposable
+private fun pair(light: Long, dark: Long) = hex(if (LocalDark.current) dark else light)
+
+/**
+ * Black and white: a pure black (or white) ground, grey bubbles, and color that comes only
+ * from the bots; amber marks "needs you" and red marks errors. Mirrors CodyncKit `Palette`.
+ */
+object Palette {
+ val background: Color @Composable @ReadOnlyComposable get() = pair(0xFFFFFF, 0x0A0A0A)
+ val surface: Color @Composable @ReadOnlyComposable get() = pair(0xF4F4F4, 0x141414)
+ val bubbleAgent: Color @Composable @ReadOnlyComposable get() = pair(0xF0F0F0, 0x1C1C1C)
+ val bubbleUser: Color @Composable @ReadOnlyComposable get() = pair(0xE2E2E2, 0x363636)
+ val border: Color @Composable @ReadOnlyComposable get() = pair(0xE6E6E6, 0x262626)
+ val text: Color @Composable @ReadOnlyComposable get() = pair(0x141414, 0xF2F2F2)
+ val secondary: Color @Composable @ReadOnlyComposable get() = pair(0x6B6B6B, 0x9A9A9A)
+ val tertiary: Color @Composable @ReadOnlyComposable get() = pair(0x767676, 0x929292)
+ /** Ink used for fills (primary buttons, the send button, unread badges). */
+ val accentFill: Color @Composable @ReadOnlyComposable get() = pair(0x000000, 0xFFFFFF)
+ /** Ink readable as text and tint on the background. */
+ val accent: Color @Composable @ReadOnlyComposable get() = pair(0x000000, 0xFFFFFF)
+ val onAccent: Color @Composable @ReadOnlyComposable get() = pair(0xFFFFFF, 0x000000)
+ val accentDim: Color @Composable @ReadOnlyComposable get() = pair(0xD9D9D9, 0x333333)
+ val danger: Color @Composable @ReadOnlyComposable get() = pair(0xC23A2B, 0xF0A7A7)
+ val warning: Color get() = hex(0xF0A030)
+ /** A bot that needs you, in widgets and task cards: readable amber in both modes. */
+ val attention: Color @Composable @ReadOnlyComposable get() = pair(0x936000, 0xECAF52)
+ val codeBackground: Color @Composable @ReadOnlyComposable get() = pair(0xF4F4F4, 0x111111)
+ val added: Color @Composable @ReadOnlyComposable get() = pair(0x2E7D32, 0x8FD18B)
+ val removed: Color @Composable @ReadOnlyComposable get() = pair(0xC62828, 0xF0A7A7)
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Sheet.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Sheet.kt
new file mode 100644
index 00000000..7d5dcbe5
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Sheet.kt
@@ -0,0 +1,147 @@
+package com.codync.android.design
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.core.Animatable
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.gestures.Orientation
+import androidx.compose.foundation.gestures.draggable
+import androidx.compose.foundation.gestures.rememberDraggableState
+import androidx.compose.foundation.interaction.MutableInteractionSource
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBars
+import androidx.compose.foundation.layout.windowInsetsTopHeight
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.staticCompositionLocalOf
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
+import androidx.compose.ui.input.nestedscroll.NestedScrollSource
+import androidx.compose.ui.input.nestedscroll.nestedScroll
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.Velocity
+import androidx.compose.ui.unit.dp
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.UnevenRoundedRectangle
+import kotlinx.coroutines.launch
+import kotlin.math.roundToInt
+
+/** Closes the modal the content is in (`\.dismissModal`). */
+val LocalDismissModal = staticCompositionLocalOf<() -> Unit> { {} }
+
+/**
+ * The iOS sheet at its large detent: slides up over a dimmed app, a grabber on top, and
+ * drags down to close (also from content scrolled to its top). Content titles itself with
+ * `ModalHeader` and closes with `LocalDismissModal`.
+ */
+@Composable fun CodyncSheet(isPresented: Boolean, onDismiss: () -> Unit, content: @Composable () -> Unit) {
+ val shown = remember { Animatable(0f) }
+ var mounted by remember { mutableStateOf(isPresented) }
+ LaunchedEffect(isPresented) {
+ if (isPresented) {
+ mounted = true
+ shown.animateTo(1f, Motion.present())
+ } else {
+ shown.animateTo(0f, Motion.present())
+ mounted = false
+ }
+ }
+ if (!mounted) return
+ val dismiss by rememberUpdatedState(onDismiss)
+ BackHandler(isPresented) { dismiss() }
+ Overlay { SheetFrame(shown.value, { dismiss() }, content) }
+}
+
+/** `.codyncSheet(item:)`: keeps showing the last item while the sheet slides away. */
+@Composable fun <T : Any> CodyncSheet(item: T?, onDismiss: () -> Unit, content: @Composable (T) -> Unit) {
+ var last by remember { mutableStateOf(item) }
+ if (item != null) last = item
+ CodyncSheet(item != null, onDismiss) { last?.let { content(it) } }
+}
+
+@Composable private fun SheetFrame(shown: Float, dismiss: () -> Unit, content: @Composable () -> Unit) {
+ val dark = LocalDark.current
+ val scope = rememberCoroutineScope()
+ val drag = remember { Animatable(0f) }
+ BoxWithConstraints(Modifier.fillMaxSize()) {
+ val height = with(LocalDensity.current) { maxHeight.toPx() }
+ val closeAt = height * 0.25f
+ fun release(velocity: Float) {
+ scope.launch {
+ if (drag.value > closeAt || velocity > 1600f) dismiss() else drag.animateTo(0f, Motion.layout())
+ }
+ }
+ val pull = remember {
+ object : NestedScrollConnection {
+ override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
+ if (drag.value <= 0f || available.y >= 0f) return Offset.Zero
+ val used = maxOf(available.y, -drag.value)
+ scope.launch { drag.snapTo(drag.value + used) }
+ return Offset(0f, used)
+ }
+
+ override fun onPostScroll(consumed: Offset, available: Offset, source: NestedScrollSource): Offset {
+ if (available.y <= 0f || source != NestedScrollSource.UserInput) return Offset.Zero
+ scope.launch { drag.snapTo(drag.value + available.y) }
+ return Offset(0f, available.y)
+ }
+
+ override suspend fun onPreFling(available: Velocity): Velocity {
+ if (drag.value <= 0f) return Velocity.Zero
+ release(available.y)
+ return available
+ }
+ }
+ }
+ // The dimmed app behind; a tap outside closes, like the system sheet's.
+ Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = (if (dark) 0.48f else 0.2f) * shown))
+ .clickable(remember { MutableInteractionSource() }, null, onClick = dismiss))
+ val offset = (1f - shown) * height + drag.value
+ Column(Modifier.fillMaxSize()) {
+ Spacer(Modifier.windowInsetsTopHeight(WindowInsets.statusBars))
+ Spacer(Modifier.height(10.dp))
+ Box(Modifier.fillMaxSize()
+ .offset { IntOffset(0, offset.roundToInt()) }
+ .graphicsLayer { shadowElevation = if (dark) 0f else 24f; shape = SheetShape; clip = true }
+ .background(Palette.background)
+ .clickable(remember { MutableInteractionSource() }, null) {}
+ .draggable(rememberDraggableState { delta -> scope.launch { drag.snapTo((drag.value + delta).coerceAtLeast(0f)) } },
+ Orientation.Vertical, onDragStopped = { velocity -> release(velocity) })
+ .nestedScroll(pull)) {
+ CompositionLocalProvider(LocalDismissModal provides dismiss) {
+ GlassStage(Modifier.fillMaxSize().navigationBarsPadding().imePadding()) { content() }
+ }
+ Box(Modifier.fillMaxWidth().padding(top = 5.dp), contentAlignment = Alignment.TopCenter) {
+ Box(Modifier.size(36.dp, 5.dp).clip(Capsule()).background(if (dark) Color(0xFF5A5A5A) else Color(0xFFC6C6C6)))
+ }
+ }
+ }
+ }
+}
+
+private val SheetShape = UnevenRoundedRectangle(topStart = 40.dp, topEnd = 40.dp)
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Symbol.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Symbol.kt
new file mode 100644
index 00000000..5742067c
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Symbol.kt
@@ -0,0 +1,33 @@
+package com.codync.android.design
+
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.layout.size
+import androidx.compose.material3.LocalContentColor
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.ColorFilter
+import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.semantics.clearAndSetSemantics
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+
+/**
+ * `Image(systemName:)`: the stand-in for an SF Symbol, tinted with the content color.
+ * `size` is the glyph's box; a symbol set at font size F looks right at about F × 1.2.
+ */
+@Composable fun Symbol(name: String, modifier: Modifier = Modifier, size: Dp = 20.dp, tint: Color = LocalContentColor.current,
+ contentDescription: String? = null, height: Dp = size) {
+ val painter = when (name) {
+ "bubble.left.and.bubble.right.fill" -> Bubbles
+ "rectangle.stack.fill" -> CardStack
+ "apple.logo" -> painterResource(R.drawable.apple_logo)
+ "computer.linux" -> painterResource(R.drawable.computer_linux)
+ else -> painterResource(symbolRes(name) ?: R.drawable.sf_circle_dotted)
+ }
+ val described = if (contentDescription == null) modifier.clearAndSetSemantics {}
+ else modifier.semantics { this.contentDescription = contentDescription }
+ Image(painter, null, described.size(size, height), colorFilter = ColorFilter.tint(tint))
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt
new file mode 100644
index 00000000..174d1151
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt
@@ -0,0 +1,170 @@
+// Generated by tools/symbols.py: the Material Symbols standing in for SF Symbol names.
+package com.codync.android.design
+
+import androidx.annotation.DrawableRes
+
+/** The drawable for an SF Symbol name the iOS app uses, or null when Android has none. */
+@DrawableRes fun symbolRes(name: String): Int? = when (name) {
+ "app" -> R.drawable.sf_app
+ "arrow.clockwise" -> R.drawable.sf_arrow_clockwise
+ "arrow.counterclockwise" -> R.drawable.sf_arrow_counterclockwise
+ "arrow.down" -> R.drawable.sf_arrow_down
+ "arrow.down.circle" -> R.drawable.sf_arrow_down_circle
+ "arrow.down.circle.fill" -> R.drawable.sf_arrow_down_circle_fill
+ "arrow.down.doc.on.clipboard" -> R.drawable.sf_arrow_down_doc_on_clipboard
+ "arrow.down.right.and.arrow.up.left" -> R.drawable.sf_arrow_down_right_and_arrow_up_left
+ "arrow.down.to.line" -> R.drawable.sf_arrow_down_to_line
+ "arrow.left" -> R.drawable.sf_arrow_left
+ "arrow.left.arrow.right" -> R.drawable.sf_arrow_left_arrow_right
+ "arrow.right" -> R.drawable.sf_arrow_right
+ "arrow.right.doc.on.clipboard" -> R.drawable.sf_arrow_right_doc_on_clipboard
+ "arrow.right.to.line" -> R.drawable.sf_arrow_right_to_line
+ "arrow.triangle.2.circlepath" -> R.drawable.sf_arrow_triangle_2_circlepath
+ "arrow.triangle.branch" -> R.drawable.sf_arrow_triangle_branch
+ "arrow.up" -> R.drawable.sf_arrow_up
+ "arrow.up.doc.on.clipboard" -> R.drawable.sf_arrow_up_doc_on_clipboard
+ "arrow.up.right" -> R.drawable.sf_arrow_up_right
+ "arrowshape.turn.up.left" -> R.drawable.sf_arrowshape_turn_up_left
+ "battery.100percent" -> R.drawable.sf_battery_100percent
+ "battery.75percent" -> R.drawable.sf_battery_75percent
+ "bell" -> R.drawable.sf_bell
+ "bolt" -> R.drawable.sf_bolt
+ "book.fill" -> R.drawable.sf_book_fill
+ "book.pages" -> R.drawable.sf_book_pages
+ "brain" -> R.drawable.sf_brain
+ "bubble.left.and.bubble.right" -> R.drawable.sf_bubble_left_and_bubble_right
+ "bubble.left.and.bubble.right.fill" -> R.drawable.sf_bubble_left_and_bubble_right_fill
+ "calendar" -> R.drawable.sf_calendar
+ "camera.fill" -> R.drawable.sf_camera_fill
+ "chart.bar" -> R.drawable.sf_chart_bar
+ "checklist" -> R.drawable.sf_checklist
+ "checkmark" -> R.drawable.sf_checkmark
+ "checkmark.circle" -> R.drawable.sf_checkmark_circle
+ "checkmark.circle.fill" -> R.drawable.sf_checkmark_circle_fill
+ "checkmark.message" -> R.drawable.sf_checkmark_message
+ "checkmark.seal" -> R.drawable.sf_checkmark_seal
+ "chevron.down" -> R.drawable.sf_chevron_down
+ "chevron.left" -> R.drawable.sf_chevron_left
+ "chevron.right" -> R.drawable.sf_chevron_right
+ "chevron.up" -> R.drawable.sf_chevron_up
+ "circle" -> R.drawable.sf_circle
+ "circle.dotted" -> R.drawable.sf_circle_dotted
+ "clock" -> R.drawable.sf_clock
+ "clock.arrow.circlepath" -> R.drawable.sf_clock_arrow_circlepath
+ "clock.fill" -> R.drawable.sf_clock_fill
+ "cloud" -> R.drawable.sf_cloud
+ "cloud.sun.fill" -> R.drawable.sf_cloud_sun_fill
+ "command" -> R.drawable.sf_command
+ "control" -> R.drawable.sf_control
+ "crop" -> R.drawable.sf_crop
+ "cursorarrow.motionlines" -> R.drawable.sf_cursorarrow_motionlines
+ "desktopcomputer" -> R.drawable.sf_desktopcomputer
+ "desktopcomputer.trianglebadge.exclamationmark" -> R.drawable.sf_desktopcomputer_trianglebadge_exclamationmark
+ "display" -> R.drawable.sf_display
+ "display.2" -> R.drawable.sf_display_2
+ "doc" -> R.drawable.sf_doc
+ "doc.badge.plus" -> R.drawable.sf_doc_badge_plus
+ "doc.on.clipboard" -> R.drawable.sf_doc_on_clipboard
+ "doc.on.clipboard.fill" -> R.drawable.sf_doc_on_clipboard_fill
+ "doc.on.doc" -> R.drawable.sf_doc_on_doc
+ "doc.richtext" -> R.drawable.sf_doc_richtext
+ "doc.text" -> R.drawable.sf_doc_text
+ "doc.zipper" -> R.drawable.sf_doc_zipper
+ "ellipsis" -> R.drawable.sf_ellipsis
+ "envelope.fill" -> R.drawable.sf_envelope_fill
+ "escape" -> R.drawable.sf_escape
+ "exclamationmark" -> R.drawable.sf_exclamationmark
+ "exclamationmark.circle" -> R.drawable.sf_exclamationmark_circle
+ "exclamationmark.circle.fill" -> R.drawable.sf_exclamationmark_circle_fill
+ "exclamationmark.triangle" -> R.drawable.sf_exclamationmark_triangle
+ "exclamationmark.triangle.fill" -> R.drawable.sf_exclamationmark_triangle_fill
+ "eye" -> R.drawable.sf_eye
+ "eye.slash" -> R.drawable.sf_eye_slash
+ "figure.run" -> R.drawable.sf_figure_run
+ "folder" -> R.drawable.sf_folder
+ "function" -> R.drawable.sf_function
+ "gearshape" -> R.drawable.sf_gearshape
+ "gearshape.fill" -> R.drawable.sf_gearshape_fill
+ "globe" -> R.drawable.sf_globe
+ "hand.point.up.left" -> R.drawable.sf_hand_point_up_left
+ "hand.raised" -> R.drawable.sf_hand_raised
+ "hand.raised.fill" -> R.drawable.sf_hand_raised_fill
+ "hand.raised.slash" -> R.drawable.sf_hand_raised_slash
+ "heart.fill" -> R.drawable.sf_heart_fill
+ "info.circle" -> R.drawable.sf_info_circle
+ "italic" -> R.drawable.sf_italic
+ "key" -> R.drawable.sf_key
+ "key.fill" -> R.drawable.sf_key_fill
+ "keyboard" -> R.drawable.sf_keyboard
+ "keyboard.chevron.compact.down" -> R.drawable.sf_keyboard_chevron_compact_down
+ "laptopcomputer" -> R.drawable.sf_laptopcomputer
+ "list.bullet" -> R.drawable.sf_list_bullet
+ "list.bullet.rectangle" -> R.drawable.sf_list_bullet_rectangle
+ "lock.display" -> R.drawable.sf_lock_display
+ "lock.fill" -> R.drawable.sf_lock_fill
+ "lock.rectangle" -> R.drawable.sf_lock_rectangle
+ "lock.shield" -> R.drawable.sf_lock_shield
+ "lock.slash" -> R.drawable.sf_lock_slash
+ "magnifyingglass" -> R.drawable.sf_magnifyingglass
+ "map.fill" -> R.drawable.sf_map_fill
+ "mic" -> R.drawable.sf_mic
+ "mic.fill" -> R.drawable.sf_mic_fill
+ "mic.slash" -> R.drawable.sf_mic_slash
+ "move" -> R.drawable.sf_move
+ "music.note" -> R.drawable.sf_music_note
+ "network" -> R.drawable.sf_network
+ "note.text" -> R.drawable.sf_note_text
+ "option" -> R.drawable.sf_option
+ "paintbrush" -> R.drawable.sf_paintbrush
+ "paintpalette" -> R.drawable.sf_paintpalette
+ "pause.fill" -> R.drawable.sf_pause_fill
+ "pencil" -> R.drawable.sf_pencil
+ "person.2" -> R.drawable.sf_person_2
+ "person.crop.circle" -> R.drawable.sf_person_crop_circle
+ "person.crop.circle.badge.checkmark" -> R.drawable.sf_person_crop_circle_badge_checkmark
+ "person.fill" -> R.drawable.sf_person_fill
+ "phone.fill" -> R.drawable.sf_phone_fill
+ "photo" -> R.drawable.sf_photo
+ "photo.fill" -> R.drawable.sf_photo_fill
+ "photo.on.rectangle" -> R.drawable.sf_photo_on_rectangle
+ "pin" -> R.drawable.sf_pin
+ "pin.fill" -> R.drawable.sf_pin_fill
+ "pin.slash" -> R.drawable.sf_pin_slash
+ "play.circle" -> R.drawable.sf_play_circle
+ "play.circle.fill" -> R.drawable.sf_play_circle_fill
+ "play.fill" -> R.drawable.sf_play_fill
+ "plus" -> R.drawable.sf_plus
+ "plus.circle" -> R.drawable.sf_plus_circle
+ "plus.rectangle.on.rectangle" -> R.drawable.sf_plus_rectangle_on_rectangle
+ "point.3.connected.trianglepath.dotted" -> R.drawable.sf_point_3_connected_trianglepath_dotted
+ "power" -> R.drawable.sf_power
+ "qrcode" -> R.drawable.sf_qrcode
+ "qrcode.viewfinder" -> R.drawable.sf_qrcode_viewfinder
+ "rectangle.and.hand.point.up.left" -> R.drawable.sf_rectangle_and_hand_point_up_left
+ "rectangle.portrait.and.arrow.right" -> R.drawable.sf_rectangle_portrait_and_arrow_right
+ "rectangle.stack.fill" -> R.drawable.sf_rectangle_stack_fill
+ "return" -> R.drawable.sf_return
+ "rotate.right" -> R.drawable.sf_rotate_right
+ "safari" -> R.drawable.sf_safari
+ "shippingbox" -> R.drawable.sf_shippingbox
+ "square.and.arrow.down" -> R.drawable.sf_square_and_arrow_down
+ "square.and.arrow.up" -> R.drawable.sf_square_and_arrow_up
+ "square.and.pencil" -> R.drawable.sf_square_and_pencil
+ "square.grid.2x2" -> R.drawable.sf_square_grid_2x2
+ "square.grid.3x3" -> R.drawable.sf_square_grid_3x3
+ "square.on.square" -> R.drawable.sf_square_on_square
+ "stop.fill" -> R.drawable.sf_stop_fill
+ "tab" -> R.drawable.sf_tab
+ "terminal" -> R.drawable.sf_terminal
+ "text.bubble" -> R.drawable.sf_text_bubble
+ "trash" -> R.drawable.sf_trash
+ "waveform" -> R.drawable.sf_waveform
+ "wifi" -> R.drawable.sf_wifi
+ "wifi.exclamationmark" -> R.drawable.sf_wifi_exclamationmark
+ "wifi.slash" -> R.drawable.sf_wifi_slash
+ "wrench.and.screwdriver" -> R.drawable.sf_wrench_and_screwdriver
+ "xmark" -> R.drawable.sf_xmark
+ "xmark.circle" -> R.drawable.sf_xmark_circle
+ "xmark.circle.fill" -> R.drawable.sf_xmark_circle_fill
+ else -> null
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/ThinkingOrb.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/ThinkingOrb.kt
new file mode 100644
index 00000000..475e498b
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/ThinkingOrb.kt
@@ -0,0 +1,58 @@
+package com.codync.android.design
+
+import androidx.compose.foundation.Canvas
+import androidx.compose.foundation.layout.size
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableDoubleStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.runtime.withFrameNanos
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.semantics.clearAndSetSemantics
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.compose.LocalLifecycleOwner
+import androidx.lifecycle.repeatOnLifecycle
+
+enum class ThinkingOrbState { Working, Searching, Listening, Connecting, Shaping }
+
+/** thinking-orbs' states with their tuned dot geometry and depth shading; decorative only. */
+@Composable fun ThinkingOrb(state: ThinkingOrbState = ThinkingOrbState.Working, size: Dp = 16.dp, color: Color = Palette.text,
+ animated: Boolean = true, modifier: Modifier = Modifier) {
+ val points = with(LocalDensity.current) { size.toPx() }.toDouble()
+ var time by remember { mutableDoubleStateOf(0.6) }
+ val lifecycle = LocalLifecycleOwner.current.lifecycle
+ if (animated && !reduceMotion()) LaunchedEffect(state, points) {
+ val speed = ThinkingOrbGeometry.speed(state, size.value.toDouble())
+ lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
+ val start = withFrameNanos { it }
+ var last = 0L
+ while (true) withFrameNanos { now ->
+ // 30 fps, like the iOS TimelineView.
+ if (now - last >= 33_000_000L) { last = now; time = 0.6 + (now - start) / 1e9 * speed }
+ }
+ }
+ }
+ val scale = points / size.value
+ Canvas(modifier.size(size).clearAndSetSemantics {}) {
+ val frame = ThinkingOrbGeometry.frame(state, size.value.toDouble(), time)
+ fun ink(white: Double, alpha: Double) = ((1 - white.coerceIn(0.0, 1.0)) * alpha).toFloat()
+ for (line in frame.lines) drawLine(color.copy(alpha = color.alpha * ink(line.white, line.alpha)),
+ Offset((line.x1 * scale).toFloat(), (line.y1 * scale).toFloat()), Offset((line.x2 * scale).toFloat(), (line.y2 * scale).toFloat()),
+ (line.width * scale).toFloat())
+ for (dot in frame.dots) drawCircle(color.copy(alpha = color.alpha * ink(dot.white, dot.alpha)), (dot.radius * scale).toFloat(),
+ Offset((dot.x * scale).toFloat(), (dot.y * scale).toFloat()))
+ }
+}
+
+/** The system's "Remove animations" setting, iOS Reduce Motion's counterpart. */
+@Composable fun reduceMotion(): Boolean {
+ val context = androidx.compose.ui.platform.LocalContext.current
+ return remember { android.provider.Settings.Global.getFloat(context.contentResolver, android.provider.Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0f }
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/ThinkingOrbGeometry.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/ThinkingOrbGeometry.kt
new file mode 100644
index 00000000..d0f0033e
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/ThinkingOrbGeometry.kt
@@ -0,0 +1,239 @@
+package com.codync.android.design
+
+import kotlin.math.PI
+import kotlin.math.abs
+import kotlin.math.acos
+import kotlin.math.atan2
+import kotlin.math.cos
+import kotlin.math.exp
+import kotlin.math.floor
+import kotlin.math.hypot
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.pow
+import kotlin.math.roundToInt
+import kotlin.math.sin
+import kotlin.math.sqrt
+
+// Native port of thinking-orbs 0.3.1, commit de85557 (MIT, Jakub Antalik), line for line with
+// CodyncKit `ThinkingOrbGeometry.swift`. See assets/licenses/thinking-orbs-LICENSE.txt.
+internal object ThinkingOrbGeometry {
+ data class Dot(val x: Double, val y: Double, val z: Double, val radius: Double, val white: Double, val alpha: Double = 1.0)
+ data class Line(val x1: Double, val y1: Double, val x2: Double, val y2: Double, val white: Double, val alpha: Double, val width: Double)
+ class Frame(val dots: MutableList<Dot> = mutableListOf(), val lines: MutableList<Line> = mutableListOf())
+
+ private data class P(val x: Double, val y: Double, val z: Double) {
+ operator fun plus(o: P) = P(x + o.x, y + o.y, z + o.z)
+ operator fun minus(o: P) = P(x - o.x, y - o.y, z - o.z)
+ operator fun times(s: Double) = P(x * s, y * s, z * s)
+ operator fun div(s: Double) = P(x / s, y / s, z / s)
+ val length get() = sqrt(x * x + y * y + z * z)
+ }
+
+ private data class P2(val x: Double, val y: Double) {
+ operator fun plus(o: P2) = P2(x + o.x, y + o.y)
+ operator fun minus(o: P2) = P2(x - o.x, y - o.y)
+ operator fun times(s: Double) = P2(x * s, y * s)
+ }
+
+ fun speed(state: ThinkingOrbState, size: Double): Double {
+ val small = size < 40
+ return when (state) {
+ ThinkingOrbState.Working -> if (small) 3.9 else 1.885
+ ThinkingOrbState.Searching -> if (small) 2.665 else 2.015
+ ThinkingOrbState.Listening -> if (small) 3.998 else 4.388
+ ThinkingOrbState.Connecting -> if (small) 6.63 else 3.315
+ ThinkingOrbState.Shaping -> if (small) 2.08 else 2.405
+ }
+ }
+
+ /** `time` is the engine time, already multiplied by the preset speed. */
+ fun frame(state: ThinkingOrbState, size: Double, time: Double): Frame {
+ if (!size.isFinite() || size <= 0 || !time.isFinite()) return Frame()
+ val frame = when (state) {
+ ThinkingOrbState.Working -> orbits(size, time)
+ ThinkingOrbState.Searching -> lattice(size, time, listening = false)
+ ThinkingOrbState.Listening -> lattice(size, time, listening = true)
+ ThinkingOrbState.Connecting -> web(size, time)
+ ThinkingOrbState.Shaping -> morph(size, time)
+ }
+ val dots = frame.dots.filter { it.alpha >= 0.02 }.map { it.copy(radius = max(0.3, it.radius)) }.sortedBy { it.z }
+ return Frame(dots.toMutableList(), frame.lines.filter { it.alpha >= 0.02 }.toMutableList())
+ }
+
+ private fun projector(yaw: Double, tilt: Double, size: Double, scale: Double): (P) -> P {
+ val sy = sin(yaw); val cy = cos(yaw); val st = sin(tilt); val ct = cos(tilt)
+ return { p ->
+ val x = p.x * cy + p.z * sy; val z = -p.x * sy + p.z * cy
+ P(size / 2 + x * scale, size / 2 - (p.y * ct - z * st) * scale, p.y * st + z * ct)
+ }
+ }
+
+ private fun hash(a: Double, b: Double): Double {
+ val h = sin(a * 12.9898 + b * 78.233) * 43758.5453
+ return h - floor(h)
+ }
+
+ private fun noise(x: Double, y: Double): Double {
+ val xi = floor(x); val yi = floor(y)
+ val dx = x - xi; val dy = y - yi
+ val fx = dx * dx * (3 - 2 * dx); val fy = dy * dy * (3 - 2 * dy)
+ val a = hash(xi, yi); val b = hash(xi + 1, yi); val c = hash(xi, yi + 1); val d = hash(xi + 1, yi + 1)
+ return a + (b - a) * fx + (c - a) * fy + (a - b - c + d) * fx * fy
+ }
+
+ private fun orbits(size: Double, t: Double): Frame {
+ val small = size < 40; val radius = size / 2 * 0.82
+ val project = projector(t * 0.12, 0.3, size, 1.0)
+ val rs = (size / 300).pow(0.6); val multiplier = if (small) 2.4 else 1.0
+ val orbitCount = if (small) 3 else 12; val ghostCount = if (small) 10 else 40
+ val frame = Frame()
+ for (orb in 0 until orbitCount) {
+ val h1 = hash(orb.toDouble(), 1.7); val h2 = hash(orb.toDouble(), 5.2); val h3 = hash(orb.toDouble(), 8.9)
+ val ro = radius * (0.45 + 0.52 * h1); val theta = h1 * 2 * PI; val phi = acos(2 * h2 - 1)
+ val normal = P(sin(phi) * cos(theta), cos(phi), sin(phi) * sin(theta))
+ var u = P(-normal.y, normal.x, 0.0)
+ u /= max(1e-6, u.length)
+ val v = P(-normal.z * u.y, normal.z * u.x, normal.x * u.y - normal.y * u.x)
+ val speed = (0.25 + 0.55 * h3) * (if (h3 > 0.5) 1.0 else -1.0)
+ for (k in 0 until ghostCount) {
+ val angle = k.toDouble() / ghostCount * 2 * PI
+ val p = project((u * cos(angle) + v * sin(angle)) * ro)
+ val depth = (p.z / ro + 1) / 2
+ frame.dots += Dot(p.x, p.y, p.z, 0.9 * multiplier * rs, 0.72, 0.5 * (0.4 + 0.6 * depth))
+ }
+ for (m in 0 until 3) {
+ val angle = t * speed + m / 3.0 * 2 * PI + h2 * 6
+ val p = project((u * cos(angle) + v * sin(angle)) * ro)
+ val depth = (p.z / ro + 1) / 2
+ frame.dots += Dot(p.x, p.y, p.z, (1.2 + 1.6 * depth) * multiplier * rs, 0.3 - 0.22 * depth)
+ }
+ }
+ return frame
+ }
+
+ private fun lattice(size: Double, t: Double, listening: Boolean): Frame {
+ val small = size < 40; val rs = (size / 300).pow(0.6)
+ val rings = if (listening) (if (small) 5 else 9) else (if (small) 6 else 11)
+ val density = if (listening) (if (small) 13 else 23) else (if (small) 14 else 29)
+ val multiplier = if (listening) (if (small) 1.6 else 1.0) else (if (small) 1.75 else 1.15)
+ val radius = size / 2 * (if (listening) 0.874 else 0.82)
+ val tilt = if (listening) 0.38 else 0.4 + 0.06 * sin(t * 0.35)
+ val project = projector(t * (if (listening) 0.18 else 0.5), tilt, size, if (listening) 1.0 else radius)
+ val scan = t * (0.5 + 1.2 * (if (small) 4.335 else 4.08))
+ val frame = Frame()
+ for (ri in 0..rings) {
+ val lat = -PI / 2 + ri.toDouble() / rings * PI
+ val cosLat = cos(lat); val sinLat = sin(lat)
+ val wave = 0.62 * sin(t * 2.1 - ri * 0.52) + 0.38 * sin(t * 1.27 + ri * 0.83)
+ val rr = if (listening) radius * (0.88 + 0.105 * wave) else 1.0
+ val lonCount = max(1, (abs(cosLat) * density).roundToInt())
+ for (j in 0 until lonCount) {
+ val lon = j.toDouble() / lonCount * 2 * PI
+ val p = project(P(cosLat * cos(lon), sinLat, cosLat * sin(lon)) * rr)
+ val depth = (p.z / (if (listening) radius else 1.0) + 1) / 2
+ if (listening) {
+ val crest = max(0.0, wave)
+ frame.dots += Dot(p.x, p.y, p.z, (0.6 + 1.7 * depth) * multiplier * (1 + 0.4 * crest) * rs,
+ 0.66 - 0.56 * depth - 0.1 * crest)
+ } else {
+ val angle = lon + t * 0.5 - scan
+ val delta = atan2(sin(angle), cos(angle))
+ val boost = exp(-(delta * delta) / 0.18) * max(0.0, p.z)
+ frame.dots += Dot(p.x, p.y, p.z, ((0.6 + 1.7 * depth) * multiplier + boost) * rs,
+ 0.62 - 0.54 * depth, 0.45 + 0.55 * min(1.0, boost))
+ }
+ }
+ }
+ return frame
+ }
+
+ private fun web(size: Double, t: Double): Frame {
+ val small = size < 40; val rs = (size / 300).pow(0.6)
+ val count = if (small) 8 else 41; val signals = if (small) 1 else 7
+ val multiplier = if (small) 1.52 else 0.95; val threshold = 0.72
+ val project = projector(t * 0.12, 0.32, size, size / 2 * 0.8)
+ val golden = PI * (3 - sqrt(5.0))
+ val nodes = (0 until count).map { index ->
+ val i = index.toDouble(); val y = 1 - 2 * (i + 0.5) / count
+ val r = sqrt(1 - y * y); val a = i * golden
+ val p = P(r * cos(a) + 0.3 * (noise(i * 0.31 + 9, t * 0.24) - 0.5) * 2,
+ y + 0.3 * (noise(i * 0.53 + 27, t * 0.21) - 0.5) * 2,
+ r * sin(a) + 0.3 * (noise(i * 0.77 + 55, t * 0.27) - 0.5) * 2)
+ p / p.length
+ }
+ val frame = Frame()
+ for (i in 0 until count) {
+ for (j in i + 1 until count) {
+ val distance = (nodes[i] - nodes[j]).length
+ if (distance >= threshold) continue
+ val a = project(nodes[i]); val b = project(nodes[j]); val depth = ((a.z + b.z) / 2 + 1) / 2
+ frame.lines += Line(a.x, a.y, b.x, b.y, 0.42, (1 - distance / threshold) * (0.3 + 0.55 * depth), max(0.6, 0.8 * rs))
+ }
+ val p = project(nodes[i]); val depth = (p.z + 1) / 2
+ val pulse = 1 + 0.25 * sin(t * 1.4 + i * 2.7)
+ frame.dots += Dot(p.x, p.y, p.z, (1.4 + 1.8 * depth) * multiplier * pulse * rs, 0.55 - 0.45 * depth)
+ }
+ for (s in 0 until signals) {
+ val segment = floor(t * 0.55 + s * 7.31)
+ val a = floor(hash(segment, s * 3.1 + 1.7) * count).toInt()
+ val b = floor(hash(segment, s * 5.7 + 4.2) * count).toInt()
+ if (a == b) continue
+ val tick = t * 0.55 + s * 7.31; val fraction = tick - floor(tick)
+ val node = nodes[a] + (nodes[b] - nodes[a]) * fraction
+ val p = project(node / max(1e-6, node.length)); val depth = (p.z + 1) / 2
+ frame.dots += Dot(p.x, p.y, p.z, (1.4 * 1.5 + 1.8 * depth) * multiplier * rs, 0.05, 0.5 + 0.5 * depth)
+ }
+ return frame
+ }
+
+ /** A dotted outline that holds a circle, triangle and square in turn, morphing between them. */
+ private fun morph(size: Double, t: Double): Frame {
+ val small = size < 40; val spread = 1.45; val hold = 1.4; val change = 0.9; val segment = hold + change
+ val cycle = t % (segment * shapes.size)
+ val k = min(shapes.size - 1, (cycle / segment).toInt()); val local = cycle - k * segment
+ val x = (local - hold) / change; val m = if (local > hold) x * x * (3 - 2 * x) else 0.0
+ val from = shapes[k]; val to = shapes[(k + 1) % shapes.size]
+ val samples = 160
+ val points = (0 until samples).map { i ->
+ val f = i.toDouble() / samples; val a = from(f); val b = to(f)
+ (a + (b - a) * m) * spread
+ }
+ val lengths = (0 until samples).map { i -> hypot(points[(i + 1) % samples].x - points[i].x, points[(i + 1) % samples].y - points[i].y) }
+ val total = lengths.sum()
+ val count = if (small) 18 else 24
+ val radius = max(0.35, (if (small) 0.021231 else 0.008295) * 1.35 * spread * size)
+ val pulse = 1 + 0.02 * sin(local * 3.1)
+ val frame = Frame()
+ var i = 0; var walked = 0.0
+ for (n in 0 until count) {
+ val target = n.toDouble() / count * total
+ while (walked + lengths[i] < target && i < samples - 1) { walked += lengths[i]; i += 1 }
+ val a = points[i]; val b = points[(i + 1) % samples]
+ val f = if (lengths[i] > 0) min(1.0, (target - walked) / lengths[i]) else 0.0
+ val p = (a + (b - a) * f) * pulse
+ frame.dots += Dot(size / 2 + p.x * size, size / 2 + p.y * size, 0.0, radius, 0.1)
+ }
+ return frame
+ }
+
+ private val shapes: List<(Double) -> P2> = listOf(
+ { f -> P2(cos(-PI / 2 + f * 2 * PI), sin(-PI / 2 + f * 2 * PI)) * 0.24 },
+ polygon(listOf(P2(0.0, -0.26), P2(0.24, 0.16), P2(-0.24, 0.16))),
+ polygon(listOf(P2(0.0, -0.2), P2(0.2, -0.2), P2(0.2, 0.2), P2(-0.2, 0.2), P2(-0.2, -0.2))),
+ )
+
+ /** The closed outline through `vertices`, parameterized by arc length (0...1). */
+ private fun polygon(vertices: List<P2>): (Double) -> P2 {
+ val lengths = vertices.indices.map { i ->
+ hypot(vertices[(i + 1) % vertices.size].x - vertices[i].x, vertices[(i + 1) % vertices.size].y - vertices[i].y)
+ }
+ val total = lengths.sum()
+ return { f ->
+ var target = f * total; var i = 0
+ while (target > lengths[i] && i < vertices.size - 1) { target -= lengths[i]; i += 1 }
+ val a = vertices[i]; val b = vertices[(i + 1) % vertices.size]
+ a + (b - a) * (if (lengths[i] > 0) min(1.0, target / lengths[i]) else 0.0)
+ }
+ }
+}
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Type.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Type.kt
new file mode 100644
index 00000000..9123c36b
--- /dev/null
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Type.kt
@@ -0,0 +1,61 @@
+package com.codync.android.design
+
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.Font
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontVariation
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.LineHeightStyle
+import androidx.compose.ui.unit.TextUnit
+import androidx.compose.ui.unit.em
+import androidx.compose.ui.unit.sp
+import kotlin.math.exp
+
+/**
+ * The iOS text styles at the default Dynamic Type size, set in Inter (SF Pro is Apple-only).
+ * Sizes are `sp`, so Android's font scale grows them like Dynamic Type.
+ */
+object Type {
+ val largeTitle = style(34f, 41f)
+ val title = style(28f, 34f)
+ val title2 = style(22f, 28f)
+ val title3 = style(20f, 25f)
+ val headline = style(17f, 22f, FontWeight.SemiBold)
+ val body = style(17f, 22f)
+ val callout = style(16f, 21f)
+ val subheadline = style(15f, 20f)
+ val footnote = style(13f, 18f)
+ val caption = style(12f, 16f)
+ val caption2 = style(11f, 13f)
+
+ /** `Font.system(size:weight:)`. */
+ fun system(size: Float, weight: FontWeight = FontWeight.Normal) = style(size, size * 1.2f, weight)
+
+ val monospaced = FontFamily.Monospace
+}
+
+val TextStyle.medium get() = copy(fontWeight = FontWeight.Medium)
+val TextStyle.semibold get() = copy(fontWeight = FontWeight.SemiBold)
+val TextStyle.bold get() = copy(fontWeight = FontWeight.Bold)
+val TextStyle.monospacedDigit get() = copy(fontFeatureSettings = "tnum")
+val TextStyle.monospaced get() = copy(fontFamily = FontFamily.Monospace, letterSpacing = 0.sp)
+
+private val families = HashMap<Int, FontFamily>()
+
+/** Inter's optical size follows the text size, as SF switches from Text to Display. */
+private fun family(size: Float): FontFamily = families.getOrPut(size.toInt().coerceIn(14, 32)) {
+ val opsz = size.coerceIn(14f, 32f)
+ FontFamily(listOf(FontWeight.Normal, FontWeight.Medium, FontWeight.SemiBold, FontWeight.Bold).map { weight ->
+ Font(R.font.inter, weight, variationSettings = FontVariation.Settings(
+ FontVariation.weight(weight.weight), FontVariation.Setting("opsz", opsz)))
+ })
+}
+
+/** Inter's dynamic tracking (rsms.me/inter/dynmetrics), tightened toward SF Pro's widths. */
+private fun tracking(size: Float): TextUnit = (-0.0223f + 0.185f * exp(-0.1745f * size) - 0.008f).em
+
+private fun style(size: Float, line: Float, weight: FontWeight = FontWeight.Normal) = TextStyle(
+ fontFamily = family(size), fontSize = size.sp, lineHeight = line.sp, fontWeight = weight,
+ letterSpacing = tracking(size),
+ lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Center, LineHeightStyle.Trim.None),
+)
diff --git a/apps/android/design/src/main/res/drawable/apple_logo.xml b/apps/android/design/src/main/res/drawable/apple_logo.xml
new file mode 100644
index 00000000..c2a4d780
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/apple_logo.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- The Apple mark from Simple Icons (CC0), for "Continue with Apple". -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:fillColor="#FF000000" android:pathData="M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701"/>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/computer_linux.xml b/apps/android/design/src/main/res/drawable/computer_linux.xml
new file mode 100644
index 00000000..c5926fdb
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/computer_linux.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Codync's Linux computer mark (apps/desktop/src/renderer/assets/computer-linux.svg); SF Symbols has no penguin. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
+ <path android:fillColor="#FF000000" android:fillType="evenOdd"
+ android:pathData="M12 1.8C9 1.8 7.6 4.2 7.6 7c0 1.6-.6 2.8-1.6 4.2C4.8 12.9 4 14.8 4 16.8c0 1.2.4 2.2 1 3l-1 1.7c-.2.5.2.9.7.8l3.8-.7c1.1.4 2.3.6 3.5.6s2.4-.2 3.5-.6l3.8.7c.5.1.9-.3.7-.8l-1-1.7c.6-.8 1-1.8 1-3 0-2-.8-3.9-2-5.6-1-1.4-1.6-2.6-1.6-4.2 0-2.8-1.4-5.2-4.4-5.2ZM12 10.6c-2.4 0-4 2.7-4 5.6 0 2.4 1.7 3.8 4 3.8s4-1.4 4-3.8c0-2.9-1.6-5.6-4-5.6ZM10.4 5.3a.9.9 0 1 0 0 1.8.9.9 0 0 0 0-1.8Zm3.2 0a.9.9 0 1 0 0 1.8.9.9 0 0 0 0-1.8ZM10.9 8.1h2.2L12 9.5Z"/>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_app.xml b/apps/android/design/src/main/res/drawable/sf_app.xml
new file mode 100644
index 00000000..61333055
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_app.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `apps`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M236.44-152.59q-34.46 0-59.16-24.69-24.69-24.7-24.69-59.16 0-34.47 24.69-59.02Q201.98-320 236.44-320q34.47 0 59.02 24.54Q320-270.91 320-236.44q0 34.46-24.54 59.16-24.55 24.69-59.02 24.69Zm243.59 0q-34.46 0-59.04-24.69-24.58-24.7-24.58-59.16 0-34.47 24.55-59.02Q445.5-320 479.97-320q34.46 0 59.04 24.54 24.58 24.55 24.58 59.02 0 34.46-24.55 59.16-24.54 24.69-59.01 24.69Zm243.53 0q-34.47 0-59.02-24.69Q640-201.98 640-236.44q0-34.47 24.54-59.02Q689.09-320 723.56-320q34.46 0 59.16 24.54 24.69 24.55 24.69 59.02 0 34.46-24.69 59.16-24.7 24.69-59.16 24.69ZM236.44-396.41q-34.46 0-59.16-24.55-24.69-24.54-24.69-59.01 0-34.46 24.69-59.04 24.7-24.58 59.16-24.58 34.47 0 59.02 24.55Q320-514.5 320-480.03q0 34.46-24.54 59.04-24.55 24.58-59.02 24.58Zm243.59 0q-34.46 0-59.04-24.55-24.58-24.54-24.58-59.01 0-34.46 24.55-59.04 24.54-24.58 59.01-24.58 34.46 0 59.04 24.55 24.58 24.54 24.58 59.01 0 34.46-24.55 59.04-24.54 24.58-59.01 24.58Zm243.53 0q-34.47 0-59.02-24.55Q640-445.5 640-479.97q0-34.46 24.54-59.04 24.55-24.58 59.02-24.58 34.46 0 59.16 24.55 24.69 24.54 24.69 59.01 0 34.46-24.69 59.04-24.7 24.58-59.16 24.58ZM236.44-640q-34.46 0-59.16-24.54-24.69-24.55-24.69-59.02 0-34.46 24.69-59.16 24.7-24.69 59.16-24.69 34.47 0 59.02 24.69Q320-758.02 320-723.56q0 34.47-24.54 59.02Q270.91-640 236.44-640Zm243.59 0q-34.46 0-59.04-24.54-24.58-24.55-24.58-59.02 0-34.46 24.55-59.16 24.54-24.69 59.01-24.69 34.46 0 59.04 24.69 24.58 24.7 24.58 59.16 0 34.47-24.55 59.02Q514.5-640 480.03-640Zm243.53 0q-34.47 0-59.02-24.54Q640-689.09 640-723.56q0-34.46 24.54-59.16 24.55-24.69 59.02-24.69 34.46 0 59.16 24.69 24.69 24.7 24.69 59.16 0 34.47-24.69 59.02Q758.02-640 723.56-640Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_clockwise.xml b/apps/android/design/src/main/res/drawable/sf_arrow_clockwise.xml
new file mode 100644
index 00000000..137e7810
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_clockwise.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `refresh`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M479.04-151.87q-137.11 0-232.62-95.51-95.51-95.51-95.51-232.62t95.51-232.62q95.51-95.51 232.62-95.51 71.16 0 135.71 29.22 64.55 29.21 110.51 83.89v-71.2q0-17.81 12.05-29.86t29.86-12.05q17.82 0 29.87 12.05t12.05 29.86v204.31q0 19.15-13.18 32.32-13.17 13.18-32.32 13.18H558.8q-17.71 0-29.69-12.05t-11.98-29.87q0-17.71 12.05-29.69T559.04-600H683.7q-32-54.57-86.45-85.85-54.44-31.28-118.21-31.28-98.8 0-167.96 69.16Q241.91-578.8 241.91-480t69.17 167.97q69.16 69.16 167.96 69.16 65.37 0 120.08-32.71 54.71-32.7 85.95-87.59 9.34-15.48 26.28-21.56 16.93-6.07 33.78-.12 17.98 5.96 25.94 23.39 7.95 17.44-1 32.87-42.44 80.24-119.75 128.48-77.32 48.24-171.28 48.24Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_counterclockwise.xml b/apps/android/design/src/main/res/drawable/sf_arrow_counterclockwise.xml
new file mode 100644
index 00000000..a28ea775
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_counterclockwise.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `replay`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-70.43q-76.67 0-143.73-29.1-67.05-29.1-116.75-78.8-49.69-49.69-78.79-116.75-29.1-67.05-29.1-143.49 0-19.15 13.17-32.32 13.18-13.18 32.33-13.18t32.33 13.18q13.17 13.17 13.17 32.32 0 115.81 80.78 196.47Q364.2-161.43 480-161.43t196.59-80.79Q757.37-323 757.37-438.8q0-115.81-80.9-196.47t-196.71-80.66h-6.24l30.89 30.89q12.48 12.47 12.1 29.31-.38 16.84-12.1 29.32-12.48 12.48-29.93 12.86-17.46.38-29.94-12.1L340.83-729.37q-13.68-13.67-13.68-32.06 0-18.4 13.68-32.07l103.71-103.72q12.48-12.48 29.94-12.1 17.45.39 29.93 13.1 11.72 12.48 11.98 29.44.26 16.95-12.22 29.43l-30.41 30.42h6q76.67 0 143.73 29.09 67.05 29.1 116.87 78.8 49.81 49.69 78.91 116.63 29.1 66.93 29.1 143.61 0 76.67-29.1 143.72-29.1 67.06-78.79 116.75-49.7 49.7-116.75 78.8-67.06 29.1-143.73 29.1Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_down.xml b/apps/android/design/src/main/res/drawable/sf_arrow_down.xml
new file mode 100644
index 00000000..a7eedfda
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_down.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `arrow_downward`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M434.5-326.15v-436.48q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v436.48l186.67-186.68q13.68-13.67 32.07-13.29 18.39.38 32.06 14.05 12.68 13.68 13.06 32.07.38 18.39-13.29 32.07l-264 264q-6.72 6.71-14.92 9.81-8.19 3.1-17.15 3.1-8.96 0-17.15-3.1-8.2-3.1-14.92-9.81L183.7-448.17q-12.92-12.92-12.92-31.57t12.92-32.33q13.67-13.67 32.44-13.67 18.77 0 32.45 13.67L434.5-326.15Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_down_circle.xml b/apps/android/design/src/main/res/drawable/sf_arrow_down_circle.xml
new file mode 100644
index 00000000..233e9fb4
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_down_circle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `arrow_circle_down`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m434.5-484.44-30.26-30.26q-12.67-12.67-31.83-12.67-19.15 0-31.94 12.67-12.8 12.68-12.8 31.71t12.92 31.95l107.58 107.58q13.63 13.44 31.81 13.44 18.17 0 31.85-13.44l107.58-107.58q12.92-12.68 12.92-31.83t-12.8-31.83q-12.79-12.67-31.94-12.67-19.16 0-31.83 12.67l-30.26 30.26v-118.43q0-19.15-13.17-32.33-13.18-13.17-32.33-13.17t-32.33 13.17q-13.17 13.18-13.17 32.33v118.43ZM480-71.87q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Zm0-91q133.04 0 225.09-92.04 92.04-92.05 92.04-225.09 0-133.04-92.04-225.09-92.05-92.04-225.09-92.04-133.04 0-225.09 92.04-92.04 92.05-92.04 225.09 0 133.04 92.04 225.09 92.05 92.04 225.09 92.04ZM480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_down_circle_fill.xml b/apps/android/design/src/main/res/drawable/sf_arrow_down_circle_fill.xml
new file mode 100644
index 00000000..a02acf5c
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_down_circle_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `arrow_circle_down` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m434.5-484.44-30.26-30.26q-12.67-12.67-31.83-12.67-19.15 0-31.94 12.67-12.8 12.68-12.8 31.71t12.92 31.95l107.58 107.58q13.63 13.44 31.81 13.44 18.17 0 31.85-13.44l107.58-107.58q12.92-12.68 12.92-31.83t-12.8-31.83q-12.79-12.67-31.94-12.67-19.16 0-31.83 12.67l-30.26 30.26v-118.43q0-19.15-13.17-32.33-13.18-13.17-32.33-13.17t-32.33 13.17q-13.17 13.18-13.17 32.33v118.43ZM480-71.87q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_down_doc_on_clipboard.xml b/apps/android/design/src/main/res/drawable/sf_arrow_down_doc_on_clipboard.xml
new file mode 100644
index 00000000..51b90ee1
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_down_doc_on_clipboard.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `content_paste_go`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M727.48-232.59H529.09q-18.53 0-31.06-12.69-12.53-12.7-12.53-31.13 0-18.44 12.7-31.01Q510.89-320 529.33-320h198.15l-33.37-33.61q-12.2-12.19-12.2-30.01 0-17.81 13.25-31.06 12.14-12.15 30.34-12.15t30.39 12.2l106.39 106.15q13.68 13.76 13.68 32.11t-13.68 32.02L756.13-138.2q-12.96 12.96-30.63 12.7-17.67-.26-30.63-13.46-12.2-12.95-12.46-30.63-.26-17.67 12.7-30.63l32.37-32.37ZM202.87-111.87q-37.54 0-64.27-26.73-26.73-26.73-26.73-64.27v-554.26q0-37.54 26.73-64.27 26.73-26.73 64.27-26.73h157.91q12.44-35.72 45.94-58.46 33.5-22.74 73.28-22.74 41.2 0 74.37 22.74t45.85 58.46h156.91q37.54 0 64.27 26.73 26.73 26.73 26.73 64.27v186.61q0 19.15-13.17 32.32-13.18 13.18-32.33 13.18T770.3-538.2q-13.17-13.17-13.17-32.32v-186.61H678.8v78.33q0 19.15-13.17 32.32-13.17 13.18-32.33 13.18H326.7q-19.16 0-32.33-13.18-13.17-13.17-13.17-32.32v-78.33h-78.33v554.26H360q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H202.87ZM480-760.72q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_down_right_and_arrow_up_left.xml b/apps/android/design/src/main/res/drawable/sf_arrow_down_right_and_arrow_up_left.xml
new file mode 100644
index 00000000..ac442c8d
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_down_right_and_arrow_up_left.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `close_fullscreen`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M389-325.35 167.35-103.7q-12.68 12.68-31.83 12.68T103.7-103.7q-12.68-12.67-12.68-31.82t12.68-31.83L325.35-389H197.37q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33t13.17-32.33Q178.22-480 197.37-480H434.5q19.15 0 32.33 13.17Q480-453.65 480-434.5v237.13q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17t-32.33-13.17Q389-178.22 389-197.37v-127.98ZM634.65-571h127.98q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33Q781.78-480 762.63-480H525.5q-19.15 0-32.33-13.17Q480-506.35 480-525.5v-237.13q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17Q571-781.78 571-762.63v127.98L792.65-856.3q12.68-12.68 31.83-12.68t31.82 12.68q12.68 12.67 12.68 31.82t-12.68 31.83L634.65-571Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_down_to_line.xml b/apps/android/design/src/main/res/drawable/sf_arrow_down_to_line.xml
new file mode 100644
index 00000000..4534e9c7
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_down_to_line.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `vertical_align_bottom`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M197.37-111.87q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33t13.17-32.33q13.18-13.17 32.33-13.17h565.26q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H197.37ZM480-301.07q-8.96 0-17.15-3.09-8.2-3.1-14.92-9.82L304.17-457.74q-12.67-12.67-12.67-31.83 0-19.15 12.67-31.82 12.68-12.68 31.83-12.68t31.83 12.68l66.67 66.67v-347.91q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v347.91l66.67-66.67q12.68-12.68 31.83-12.68t31.83 12.68q12.67 12.67 12.67 31.82 0 19.16-12.67 31.83L512.07-313.98q-6.72 6.72-14.92 9.82-8.19 3.09-17.15 3.09Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_left.xml b/apps/android/design/src/main/res/drawable/sf_arrow_left.xml
new file mode 100644
index 00000000..e36dc4f9
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_left.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `arrow_back`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m326.15-434.5 186.68 186.67q13.67 13.68 13.29 32.07-.38 18.39-14.05 32.06-13.68 12.68-32.07 13.06-18.39.38-32.07-13.29l-264-264q-6.71-6.72-9.81-14.92-3.1-8.19-3.1-17.15 0-8.96 3.1-17.15 3.1-8.2 9.81-14.92L448.17-776.3q12.92-12.92 31.57-12.92t32.33 12.92q13.67 13.67 13.67 32.44 0 18.77-13.67 32.45L326.15-525.5h436.48q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H326.15Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_left_arrow_right.xml b/apps/android/design/src/main/res/drawable/sf_arrow_left_arrow_right.xml
new file mode 100644
index 00000000..341e9dfc
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_left_arrow_right.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `swap_horiz`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m245.91-314.02 65.68 65.67q12.67 12.68 12.67 31.33t-12.67 32.32q-13.44 13.68-32.21 13.68-18.77 0-32.45-13.44l-143-143q-6.71-6.71-9.81-14.91-3.1-8.2-3.1-17.15 0-8.96 3.1-17.15 3.1-8.2 9.81-14.92l144-143.76q13.68-13.43 31.95-13.05 18.27.38 31.71 14.05 12.67 13.44 13.05 31.83.38 18.39-13.05 31.82l-65.68 65.68h229.07q19.15 0 32.32 13.17 13.18 13.18 13.18 32.33T507.3-327.2q-13.17 13.18-32.32 13.18H245.91Zm468.18-240.96H485.02q-19.15 0-32.32-13.17-13.18-13.18-13.18-32.33t13.18-32.32q13.17-13.18 32.32-13.18h229.07l-65.68-65.67q-12.67-12.68-12.67-31.33t12.67-32.32q13.44-13.68 32.21-13.68 18.77 0 32.45 13.44l143 143q6.71 6.71 9.81 14.91 3.1 8.2 3.1 17.15 0 8.96-3.1 17.15-3.1 8.2-9.81 14.92l-144 143.76q-13.68 13.43-31.95 13.05-18.27-.38-31.71-14.05-12.67-13.44-13.05-31.83-.38-18.39 13.05-31.82l65.68-65.68Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_right.xml b/apps/android/design/src/main/res/drawable/sf_arrow_right.xml
new file mode 100644
index 00000000..d83eafe0
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_right.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `arrow_forward`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M633.85-434.5H197.37q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33t13.17-32.33q13.18-13.17 32.33-13.17h436.48L447.17-712.17q-13.67-13.68-13.29-32.07.38-18.39 14.05-32.06 13.68-12.68 32.07-13.06 18.39-.38 32.07 13.29l264 264q6.71 6.72 9.81 14.92 3.1 8.19 3.1 17.15 0 8.96-3.1 17.15-3.1 8.2-9.81 14.92L511.83-183.7q-12.92 12.92-31.57 12.92t-32.33-12.92q-13.67-13.67-13.67-32.44 0-18.77 13.67-32.45L633.85-434.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_right_doc_on_clipboard.xml b/apps/android/design/src/main/res/drawable/sf_arrow_right_doc_on_clipboard.xml
new file mode 100644
index 00000000..51b90ee1
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_right_doc_on_clipboard.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `content_paste_go`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M727.48-232.59H529.09q-18.53 0-31.06-12.69-12.53-12.7-12.53-31.13 0-18.44 12.7-31.01Q510.89-320 529.33-320h198.15l-33.37-33.61q-12.2-12.19-12.2-30.01 0-17.81 13.25-31.06 12.14-12.15 30.34-12.15t30.39 12.2l106.39 106.15q13.68 13.76 13.68 32.11t-13.68 32.02L756.13-138.2q-12.96 12.96-30.63 12.7-17.67-.26-30.63-13.46-12.2-12.95-12.46-30.63-.26-17.67 12.7-30.63l32.37-32.37ZM202.87-111.87q-37.54 0-64.27-26.73-26.73-26.73-26.73-64.27v-554.26q0-37.54 26.73-64.27 26.73-26.73 64.27-26.73h157.91q12.44-35.72 45.94-58.46 33.5-22.74 73.28-22.74 41.2 0 74.37 22.74t45.85 58.46h156.91q37.54 0 64.27 26.73 26.73 26.73 26.73 64.27v186.61q0 19.15-13.17 32.32-13.18 13.18-32.33 13.18T770.3-538.2q-13.17-13.17-13.17-32.32v-186.61H678.8v78.33q0 19.15-13.17 32.32-13.17 13.18-32.33 13.18H326.7q-19.16 0-32.33-13.18-13.17-13.17-13.17-32.32v-78.33h-78.33v554.26H360q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H202.87ZM480-760.72q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_right_to_line.xml b/apps/android/design/src/main/res/drawable/sf_arrow_right_to_line.xml
new file mode 100644
index 00000000..9220fe67
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_right_to_line.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keyboard_tab`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M842.63-234.5q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33v-400q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v400q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17Zm-299.3-200H117.37q-19.15 0-32.33-13.17Q71.87-460.85 71.87-480t13.17-32.33q13.18-13.17 32.33-13.17h425.96L437.65-632.17q-12.67-12.68-13.05-31.45-.38-18.77 13.05-32.21 12.68-12.67 31.83-12.67t31.82 12.67l183.77 183.76q6.71 6.72 9.81 14.92 3.1 8.19 3.1 17.15 0 8.96-3.1 17.15-3.1 8.2-9.81 14.92L501.3-264.17q-12.67 12.67-31.32 12.79-18.65.12-32.33-12.55-13.67-13.68-13.79-32.45-.12-18.77 13.55-32.45L543.33-434.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_triangle_2_circlepath.xml b/apps/android/design/src/main/res/drawable/sf_arrow_triangle_2_circlepath.xml
new file mode 100644
index 00000000..36bb06a3
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_triangle_2_circlepath.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `sync`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M245.02-478q0 43.57 16.64 84.99 16.64 41.42 51.69 76.94l8.08 8.09v-50.35q0-17.71 12.1-29.69T363.35-400q17.72 0 29.69 11.98 11.98 11.98 11.98 29.69v157.61q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17H202.15q-17.72 0-29.69-12.1-11.98-12.09-11.98-29.81t12.1-29.7q12.09-11.97 29.81-11.97h60.2l-12.89-11.61q-52.24-47.44-73.96-107.16-21.72-59.71-21.72-120.43 0-96.39 50.03-174.92 50.04-78.54 133.91-119.78 15.67-8.47 32.25.08 16.57 8.55 22.05 26.71 5.24 17.15-1.34 33.94-6.57 16.8-22.49 25.75-56.32 31.29-89.86 86.59-33.55 55.3-33.55 121.63Zm469.96-4q0-43.57-16.64-84.99-16.64-41.42-51.69-76.94l-8.08-8.09v50.35q0 17.71-11.98 29.69T596.89-560q-17.72 0-29.81-12.1-12.1-12.1-12.1-29.81v-157.37q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17h157.37q17.72 0 29.69 11.98 11.98 11.97 11.98 29.69t-11.98 29.82q-11.97 12.09-29.69 12.09h-60.44l12.89 11.61q49.72 49.96 72.7 108.42 22.98 58.45 22.98 119.17 0 96.39-50.03 174.92-50.04 78.54-133.91 119.78-15.67 8.47-32.25-.08-16.57-8.55-22.05-26.71-5.24-17.15 1.34-33.94 6.57-16.8 22.49-25.75 56.32-31.29 89.86-86.59 33.55-55.3 33.55-121.63Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_triangle_branch.xml b/apps/android/design/src/main/res/drawable/sf_arrow_triangle_branch.xml
new file mode 100644
index 00000000..a3e27087
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_triangle_branch.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `call_split`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M242.87-653.48v50.85q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17t-32.33-13.17q-13.17-13.18-13.17-32.33v-160q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17h160q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33T389.7-730.3q-13.18 13.17-32.33 13.17h-50.85L499.15-524.5q12.68 12.67 19.51 29.21 6.84 16.53 6.84 34.68v263q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17t-32.33-13.17q-13.17-13.18-13.17-32.33v-264.24L242.87-653.48Zm474.26.48-83.41 84.41q-13.68 13.68-32.45 13.68-18.77 0-32.44-13.68-13.68-13.67-13.8-32.82-.12-19.16 13.56-32.83L653-717.13h-50.37q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33t13.17-32.33q13.18-13.17 32.33-13.17h160q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33v160q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17T730.3-570.3q-13.17-13.18-13.17-32.33V-653Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_up.xml b/apps/android/design/src/main/res/drawable/sf_arrow_up.xml
new file mode 100644
index 00000000..a3462ff7
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_up.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `arrow_upward`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M434.5-633.85 247.83-447.17q-13.68 13.67-32.07 13.29-18.39-.38-32.06-14.05-12.68-13.68-13.06-32.07-.38-18.39 13.29-32.07l264-264q6.72-6.71 14.92-9.81 8.19-3.1 17.15-3.1 8.96 0 17.15 3.1 8.2 3.1 14.92 9.81L776.3-511.83q12.92 12.92 12.92 31.57t-12.92 32.33q-13.67 13.67-32.44 13.67-18.77 0-32.45-13.67L525.5-633.85v436.48q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17t-32.33-13.17q-13.17-13.18-13.17-32.33v-436.48Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_up_doc_on_clipboard.xml b/apps/android/design/src/main/res/drawable/sf_arrow_up_doc_on_clipboard.xml
new file mode 100644
index 00000000..51b90ee1
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_up_doc_on_clipboard.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `content_paste_go`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M727.48-232.59H529.09q-18.53 0-31.06-12.69-12.53-12.7-12.53-31.13 0-18.44 12.7-31.01Q510.89-320 529.33-320h198.15l-33.37-33.61q-12.2-12.19-12.2-30.01 0-17.81 13.25-31.06 12.14-12.15 30.34-12.15t30.39 12.2l106.39 106.15q13.68 13.76 13.68 32.11t-13.68 32.02L756.13-138.2q-12.96 12.96-30.63 12.7-17.67-.26-30.63-13.46-12.2-12.95-12.46-30.63-.26-17.67 12.7-30.63l32.37-32.37ZM202.87-111.87q-37.54 0-64.27-26.73-26.73-26.73-26.73-64.27v-554.26q0-37.54 26.73-64.27 26.73-26.73 64.27-26.73h157.91q12.44-35.72 45.94-58.46 33.5-22.74 73.28-22.74 41.2 0 74.37 22.74t45.85 58.46h156.91q37.54 0 64.27 26.73 26.73 26.73 26.73 64.27v186.61q0 19.15-13.17 32.32-13.18 13.18-32.33 13.18T770.3-538.2q-13.17-13.17-13.17-32.32v-186.61H678.8v78.33q0 19.15-13.17 32.32-13.17 13.18-32.33 13.18H326.7q-19.16 0-32.33-13.18-13.17-13.17-13.17-32.32v-78.33h-78.33v554.26H360q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H202.87ZM480-760.72q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrow_up_right.xml b/apps/android/design/src/main/res/drawable/sf_arrow_up_right.xml
new file mode 100644
index 00000000..893bcde0
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrow_up_right.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `arrow_outward`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M636.89-610.61 290.22-263.93q-12.92 12.91-31.83 12.79-18.91-.12-31.82-13.03-12.92-12.92-12.92-31.95t12.92-31.95L573-674.5H282.39q-19.15 0-32.32-13.17-13.18-13.18-13.18-32.33t13.18-32.33q13.17-13.17 32.32-13.17h400q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33v400q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17t-32.32-13.17q-13.18-13.18-13.18-32.33v-290.61Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_arrowshape_turn_up_left.xml b/apps/android/design/src/main/res/drawable/sf_arrowshape_turn_up_left.xml
new file mode 100644
index 00000000..b40feafe
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_arrowshape_turn_up_left.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `reply`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m285.44-474.5 106.67 106.67q13.43 13.44 13.05 31.83-.38 18.39-13.81 31.83-13.44 12.67-31.83 13.05-18.39.38-31.82-13.05L143.93-487.93q-13.67-13.68-13.67-32.07t13.67-32.07L327.7-735.83q12.67-12.67 31.44-12.67 18.77 0 32.21 12.67 13.43 13.44 13.43 32.21 0 18.77-13.43 32.21L285.44-565.5h357.19q85.15 0 145.33 60.17 60.17 60.18 60.17 145.33v122.63q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17t-32.33-13.17q-13.17-13.18-13.17-32.33V-360q0-47.85-33.33-81.17-33.32-33.33-81.17-33.33H285.44Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_battery_100percent.xml b/apps/android/design/src/main/res/drawable/sf_battery_100percent.xml
new file mode 100644
index 00000000..deb600b9
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_battery_100percent.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `battery_full_alt`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M197.37-270.2q-19.15 0-32.33-13.17-13.17-13.17-13.17-32.33v-78.8h-34.5q-19.15 0-32.33-13.17Q71.87-420.85 71.87-440v-80q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17h34.5v-78.8q0-19.16 13.17-32.33 13.18-13.17 32.33-13.17h645.26q19.15 0 32.33 13.17 13.17 13.17 13.17 32.33v328.6q0 19.16-13.17 32.33-13.18 13.17-32.33 13.17H197.37Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_battery_75percent.xml b/apps/android/design/src/main/res/drawable/sf_battery_75percent.xml
new file mode 100644
index 00000000..25331275
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_battery_75percent.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `battery_horiz_075`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M197.37-270.2q-19.15 0-32.33-13.17-13.17-13.17-13.17-32.33v-78.8h-34.5q-19.15 0-32.33-13.17Q71.87-420.85 71.87-440v-80q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17h34.5v-78.8q0-19.16 13.17-32.33 13.18-13.17 32.33-13.17h645.26q19.15 0 32.33 13.17 13.17 13.17 13.17 32.33v328.6q0 19.16-13.17 32.33-13.18 13.17-32.33 13.17H197.37Zm45.5-91h154.26v-237.6H242.87v237.6Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_bell.xml b/apps/android/design/src/main/res/drawable/sf_bell.xml
new file mode 100644
index 00000000..945d7cec
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_bell.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `notifications`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M197.37-191.87q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33t13.17-32.33q13.18-13.17 32.33-13.17H229v-271.87q0-86.11 51.32-153.6 51.31-67.49 134.18-88.2v-26.09q0-27.29 19.1-46.4 19.11-19.1 46.4-19.1t46.4 19.1q19.1 19.11 19.1 46.4v26.09q83.11 20.71 134.3 88.08Q731-641.09 731-554.74v271.87h31.63q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H197.37ZM480-498.8Zm.24 429.56q-34.18 0-58.53-24.27-24.34-24.27-24.34-58.36h165.5q0 34.2-24.27 58.41-24.28 24.22-58.36 24.22ZM320-282.87h320v-271.87q0-66-47-113t-113-47q-66 0-113 47t-47 113v271.87Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_bolt.xml b/apps/android/design/src/main/res/drawable/sf_bolt.xml
new file mode 100644
index 00000000..41139a21
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_bolt.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `bolt`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m425.59-237.02 202.45-243.46H470.43l28.05-220.06-180.94 261.02h137.33l-29.28 202.5Zm-72.76-113.89H234.57q-27.35 0-40.41-24.37-13.05-24.37 2.86-47.24l310.96-447.46q10.72-14.96 27.79-20.69 17.08-5.74 34.8.73 17.71 6.48 26.55 22.32t6.6 34.03L571-569.09h149.74q29.35 0 41.4 26.11 12.06 26.11-7.1 48.74L413.85-84.7q-11.72 13.96-28.68 17.96-16.95 4-33.15-3.24-16.19-7.24-25.05-22.69-8.86-15.46-6.62-33.42l32.48-224.82Zm119.84-118.13Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_book_fill.xml b/apps/android/design/src/main/res/drawable/sf_book_fill.xml
new file mode 100644
index 00000000..9df2b10d
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_book_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `book` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M242.87-71.87q-37.78 0-64.39-26.61t-26.61-64.39v-634.26q0-37.78 26.61-64.39t64.39-26.61h474.26q37.78 0 64.39 26.61t26.61 64.39v634.26q0 37.78-26.61 64.39t-64.39 26.61H242.87Zm197.85-725.26v240.22q0 13.43 10.93 19.77 10.94 6.34 23.13-.38l42.07-24.94q11.19-6.71 23.37-6.71 12.17 0 23.37 6.71l42.06 24.94q12.2 6.72 23.63.38 11.44-6.34 11.44-19.77v-240.22h-200Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_book_pages.xml b/apps/android/design/src/main/res/drawable/sf_book_pages.xml
new file mode 100644
index 00000000..0e3e5c3a
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_book_pages.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `menu_book`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M260-311.15q47 0 91.5 10.5t88.5 31.5v-394q-41-24-87-36t-93-12q-36 0-71.5 7t-68.5 21v396q35-12 69.5-18t70.5-6Zm260 42q44-21 88.5-31.5t91.5-10.5q36 0 70.5 6t69.5 18v-396q-33-14-68.5-21t-71.5-7q-47 0-93 12t-87 36v394Zm-39.28 105.13q-14.24 0-27.46-3.5t-24.46-9.98q-38.76-22.76-81.44-34.62-42.69-11.86-87.36-11.86-41.18 0-80.9 11.12-39.71 11.12-76.23 30.64-24.35 12.68-47.32-1.15-22.96-13.84-22.96-40.35v-481.76q0-14.35 6.81-27.02 6.82-12.68 20.45-19.02 46.48-23.76 96.72-35.4 50.23-11.65 102.69-11.65 58.5 0 114.24 15 55.74 15 106.5 45.72 51-30.48 106.62-45.6 55.62-15.12 114.12-15.12 52.46 0 102.69 11.65 50.24 11.64 96.72 35.4 13.63 6.34 20.45 19.02 6.81 12.67 6.81 27.02v485.35q0 25.63-22.84 38.23-22.85 12.6-47.44-.32-36.52-19.52-76.23-30.64-39.72-11.12-80.9-11.12-44.52 0-86.68 11.98-42.17 11.98-80.69 34.5-11.24 6.48-24.46 9.98-13.21 3.5-27.45 3.5ZM280-485.15Zm280-115.48q0-8.77 6.26-18.03 6.26-9.25 14.26-12.25 29-10 58.24-15.12 29.24-5.12 61.24-5.12 20 0 39.5 2.51 19.5 2.52 38.5 6.55 9 2.01 15.5 10.06t6.5 18.12q0 17-11 24.88-11 7.88-28 3.88-14.24-3-29.5-4.5t-31.5-1.5q-26 0-50.76 4.88-24.76 4.88-47.76 12.88-18.21 7-29.85-1.04-11.63-8.04-11.63-26.2Zm0 220q0-8.77 6.26-18.03 6.26-9.25 14.26-12.25 29-10 58.24-15.12 29.24-5.12 61.24-5.12 20 0 39.5 2.51 19.5 2.52 38.5 6.55 9 2.01 15.5 10.06t6.5 18.12q0 17-11 24.88-11 7.88-28 3.88-14.24-3-29.5-4.5t-31.5-1.5q-26 0-50.76 4.38-24.76 4.38-47.76 12.38-18.21 7-29.85-.54-11.63-7.53-11.63-25.7Zm0-110q0-8.77 6.26-18.03 6.26-9.25 14.26-12.25 29-10 58.24-15.12 29.24-5.12 61.24-5.12 20 0 39.5 2.51 19.5 2.52 38.5 6.55 9 2.01 15.5 10.06t6.5 18.12q0 17-11 24.88-11 7.88-28 3.88-14.24-3-29.5-4.5t-31.5-1.5q-26 0-50.76 4.88-24.76 4.88-47.76 12.88-18.21 7-29.85-1.04-11.63-8.04-11.63-26.2Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_brain.xml b/apps/android/design/src/main/res/drawable/sf_brain.xml
new file mode 100644
index 00000000..6e9cb6c9
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_brain.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `psychology`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m434-410 3.76 29.61q1.24 8.96 7.43 14.67 6.19 5.72 15.2 5.72h39.22q9.01 0 15.2-5.72 6.19-5.71 7.43-14.67L526-410q8-3 14.5-7t11.5-9l27.37 12.04q7.96 3.48 16.03 1 8.08-2.47 12.56-10.19l19.61-33.7q4.71-7.95 2.97-15.92-1.74-7.97-8.69-13.66L598-504q2-8 2-16t-2-16l23.85-17.57q6.95-5.69 8.69-13.66 1.74-7.97-2.97-15.92l-19.61-33.7q-4.48-7.72-12.56-10.19-8.07-2.48-16.03 1L552-614q-5-5-11.5-9t-14.5-7l-3.76-29.61q-1.24-8.96-7.43-14.67-6.19-5.72-15.2-5.72h-39.22q-9.01 0-15.2 5.72-6.19 5.71-7.43 14.67L434-630q-8 3-14.5 7t-11.5 9l-27.37-12.04q-7.96-3.48-16.03-1-8.08 2.47-12.56 10.19l-19.61 33.7q-4.71 7.95-2.97 15.92 1.74 7.97 8.69 13.66L362-536q-2 8-2 16t2 16l-23.85 17.57q-6.95 5.69-8.69 13.66-1.74 7.97 2.97 15.92l19.61 33.7q4.48 7.72 12.56 10.19 8.07 2.48 16.03-1L408-426q5 5 11.5 9t14.5 7Zm46-50q-25 0-42.5-17.5T420-520q0-25 17.5-42.5T480-580q25 0 42.5 17.5T540-520q0 25-17.5 42.5T480-460ZM232.83-248.89q-56.76-52.96-88.38-123.41-31.62-70.46-31.62-147.7 0-152.99 107.07-260.08 107.07-107.09 260.03-107.09 127.46 0 225.87 75.05 98.42 75.05 128.13 195.45l52.48 207.15q5.72 21.63-7.91 39.16-13.63 17.53-36.35 17.53h-74.98v109q0 37.79-26.6 64.4-26.61 26.6-64.4 26.6h-69v34.5q0 19.16-13.17 32.33-13.17 13.17-32.33 13.17-19.15 0-32.32-13.17-13.18-13.17-13.18-32.33v-80q0-19.15 13.18-32.32 13.17-13.18 32.32-13.18h114.5v-154.5q0-19.15 13.18-32.32 13.17-13.18 32.32-13.18h61.55l-36.81-150.21q-23-89.33-97.04-145.73-74.04-56.4-169.37-56.4-114.41 0-195.29 79.88Q203.83-636.4 203.83-522q0 59.04 24.14 112.57 24.14 53.52 68.66 94.56l27.2 25.2v171.34q0 19.16-13.18 32.33-13.17 13.17-32.32 13.17-19.16 0-32.33-13.17-13.17-13.17-13.17-32.33v-130.56ZM493.52-434.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_bubble_left_and_bubble_right.xml b/apps/android/design/src/main/res/drawable/sf_bubble_left_and_bubble_right.xml
new file mode 100644
index 00000000..6ebd5454
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_bubble_left_and_bubble_right.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `forum`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M281.2-227.56q-19.63 0-32.57-13.09-12.93-13.08-12.93-32.42v-85.5h526.93v-366.45h85.5q19.34 0 32.42 13.08 13.08 13.08 13.08 32.42v503.95q0 30.5-27.97 42.36-27.96 11.86-49.59-9.77l-84.59-84.58H281.2Zm-51-211.01-86.5 86.27q-21.63 21.63-49.48 9.77-27.85-11.86-27.85-42.36v-464.2q0-19.33 13.08-32.42 13.08-13.08 32.42-13.08h525.26q19.34 0 32.42 13.08 13.08 13.09 13.08 32.42v365.02q0 19.34-13.08 32.42-13.08 13.08-32.42 13.08H230.2Zm361.43-91v-274.02H157.37v274.02h434.26Zm-434.26 0v-274.02 274.02Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_bubble_left_and_bubble_right_fill.xml b/apps/android/design/src/main/res/drawable/sf_bubble_left_and_bubble_right_fill.xml
new file mode 100644
index 00000000..f3c25e15
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_bubble_left_and_bubble_right_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `forum` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M281.2-227.56q-19.63 0-32.57-13.09-12.93-13.08-12.93-32.42v-85.5h526.93v-366.45h85.5q19.34 0 32.42 13.08 13.08 13.08 13.08 32.42v503.95q0 30.5-27.97 42.36-27.96 11.86-49.59-9.77l-84.59-84.58H281.2Zm-51-211.01-86.5 86.27q-21.63 21.63-49.48 9.77-27.85-11.86-27.85-42.36v-464.2q0-19.33 13.08-32.42 13.08-13.08 32.42-13.08h525.26q19.34 0 32.42 13.08 13.08 13.09 13.08 32.42v365.02q0 19.34-13.08 32.42-13.08 13.08-32.42 13.08H230.2Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_calendar.xml b/apps/android/design/src/main/res/drawable/sf_calendar.xml
new file mode 100644
index 00000000..4b57af03
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_calendar.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `calendar_today`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M202.87-71.87q-37.78 0-64.39-26.61t-26.61-64.39v-554.26q0-37.78 26.61-64.39t64.39-26.61H240v-37.37q0-17.96 12.46-30.29 12.45-12.34 30.41-12.34t30.29 12.34q12.34 12.33 12.34 30.29v37.37h309v-37.37q0-17.96 12.46-30.29 12.45-12.34 30.41-12.34t30.29 12.34Q720-863.46 720-845.5v37.37h37.13q37.78 0 64.39 26.61t26.61 64.39v554.26q0 37.78-26.61 64.39t-64.39 26.61H202.87Zm0-91h554.26V-560H202.87v397.13Zm0-477.13h554.26v-77.13H202.87V-640Zm0 0v-77.13V-640Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_camera_fill.xml b/apps/android/design/src/main/res/drawable/sf_camera_fill.xml
new file mode 100644
index 00000000..c2349f4b
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_camera_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `photo_camera` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-258.09q75.72 0 128.82-53.09 53.09-53.1 53.09-128.82t-53.09-128.82q-53.1-53.09-128.82-53.09t-128.82 53.09q-53.09 53.1-53.09 128.82t53.09 128.82q53.1 53.09 128.82 53.09Zm0-86.21q-40.33 0-68.01-27.69Q384.3-399.67 384.3-440q0-40.33 27.69-68.01Q439.67-535.7 480-535.7q40.33 0 68.01 27.69Q575.7-480.33 575.7-440q0 40.33-27.69 68.01Q520.33-344.3 480-344.3ZM162.87-111.87q-37.78 0-64.39-26.61t-26.61-64.39v-474.26q0-37.78 26.61-64.39t64.39-26.61H281.7l50.47-52.33q12.44-12.95 29.61-20.31 17.18-7.36 35.61-7.36h165.22q18.43 0 35.61 7.36 17.17 7.36 29.61 20.31l50.47 52.33h118.83q37.78 0 64.39 26.61t26.61 64.39v474.26q0 37.78-26.61 64.39t-64.39 26.61H162.87Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_chart_bar.xml b/apps/android/design/src/main/res/drawable/sf_chart_bar.xml
new file mode 100644
index 00000000..8cca613f
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_chart_bar.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `bar_chart`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M686.22-151.87q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33v-200.48q0-19.15 13.17-32.32 13.18-13.18 32.33-13.18h76.41q19.15 0 32.33 13.18 13.17 13.17 13.17 32.32v200.48q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17h-76.41Zm-244.31 0q-19.15 0-32.32-13.17-13.18-13.18-13.18-32.33v-565.26q0-19.15 13.18-32.33 13.17-13.17 32.32-13.17h76.18q19.15 0 32.32 13.17 13.18 13.18 13.18 32.33v565.26q0 19.15-13.18 32.33-13.17 13.17-32.32 13.17h-76.18Zm-244.54 0q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33v-365.26q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17h76.41q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33v365.26q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17h-76.41Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_checklist.xml b/apps/android/design/src/main/res/drawable/sf_checklist.xml
new file mode 100644
index 00000000..8bb5fb13
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_checklist.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `checklist`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m222.2-320.65 137.93-138.18Q373.8-472.5 392.2-472q18.39.5 32.06 14.17 12.67 13.68 12.56 31.95-.12 18.27-12.8 31.71l-169 169.76q-13.67 13.67-31.94 13.79-18.28.12-31.95-13.55l-85.76-86Q92.46-322.85 92.46-342t12.91-31.83q12.67-12.67 31.83-12.67 19.15 0 31.82 12.67l53.18 53.18Zm0-320 137.93-138.18Q373.8-792.5 392.2-792q18.39.5 32.06 14.17 12.67 13.68 12.56 31.95-.12 18.27-12.8 31.71l-169 169.76q-13.67 13.67-31.94 13.79-18.28.12-31.95-13.55l-85.76-86Q92.46-642.85 92.46-662t12.91-31.83q12.67-12.67 31.83-12.67 19.15 0 31.82 12.67l53.18 53.18ZM566.7-274.5q-19.16 0-32.33-13.17Q521.2-300.85 521.2-320t13.17-32.33q13.17-13.17 32.33-13.17h274.5q19.15 0 32.32 13.17Q886.7-339.15 886.7-320t-13.18 32.33q-13.17 13.17-32.32 13.17H566.7Zm0-320q-19.16 0-32.33-13.17Q521.2-620.85 521.2-640t13.17-32.33q13.17-13.17 32.33-13.17h274.5q19.15 0 32.32 13.17Q886.7-659.15 886.7-640t-13.18 32.33q-13.17 13.17-32.32 13.17H566.7Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_checkmark.xml b/apps/android/design/src/main/res/drawable/sf_checkmark.xml
new file mode 100644
index 00000000..9b708864
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_checkmark.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `check`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m382-362.13 334.7-334.7q13.67-13.67 32.06-13.67t32.07 13.67q13.67 13.68 13.67 32.45 0 18.77-13.67 32.45L414.07-264.41q-13.68 13.67-32.07 13.67t-32.07-13.67L178.41-435.93q-13.67-13.68-13.29-32.45.38-18.77 14.05-32.45 13.68-13.67 32.45-13.67 18.77 0 32.45 13.67L382-362.13Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_checkmark_circle.xml b/apps/android/design/src/main/res/drawable/sf_checkmark_circle.xml
new file mode 100644
index 00000000..edf12a33
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_checkmark_circle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `check_circle`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m423.28-416.37-79.78-79.78q-12.43-12.44-31.35-12.44-18.91 0-31.35 12.44-12.43 12.43-12.31 31.35.12 18.91 12.55 31.34l110.18 110.18q13.76 13.67 32.11 13.67 18.34 0 32.02-13.67L677.76-545.7q12.44-12.43 12.44-31.22 0-18.8-12.44-31.23-12.43-12.44-31.35-12.44-18.91 0-31.34 12.44L423.28-416.37ZM480-71.87q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Zm0-91q133.04 0 225.09-92.04 92.04-92.05 92.04-225.09 0-133.04-92.04-225.09-92.05-92.04-225.09-92.04-133.04 0-225.09 92.04-92.04 92.05-92.04 225.09 0 133.04 92.04 225.09 92.05 92.04 225.09 92.04ZM480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_checkmark_circle_fill.xml b/apps/android/design/src/main/res/drawable/sf_checkmark_circle_fill.xml
new file mode 100644
index 00000000..95a711c0
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_checkmark_circle_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `check_circle` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m423.28-416.37-79.78-79.78q-12.43-12.44-31.35-12.44-18.91 0-31.35 12.44-12.43 12.43-12.31 31.35.12 18.91 12.55 31.34l110.18 110.18q13.76 13.67 32.11 13.67 18.34 0 32.02-13.67L677.76-545.7q12.44-12.43 12.44-31.22 0-18.8-12.44-31.23-12.43-12.44-31.35-12.44-18.91 0-31.34 12.44L423.28-416.37ZM480-71.87q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_checkmark_message.xml b/apps/android/design/src/main/res/drawable/sf_checkmark_message.xml
new file mode 100644
index 00000000..ea130981
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_checkmark_message.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `mark_chat_read`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m695.67-277.78 137.94-138.18q13.76-13.67 32.11-13.17t32.09 14.17q12.6 13.68 12.86 31.95.26 18.27-13.17 31.71l-169.76 170q-13.76 13.67-32.11 13.67t-32.02-13.67l-85-86q-12.68-12.68-12.94-31.45-.26-18.77 13.18-32.21 12.67-12.67 31.82-12.67 19.16 0 31.83 12.67l53.17 53.18Zm-463.8 45.91-82.44 82.44q-21.63 21.63-49.59 9.77-27.97-11.86-27.97-42.36v-615.11q0-37.78 26.61-64.39t64.39-26.61h634.26q37.78 0 64.39 26.61t26.61 64.39V-571q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17t-32.33-13.17q-13.17-13.18-13.17-32.33v-226.13H162.87v508.5l35-34.24H429q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H231.87Zm-69-91v-474.26 474.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_checkmark_seal.xml b/apps/android/design/src/main/res/drawable/sf_checkmark_seal.xml
new file mode 100644
index 00000000..12ea348d
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_checkmark_seal.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `verified`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m438-454.63-56.33-55.57q-11.71-11.71-29.05-11.71t-29.82 12.48q-11.71 11.71-11.71 29.43t11.71 29.43l83.13 83.14q13.68 13.67 32.07 13.67t32.07-13.67L637.2-534.57q12.47-12.47 12.09-29.43-.38-16.96-12.09-29.43-12.48-12.48-29.82-12.86-17.34-.38-29.81 12.09L438-454.63ZM320.26-84.02l-57.28-97.05-108.81-23.76q-16.91-3.47-27.22-17.65-10.32-14.17-8.32-31.32l11-111.57-74.04-85.04Q44.15-463.09 44.15-480t11.44-29.59l74.04-85.04-11-111.57q-2-17.15 8.32-31.32 10.31-14.18 27.22-17.65l108.81-23.76 57.28-97.05q8.96-14.67 24.99-19.89 16.03-5.22 31.95 1.5L480-850.85l102.8-43.52q15.92-6.72 31.95-1.5t24.99 19.89l57.28 97.05 108.81 23.76q16.91 3.47 27.22 17.65 10.32 14.17 8.32 31.32l-11 111.57 74.04 85.04q11.44 12.68 11.44 29.59t-11.44 29.59l-74.04 85.04 11 111.57q2 17.15-8.32 31.32-10.31 14.18-27.22 17.65l-108.81 23.76-57.28 97.05q-8.96 14.67-24.99 19.89-16.03 5.22-31.95-1.5L480-109.15 377.2-65.63q-15.92 6.72-31.95 1.5t-24.99-19.89Zm58.94-81.57L480-209.35l102.8 43.76 55.29-95.04 108.56-25.52-9.52-111.05 72.8-82.8-72.8-84.8 9.52-111.05-108.56-23.52-57.29-95.04L480-750.65l-102.8-43.76-55.29 95.04-108.56 23.52 9.52 111.05-72.8 84.8 72.8 82.8-9.52 113.05 108.56 23.52 57.29 95.04ZM480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_chevron_down.xml b/apps/android/design/src/main/res/drawable/sf_chevron_down.xml
new file mode 100644
index 00000000..be7f96c2
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_chevron_down.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keyboard_arrow_down`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-355.5q-8.96 0-17.15-3.1-8.2-3.1-14.92-9.81L264.17-552.17Q251.5-564.85 251.5-584t12.67-31.83Q276.85-628.5 296-628.5t31.83 12.67L480-463.65l152.17-152.18Q644.85-628.5 664-628.5t31.83 12.67Q708.5-603.15 708.5-584t-12.67 31.83L512.07-368.41q-6.72 6.71-14.92 9.81-8.19 3.1-17.15 3.1Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_chevron_left.xml b/apps/android/design/src/main/res/drawable/sf_chevron_left.xml
new file mode 100644
index 00000000..2d705b0a
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_chevron_left.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `chevron_left`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m439.65-480 152.18 152.17Q604.5-315.15 604.5-296t-12.67 31.83Q579.15-251.5 560-251.5t-31.83-12.67L344.41-447.93q-6.71-6.72-9.81-14.92-3.1-8.19-3.1-17.15 0-8.96 3.1-17.15 3.1-8.2 9.81-14.92l183.76-183.76Q540.85-708.5 560-708.5t31.83 12.67Q604.5-683.15 604.5-664t-12.67 31.83L439.65-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_chevron_right.xml b/apps/android/design/src/main/res/drawable/sf_chevron_right.xml
new file mode 100644
index 00000000..eafd28f4
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_chevron_right.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `chevron_right`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M496.35-480 344.17-632.17Q331.5-644.85 331.5-664t12.67-31.83Q356.85-708.5 376-708.5t31.83 12.67l183.76 183.76q6.71 6.72 9.81 14.92 3.1 8.19 3.1 17.15 0 8.96-3.1 17.15-3.1 8.2-9.81 14.92L407.83-264.17Q395.15-251.5 376-251.5t-31.83-12.67Q331.5-276.85 331.5-296t12.67-31.83L496.35-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_chevron_up.xml b/apps/android/design/src/main/res/drawable/sf_chevron_up.xml
new file mode 100644
index 00000000..b77f2052
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_chevron_up.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keyboard_arrow_up`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-520.35 327.83-368.17Q315.15-355.5 296-355.5t-31.83-12.67Q251.5-380.85 251.5-400t12.67-31.83l183.76-183.76q13.68-13.67 32.07-13.67t32.07 13.67l183.76 183.76Q708.5-419.15 708.5-400t-12.67 31.83Q683.15-355.5 664-355.5t-31.83-12.67L480-520.35Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_circle.xml b/apps/android/design/src/main/res/drawable/sf_circle.xml
new file mode 100644
index 00000000..5f85865c
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_circle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `radio_button_unchecked`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-71.87q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Zm0-91q133.04 0 225.09-92.04 92.04-92.05 92.04-225.09 0-133.04-92.04-225.09-92.05-92.04-225.09-92.04-133.04 0-225.09 92.04-92.04 92.05-92.04 225.09 0 133.04 92.04 225.09 92.05 92.04 225.09 92.04ZM480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_circle_dotted.xml b/apps/android/design/src/main/res/drawable/sf_circle_dotted.xml
new file mode 100644
index 00000000..92971d11
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_circle_dotted.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `motion_photos_on`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M479.98-71.87q-84.65 0-159.09-31.98-74.43-31.98-129.63-87.05-55.19-55.08-87.29-129.45-32.1-74.37-32.1-158.93 0-30.74 4.52-61.47 4.52-30.74 13.57-60.51 5.24-18.15 22.77-24.73 17.53-6.58 33.68 2.38 17.39 9.2 24.73 27.01 7.34 17.82 2.34 37.36-5.05 19.61-7.83 39.58-2.78 19.97-2.78 40.38 0 132.5 92.28 224.45 92.28 91.96 224.85 91.96t224.85-92.28q92.28-92.28 92.28-224.85t-91.82-224.85q-91.82-92.28-224.11-92.28-21.58 0-42.7 2.9-21.13 2.9-41.98 8.71-19.39 5-36.9-1.84-17.51-6.84-25.47-24.11-7.95-17.27-.5-34.92 7.46-17.65 25.85-22.89 29.04-9.81 59.53-14.33 30.48-4.52 60.97-4.52 84.65 0 159.1 32.1 74.44 32.1 129.64 87.29 55.19 55.2 87.29 129.65 32.1 74.46 32.1 159.11 0 84.65-32.1 159.09-32.1 74.43-87.29 129.63-55.2 55.19-129.65 87.29-74.46 32.1-159.11 32.1Zm-260.5-601.91q-27.67 0-47.04-19.54-19.37-19.53-19.37-47.2t19.37-47.04q19.37-19.37 47.04-19.37 27.67 0 47.2 19.37 19.54 19.37 19.54 47.04 0 27.67-19.54 47.2-19.53 19.54-47.2 19.54ZM480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_clock.xml b/apps/android/design/src/main/res/drawable/sf_clock.xml
new file mode 100644
index 00000000..b9270cb1
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_clock.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `schedule`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M523.59-497.91v-137.31q0-18.52-12.53-31.05Q498.52-678.8 480-678.8t-31.06 12.53q-12.53 12.53-12.53 31.05v153.5q0 9.2 3.36 17.55 3.36 8.36 10.08 15.04l128.17 128.17q12.2 12.2 30.39 12.2 18.2 0 30.63-12.2 12.44-12.19 12.44-30.63 0-18.43-12.44-30.87L523.59-497.91ZM480-71.87q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87ZM480-480Zm0 317.13q131.8 0 224.47-92.54 92.66-92.55 92.66-224.59 0-132.04-92.66-224.59-92.66-92.54-224.47-92.54-131.8 0-224.47 92.54-92.66 92.55-92.66 224.59 0 132.04 92.66 224.59 92.66 92.54 224.47 92.54Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_clock_arrow_circlepath.xml b/apps/android/design/src/main/res/drawable/sf_clock_arrow_circlepath.xml
new file mode 100644
index 00000000..a5522571
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_clock_arrow_circlepath.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `history`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M479.52-111.87q-127.67 0-226.35-76.98-98.67-76.98-129.34-196.93-4.72-16.92 6.71-30.97 11.44-14.05 30.59-16.53 18.15-2.48 33.19 6.6 15.03 9.07 20.75 26.75 25.19 87.13 98.4 142.09 73.2 54.97 166.05 54.97 115.81 0 196.47-80.66Q756.65-364.2 756.65-480t-80.66-196.47q-80.66-80.66-196.47-80.66-66.13 0-124.22 29.97-58.08 29.96-98.37 83.09h61.4q17.71 0 29.81 12.1 12.1 12.1 12.1 29.82t-12.1 29.93Q336.04-560 318.33-560H159.28q-19.15 0-32.32-13.17-13.18-13.18-13.18-32.33v-158.8q0-17.72 12.1-29.7t29.82-11.98q17.71 0 29.69 11.98t11.98 29.7v48.73q52.2-63.52 125.93-98.04 73.74-34.52 156.22-34.52 76.44 0 143.49 29.1 67.06 29.1 116.75 78.79 49.7 49.7 78.79 116.75 29.1 67.06 29.1 143.49t-29.1 143.49q-29.09 67.05-78.79 116.75-49.69 49.69-116.75 78.79-67.05 29.1-143.49 29.1ZM521.91-496l97.85 97.61q11.72 11.72 11.72 29.43 0 17.72-11.72 29.44-11.72 11.72-29.43 11.72-17.72 0-29.44-11.72L451.76-448.65q-6.72-6.72-10.08-15.06-3.35-8.33-3.35-17.53v-157.09q0-17.71 12.09-29.69Q462.52-680 480.24-680t29.69 11.98q11.98 11.98 11.98 29.69V-496Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_clock_fill.xml b/apps/android/design/src/main/res/drawable/sf_clock_fill.xml
new file mode 100644
index 00000000..69ca3f87
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_clock_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `schedule` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M523.59-497.91v-137.31q0-18.52-12.53-31.05Q498.52-678.8 480-678.8t-31.06 12.53q-12.53 12.53-12.53 31.05v153.5q0 9.2 3.36 17.55 3.36 8.36 10.08 15.04l128.17 128.17q12.2 12.2 30.39 12.2 18.2 0 30.63-12.2 12.44-12.19 12.44-30.63 0-18.43-12.44-30.87L523.59-497.91ZM480-71.87q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_cloud.xml b/apps/android/design/src/main/res/drawable/sf_cloud.xml
new file mode 100644
index 00000000..451e6e69
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_cloud.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `cloud`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M260.72-151.87q-94.37 0-161.25-65.15T32.59-376.28q0-80.39 47.36-143.67 47.35-63.27 125.03-80.75 26.43-92.95 102.63-150.19Q383.8-808.13 480-808.13q118.2 0 201.25 81.74t85.68 199.69q69.72 10.63 115.1 63.81 45.38 53.17 45.38 123.61 0 78.09-54.66 132.75T740-151.87H260.72Zm0-91h478.56q40.57 0 68.85-28.28 28.28-28.28 28.28-68.85 0-40.57-28.28-68.85-28.28-28.28-68.85-28.28h-62.87v-83.59q0-81.51-57.45-138.96T480-717.13q-82.04 0-139.23 58.74-57.18 58.74-57.18 141.26h-22.87q-56.81 0-96.97 40.16T123.59-380q0 56.8 40.16 96.97 40.16 40.16 96.97 40.16ZM480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_cloud_sun_fill.xml b/apps/android/design/src/main/res/drawable/sf_cloud_sun_fill.xml
new file mode 100644
index 00000000..66a2db67
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_cloud_sun_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `partly_cloudy_day` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m731.37-163.98-56-57q-12.67-13.67-12.67-32.44 0-18.78 12.67-31.45 12.67-12.67 31.45-12.67 18.77 0 32.2 12.67l57 56q13.68 13.67 13.68 32.45 0 18.77-13.68 32.44-13.67 13.68-32.44 13.68-18.78 0-32.21-13.68ZM240-154.26q-68.63 0-117.18-48.56Q74.26-251.37 74.26-320q0-68.39 48.67-116.83 48.68-48.43 117.07-48.43 49.67 0 91.49 26.72 41.81 26.71 60.77 73.15l8.57 19.41h19.45q44.39 0 74.69 30.8 30.29 30.79 30.29 75.18 0 44.15-30.79 74.95-30.8 30.79-74.95 30.79H240ZM603.78-277.5q-5.67-62.76-47.41-108.4-41.74-45.64-104.26-57.36-31-53.76-83.26-85.26-52.26-31.5-114.55-36.5 26.48-70.37 88.29-111.72 61.8-41.35 137.41-41.35 99.28 0 168.68 69.41 69.41 69.4 69.41 168.68 0 62.61-30.21 116.43-30.21 53.83-84.1 86.07Zm198.13-157q-19.15 0-32.32-13.17-13.18-13.18-13.18-32.33t13.18-32.33q13.17-13.17 32.32-13.17h80q19.16 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.17 13.17-32.33 13.17h-80ZM220.98-675.37l-57-57q-12.68-12.67-12.68-31.83 0-19.15 12.68-31.82 13.67-13.68 32.44-13.68 18.78 0 32.21 13.68l56 57q12.67 13.43 12.67 32.2 0 18.78-12.67 31.45-12.67 12.67-31.83 12.67-19.15 0-31.82-12.67Zm454.39 0q-12.67-12.67-12.67-31.45 0-18.77 12.67-32.2l56-57q13.43-13.68 32.21-13.68 18.77 0 32.44 13.68 12.68 12.67 12.68 31.82 0 19.16-12.68 31.83l-57 57q-12.67 12.67-31.82 12.67-19.16 0-31.83-12.67ZM480-756.41q-19.15 0-32.33-13.18-13.17-13.17-13.17-32.32v-80q0-19.16 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.17 13.17 32.33v80q0 19.15-13.17 32.32-13.18 13.18-32.33 13.18Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_command.xml b/apps/android/design/src/main/res/drawable/sf_command.xml
new file mode 100644
index 00000000..3b10678a
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_command.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keyboard_command_key`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M260.09-114.5q-60.24 0-102.92-42.63-42.67-42.64-42.67-102.95t42.67-102.87Q199.85-405.5 260-405.5h54.5v-149H260q-60.15 0-102.83-42.63-42.67-42.64-42.67-102.95t42.63-102.87q42.64-42.55 102.95-42.55t102.87 42.61Q405.5-760.28 405.5-700v54.5h149V-700q0-60.28 42.63-102.89 42.64-42.61 102.95-42.61t102.87 42.58q42.55 42.59 42.55 102.83 0 60.24-42.61 102.92Q760.28-554.5 700-554.5h-54.5v149H700q60.28 0 102.89 42.58 42.61 42.59 42.61 102.83 0 60.24-42.58 102.92-42.59 42.67-102.83 42.67-60.24 0-102.92-42.67Q554.5-199.85 554.5-260v-54.5h-149v54.5q0 60.15-42.58 102.83-42.59 42.67-102.83 42.67Zm.01-91q22.75 0 38.57-15.9 15.83-15.89 15.83-38.6v-54.5H260q-22.71 0-38.6 15.88-15.9 15.87-15.9 38.55t15.92 38.62q15.93 15.95 38.68 15.95Zm440 0q22.75 0 38.57-15.92 15.83-15.93 15.83-38.68t-15.83-38.57q-15.82-15.83-38.57-15.83h-54.6v54.43q0 22.68 15.92 38.62 15.93 15.95 38.68 15.95Zm-294.6-200h149v-149h-149v149ZM260-645.5h54.5v-54.6q0-22.75-15.88-38.57-15.87-15.83-38.55-15.83t-38.62 15.88q-15.95 15.87-15.95 38.55t15.9 38.62q15.89 15.95 38.6 15.95Zm385.5 0h54.6q22.75 0 38.57-15.92 15.83-15.93 15.83-38.68t-15.88-38.57q-15.87-15.83-38.55-15.83t-38.62 15.83q-15.95 15.82-15.95 38.57v54.6Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_control.xml b/apps/android/design/src/main/res/drawable/sf_control.xml
new file mode 100644
index 00000000..4da55306
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_control.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keyboard_control_key`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-639.35 287.83-448.17q-12.68 12.67-31.45 13.05-18.77.38-32.21-13.05Q211.5-460.85 211.5-480t12.67-31.83l223.76-223.76q13.68-13.67 32.07-13.67t32.07 13.67l223.76 223.76q12.67 12.68 13.05 31.45.38 18.77-13.05 32.21Q723.15-435.5 704-435.5t-31.83-12.67L480-639.35Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_crop.xml b/apps/android/design/src/main/res/drawable/sf_crop.xml
new file mode 100644
index 00000000..be4d81cf
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_crop.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `crop`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M674.5-83.59V-194.5h-389q-37.78 0-64.39-26.61T194.5-285.5v-389H83.59q-19.16 0-32.33-13.17Q38.09-700.85 38.09-720t13.17-32.33q13.17-13.17 32.33-13.17H194.5v-110.91q0-19.16 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.17 13.17 32.33v590.91h590.91q19.16 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.17 13.17-32.33 13.17H765.5v110.91q0 19.16-13.17 32.33Q739.15-38.09 720-38.09t-32.33-13.17Q674.5-64.43 674.5-83.59Zm0-281.91v-309h-309v-91h309q37.78 0 64.39 26.61t26.61 64.39v309h-91Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_cursorarrow_motionlines.xml b/apps/android/design/src/main/res/drawable/sf_cursorarrow_motionlines.xml
new file mode 100644
index 00000000..9b48f0b7
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_cursorarrow_motionlines.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `arrow_selector_tool`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m321.91-419.09 75.42-104.98h164.26L321.91-712.65v293.56ZM613.89-87.78q-24.43 11.72-49.11 2.5-24.67-9.22-36.39-33.65L406.48-380.52l-92.76 129.76q-19.39 27.35-51.1 17.15-31.71-10.19-31.71-43.26v-529.02q0-28.59 25.61-41.02 25.61-12.44 48.24 5.47l416.2 327.33q25.87 19.63 15.17 50.34-10.69 30.7-43.52 30.7H523.89l121.15 259.55q11.72 24.43 2.5 49.23-9.21 24.79-33.65 36.51ZM397.33-524.07Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_desktopcomputer.xml b/apps/android/design/src/main/res/drawable/sf_desktopcomputer.xml
new file mode 100644
index 00000000..bca76ea3
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_desktopcomputer.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `desktop_mac`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M395.7-235.46H162.87q-37.78 0-64.39-26.61-26.61-26.6-26.61-64.39v-430.67q0-37.78 26.61-64.39t64.39-26.61h634.26q37.78 0 64.39 26.61t26.61 64.39v430.67q0 37.79-26.61 64.39-26.61 26.61-64.39 26.61H564.3l73.54 73.54q1.99 1.99 6.46 15.06v13.08q0 8.71-6.5 15.31t-15.17 6.6H330.89q-6.51 0-10.85-4.37-4.34-4.36-4.34-10.91v-21.83q0-2 4.47-10.95l75.53-75.53ZM162.87-437.13h634.26v-320H162.87v320Zm0 0v-320 320Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_desktopcomputer_trianglebadge_exclamationmark.xml b/apps/android/design/src/main/res/drawable/sf_desktopcomputer_trianglebadge_exclamationmark.xml
new file mode 100644
index 00000000..8b3b8c67
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_desktopcomputer_trianglebadge_exclamationmark.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `desktop_access_disabled`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m124.13-839.46 82.33 82.33h-43.59v430.67h357.24L52.17-794.39q-11.71-11.72-11.71-29.2 0-17.48 11.71-29.19 11.72-11.72 29.32-11.72t29.31 11.72l742.22 742.21q11.72 11.72 11.6 29.2-.12 17.48-11.84 29.2-11.71 11.71-29.19 11.71t-29.2-11.71L611.11-235.46h-47.52v80h34.5q19.15 0 32.32 13.18 13.18 13.17 13.18 32.32 0 19.16-13.18 32.33-13.17 13.17-32.32 13.17H361.91q-19.15 0-32.32-13.17-13.18-13.17-13.18-32.33 0-19.15 13.18-32.32 13.17-13.18 32.32-13.18h34.5v-80H162.87q-37.78 0-64.39-26.61-26.61-26.6-26.61-64.39v-430.67q0-41.3 26.13-61.82l26.13-20.51Zm764 82.33v408.76q0 22.75-14.18 34.13-14.19 11.37-31.21 11.37-17.02 0-31.32-11.7-14.29-11.69-14.29-34.56v-408h-429q-22.75 0-34.12-14.24-11.38-14.24-11.38-31.33 0-17.08 11.38-31.26 11.37-14.17 34.12-14.17h429q37.78 0 64.39 26.61t26.61 64.39ZM558.67-518.67ZM341.61-505.2Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_display.xml b/apps/android/design/src/main/res/drawable/sf_display.xml
new file mode 100644
index 00000000..4de72dc3
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_display.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `monitor`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M162.87-235.7q-37.78 0-64.39-26.6-26.61-26.61-26.61-64.4v-430.43q0-37.78 26.61-64.39t64.39-26.61h634.26q37.78 0 64.39 26.61t26.61 64.39v430.43q0 37.79-26.61 64.4-26.61 26.6-64.39 26.6H680l30.15 30.4q6.72 6.68 10.08 15.03 3.36 8.36 3.36 17.55v17.5q0 18.43-12.47 30.89-12.46 12.46-30.88 12.46H279.76q-18.42 0-30.88-12.46-12.47-12.46-12.47-30.89v-17.5q0-9.19 3.36-17.55 3.36-8.35 10.08-15.03L280-235.7H162.87Zm0-91h634.26v-430.43H162.87v430.43Zm0 0v-430.43 430.43Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_display_2.xml b/apps/android/design/src/main/res/drawable/sf_display_2.xml
new file mode 100644
index 00000000..a4a57c93
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_display_2.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `desktop_windows`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M396.41-202.87v-80H162.87q-37.78 0-64.39-26.61t-26.61-64.39v-383.02q0-37.78 26.61-64.39t64.39-26.61h634.26q37.78 0 64.39 26.61t26.61 64.39v383.02q0 37.78-26.61 64.39t-64.39 26.61H563.59v80h34.5q19.15 0 32.32 13.17 13.18 13.18 13.18 32.33t-13.18 32.33q-13.17 13.17-32.32 13.17H361.91q-19.15 0-32.32-13.17-13.18-13.18-13.18-32.33t13.18-32.33q13.17-13.17 32.32-13.17h34.5Zm-233.54-171h634.26v-383.02H162.87v383.02Zm0 0v-383.02 383.02Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_doc.xml b/apps/android/design/src/main/res/drawable/sf_doc.xml
new file mode 100644
index 00000000..f765ebdd
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_doc.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `draft`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M242.87-71.87q-37.78 0-64.39-26.61t-26.61-64.39v-634.26q0-37.78 26.61-64.39t64.39-26.61H525.8q18.22 0 34.72 6.84 16.5 6.83 29.18 19.51L781.78-669.7q12.68 12.68 19.51 29.18 6.84 16.5 6.84 34.72v442.93q0 37.78-26.61 64.39t-64.39 26.61H242.87Zm274.26-570.76v-154.5H242.87v634.26h474.26v-434.26h-154.5q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33Zm-274.26-154.5V-597.13v-200 634.26-634.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_doc_badge_plus.xml b/apps/android/design/src/main/res/drawable/sf_doc_badge_plus.xml
new file mode 100644
index 00000000..9d0856dc
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_doc_badge_plus.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `note_add`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M440-357.37v80q0 17 11.5 28.5t28.5 11.5q17 0 28.5-11.5t11.5-28.5v-80h80q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5h-80v-80q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5v80h-80q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5h80ZM242.87-71.87q-37.78 0-64.39-26.61t-26.61-64.39v-634.26q0-37.78 26.61-64.39t64.39-26.61H525.8q18.22 0 34.72 6.84 16.5 6.83 29.18 19.51L781.78-669.7q12.68 12.68 19.51 29.18 6.84 16.5 6.84 34.72v442.93q0 37.78-26.61 64.39t-64.39 26.61H242.87Zm274.26-570.76v-154.5H242.87v634.26h474.26v-434.26h-154.5q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33Zm-274.26-154.5V-597.13v-200 634.26-634.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_doc_on_clipboard.xml b/apps/android/design/src/main/res/drawable/sf_doc_on_clipboard.xml
new file mode 100644
index 00000000..3786508b
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_doc_on_clipboard.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `content_paste`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M202.87-111.87q-37.54 0-64.27-26.73-26.73-26.73-26.73-64.27v-554.26q0-37.54 26.73-64.27 26.73-26.73 64.27-26.73h157.91q12.44-35.72 45.94-58.46 33.5-22.74 73.28-22.74 41.2 0 74.37 22.74t45.85 58.46h156.91q37.54 0 64.27 26.73 26.73 26.73 26.73 64.27v554.26q0 37.54-26.73 64.27-26.73 26.73-64.27 26.73H202.87Zm0-91h554.26v-554.26H678.8v78.33q0 19.15-13.17 32.32-13.17 13.18-32.33 13.18H326.7q-19.16 0-32.33-13.18-13.17-13.17-13.17-32.32v-78.33h-78.33v554.26ZM480-760.72q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_doc_on_clipboard_fill.xml b/apps/android/design/src/main/res/drawable/sf_doc_on_clipboard_fill.xml
new file mode 100644
index 00000000..3586323e
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_doc_on_clipboard_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `content_paste` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M202.87-111.87q-37.54 0-64.27-26.73-26.73-26.73-26.73-64.27v-554.26q0-37.54 26.73-64.27 26.73-26.73 64.27-26.73h157.91q12.44-35.72 45.94-58.46 33.5-22.74 73.28-22.74 41.2 0 74.37 22.74t45.85 58.46h156.91q37.54 0 64.27 26.73 26.73 26.73 26.73 64.27v554.26q0 37.54-26.73 64.27-26.73 26.73-64.27 26.73H202.87Zm0-91h554.26v-554.26H678.8v78.33q0 19.15-13.17 32.32-13.17 13.18-32.33 13.18H326.7q-19.16 0-32.33-13.18-13.17-13.17-13.17-32.32v-78.33h-78.33v554.26ZM480-760.72q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_doc_on_doc.xml b/apps/android/design/src/main/res/drawable/sf_doc_on_doc.xml
new file mode 100644
index 00000000..c2733c7e
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_doc_on_doc.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `content_copy`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M368.37-237.37q-37.78 0-64.39-26.61t-26.61-64.39v-474.26q0-37.78 26.61-64.39t64.39-26.61h354.26q37.78 0 64.39 26.61t26.61 64.39v474.26q0 37.78-26.61 64.39t-64.39 26.61H368.37Zm0-91h354.26v-474.26H368.37v474.26Zm-171 262q-37.78 0-64.39-26.61t-26.61-64.39v-519.76q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v519.76h399.76q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H197.37Zm171-262v-474.26 474.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_doc_richtext.xml b/apps/android/design/src/main/res/drawable/sf_doc_richtext.xml
new file mode 100644
index 00000000..aa0e35f6
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_doc_richtext.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `article`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M202.87-111.87q-37.78 0-64.39-26.61t-26.61-64.39v-554.26q0-37.78 26.61-64.39t64.39-26.61h554.26q37.78 0 64.39 26.61t26.61 64.39v554.26q0 37.78-26.61 64.39t-64.39 26.61H202.87Zm0-91h554.26v-554.26H202.87v554.26Zm0-554.26v554.26-554.26Zm118.56 475.7h200q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5h-200q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm0-158.57h317.14q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5H321.43q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm0-158.57h317.14q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5H321.43q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_doc_text.xml b/apps/android/design/src/main/res/drawable/sf_doc_text.xml
new file mode 100644
index 00000000..d524a41f
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_doc_text.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `description`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M361.91-239.28h236.42q17.71 0 29.69-12.05T640-281.2q0-17.71-11.98-29.69t-29.69-11.98H361.67q-17.71 0-29.69 11.98Q320-298.9 320-281.19t12.05 29.81q12.05 12.1 29.86 12.1Zm0-160h236.42q17.71 0 29.69-12.05T640-441.2q0-17.71-11.98-29.69t-29.69-11.98H361.67q-17.71 0-29.69 11.98Q320-458.9 320-441.19t12.05 29.81q12.05 12.1 29.86 12.1ZM242.87-71.87q-37.78 0-64.39-26.61t-26.61-64.39v-634.26q0-37.78 26.61-64.39t64.39-26.61H525.8q18.22 0 34.72 6.84 16.5 6.83 29.18 19.51L781.78-669.7q12.68 12.68 19.51 29.18 6.84 16.5 6.84 34.72v442.93q0 37.78-26.61 64.39t-64.39 26.61H242.87Zm274.26-570.76v-154.5H242.87v634.26h474.26v-434.26h-154.5q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33Zm-274.26-154.5V-597.13v-200 634.26-634.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_doc_zipper.xml b/apps/android/design/src/main/res/drawable/sf_doc_zipper.xml
new file mode 100644
index 00000000..41594894
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_doc_zipper.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `folder_zip`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M635.46-476.89v-78.33h91v78.33h-91Zm0 78.09h-91v-78.09h91v78.09Zm0 78.08v-78.08h91v78.08h-91Zm-193-312.82-83.59-83.59h-196v474.26h381.59v-77.85h91v77.85h161.67v-390.67H635.46v78.32h-91v-78.32h-102ZM162.87-151.87q-37.78 0-64.39-26.61t-26.61-64.39v-474.26q0-37.78 26.61-64.39t64.39-26.61h196q18.21 0 34.71 6.84 16.51 6.83 29.18 19.51L480-724.54h317.13q37.78 0 64.39 26.61 26.61 26.6 26.61 64.39v390.67q0 37.78-26.61 64.39t-64.39 26.61H162.87Zm0-91v-474.26 474.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_ellipsis.xml b/apps/android/design/src/main/res/drawable/sf_ellipsis.xml
new file mode 100644
index 00000000..5a570b6c
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_ellipsis.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `more_horiz`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M232.69-396.41q-34.54 0-59.11-24.56Q149-445.52 149-480q0-34.67 24.55-59.13 24.56-24.46 59.04-24.46 34.58 0 59.2 24.46 24.62 24.46 24.62 59.01t-24.59 59.13q-24.6 24.58-59.13 24.58Zm247.43 0q-34.55 0-59.13-24.56-24.58-24.55-24.58-59.03 0-34.67 24.56-59.13 24.55-24.46 59.03-24.46 34.67 0 59.13 24.46t24.46 59.01q0 34.55-24.46 59.13-24.46 24.58-59.01 24.58Zm247.36 0q-34.61 0-59.25-24.56-24.64-24.55-24.64-59.03 0-34.67 24.64-59.13t59.25-24.46q34.61 0 59.06 24.46Q811-514.67 811-480.12t-24.46 59.13q-24.45 24.58-59.06 24.58Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_envelope_fill.xml b/apps/android/design/src/main/res/drawable/sf_envelope_fill.xml
new file mode 100644
index 00000000..df18fe47
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_envelope_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `mail` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M162.87-151.87q-37.78 0-64.39-26.61t-26.61-64.39v-474.26q0-37.78 26.61-64.39t64.39-26.61h634.26q37.78 0 64.39 26.61t26.61 64.39v474.26q0 37.78-26.61 64.39t-64.39 26.61H162.87ZM480-437.91q5.96 0 12.17-1.74 6.22-1.74 11.94-5.22L779.7-618.76q8.23-5 12.83-13.22t4.6-18.17q0-21.44-18.55-32.51-18.56-11.08-38.23 1.12L480-517.13 219.65-681.54q-19.43-11.96-38.11-.86-18.67 11.1-18.67 32.25 0 10.95 4.6 19.05 4.6 8.1 12.83 12.34l275.59 173.89q5.72 3.48 11.94 5.22 6.21 1.74 12.17 1.74Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_escape.xml b/apps/android/design/src/main/res/drawable/sf_escape.xml
new file mode 100644
index 00000000..195ce5a6
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_escape.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keyboard_return`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m284.91-434.5 106.68 106.67q12.67 12.68 12.67 31.83t-12.67 31.83q-12.68 12.67-31.83 12.67t-31.83-12.67l-184-183.76q-6.71-6.72-9.81-14.92-3.1-8.19-3.1-17.15 0-8.96 3.1-17.15 3.1-8.2 9.81-14.92l184-183.76q12.68-12.67 31.83-12.67t31.83 12.67q12.67 12.68 12.67 31.83t-12.67 31.83L284.91-525.5h472.22V-640q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v114.5q0 37.78-26.61 64.39t-64.39 26.61H284.91Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_exclamationmark.xml b/apps/android/design/src/main/res/drawable/sf_exclamationmark.xml
new file mode 100644
index 00000000..a889932e
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_exclamationmark.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `priority_high`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M479.96-107.09q-36.07 0-61.72-25.68-25.65-25.69-25.65-61.77 0-36.07 25.68-61.72 25.69-25.65 61.77-25.65 36.07 0 61.72 25.69 25.65 25.68 25.65 61.76 0 36.07-25.69 61.72-25.68 25.65-61.76 25.65Zm.16-254.82q-34.55 0-59.13-24.56-24.58-24.55-24.58-59.03v-321.91q0-34.48 24.46-59.04Q445.33-851 479.88-851t59.13 24.55q24.58 24.56 24.58 59.04v321.91q0 34.48-24.46 59.03-24.46 24.56-59.01 24.56Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_exclamationmark_circle.xml b/apps/android/design/src/main/res/drawable/sf_exclamationmark_circle.xml
new file mode 100644
index 00000000..98d64f01
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_exclamationmark_circle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `error`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M479.95-271.87q19.92 0 33.45-13.48 13.53-13.48 13.53-33.4 0-19.92-13.47-33.58-13.48-13.65-33.41-13.65-19.92 0-33.45 13.65-13.53 13.66-13.53 33.58 0 19.92 13.47 33.4 13.48 13.48 33.41 13.48Zm.05-167.65q19.15 0 32.33-13.18 13.17-13.17 13.17-32.32v-154.5q0-19.15-13.17-32.33-13.18-13.17-32.33-13.17t-32.33 13.17q-13.17 13.18-13.17 32.33v154.5q0 19.15 13.17 32.32 13.18 13.18 32.33 13.18Zm0 367.65q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Zm0-91q133.04 0 225.09-92.04 92.04-92.05 92.04-225.09 0-133.04-92.04-225.09-92.05-92.04-225.09-92.04-133.04 0-225.09 92.04-92.04 92.05-92.04 225.09 0 133.04 92.04 225.09 92.05 92.04 225.09 92.04ZM480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_exclamationmark_circle_fill.xml b/apps/android/design/src/main/res/drawable/sf_exclamationmark_circle_fill.xml
new file mode 100644
index 00000000..2e87a6ce
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_exclamationmark_circle_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `error` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M479.95-271.87q19.92 0 33.45-13.48 13.53-13.48 13.53-33.4 0-19.92-13.47-33.58-13.48-13.65-33.41-13.65-19.92 0-33.45 13.65-13.53 13.66-13.53 33.58 0 19.92 13.47 33.4 13.48 13.48 33.41 13.48Zm.05-167.65q19.15 0 32.33-13.18 13.17-13.17 13.17-32.32v-154.5q0-19.15-13.17-32.33-13.18-13.17-32.33-13.17t-32.33 13.17q-13.17 13.18-13.17 32.33v154.5q0 19.15 13.17 32.32 13.18 13.18 32.33 13.18Zm0 367.65q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_exclamationmark_triangle.xml b/apps/android/design/src/main/res/drawable/sf_exclamationmark_triangle.xml
new file mode 100644
index 00000000..facf8fb6
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_exclamationmark_triangle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `warning`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M111.63-115.93q-12.67 0-22.89-6.29T72.85-138.8q-5.72-10.2-6.22-22.16t6.22-23.34L440.22-820q6.71-11.43 17.55-17.03 10.84-5.6 22.25-5.6t22.23 5.6q10.82 5.6 17.53 17.03l367.37 635.7q6.72 11.38 6.22 23.34-.5 11.96-6.22 22.16-5.72 10.19-15.91 16.53-10.2 6.34-22.87 6.34H111.63Zm72.35-87.42h592.04L480-713.3 183.98-203.35ZM480-240.72q17.24 0 29.22-11.98 11.98-11.97 11.98-29.21 0-17.24-11.98-29.1-11.98-11.86-29.22-11.86t-29.22 11.86q-11.98 11.86-11.98 29.1 0 17.24 11.98 29.21 11.98 11.98 29.22 11.98ZM480-360q17 0 28.5-11.5T520-400v-117.37q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5V-400q0 17 11.5 28.5T480-360Zm0-98.33Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_exclamationmark_triangle_fill.xml b/apps/android/design/src/main/res/drawable/sf_exclamationmark_triangle_fill.xml
new file mode 100644
index 00000000..45afdb4a
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_exclamationmark_triangle_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `warning` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M111.63-115.93q-12.67 0-22.89-6.29T72.85-138.8q-5.72-10.2-6.22-22.16t6.22-23.34L440.22-820q6.71-11.43 17.55-17.03 10.84-5.6 22.25-5.6t22.23 5.6q10.82 5.6 17.53 17.03l367.37 635.7q6.72 11.38 6.22 23.34-.5 11.96-6.22 22.16-5.72 10.19-15.91 16.53-10.2 6.34-22.87 6.34H111.63ZM480-240.72q17.24 0 29.22-11.98 11.98-11.97 11.98-29.21 0-17.24-11.98-29.1-11.98-11.86-29.22-11.86t-29.22 11.86q-11.98 11.86-11.98 29.1 0 17.24 11.98 29.21 11.98 11.98 29.22 11.98ZM480-360q17 0 28.5-11.5T520-400v-117.37q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5V-400q0 17 11.5 28.5T480-360Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_eye.xml b/apps/android/design/src/main/res/drawable/sf_eye.xml
new file mode 100644
index 00000000..c6265af3
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_eye.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `visibility`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-320q75 0 127.5-52.5T660-500q0-75-52.5-127.5T480-680q-75 0-127.5 52.5T300-500q0 75 52.5 127.5T480-320Zm.04-77.02q-42.89 0-72.95-30.02-30.07-30.03-30.07-72.92t30.02-72.95q30.03-30.07 72.92-30.07t72.95 30.02q30.07 30.03 30.07 72.92t-30.02 72.95q-30.03 30.07-72.92 30.07ZM480-192.59q-135.43 0-247.37-72.48Q120.7-337.54 56.22-456.98q-5.72-10.19-8.46-21.01-2.74-10.81-2.74-22.01 0-11.2 2.74-22.01 2.74-10.82 8.46-21.01 64.48-119.44 176.41-191.91Q344.57-807.41 480-807.41t247.37 72.48q111.93 72.47 176.41 191.91 5.72 10.19 8.46 21.01 2.74 10.81 2.74 22.01 0 11.2-2.74 22.01-2.74 10.82-8.46 21.01-64.48 119.44-176.41 191.91Q615.43-192.59 480-192.59ZM480-500Zm.02 220q112.74 0 207-59.62T831.28-500q-50-100.76-144.28-160.38Q592.72-720 479.98-720q-112.74 0-207 59.62T128.72-500q50 100.76 144.28 160.38Q367.28-280 480.02-280Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_eye_slash.xml b/apps/android/design/src/main/res/drawable/sf_eye_slash.xml
new file mode 100644
index 00000000..68725259
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_eye_slash.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `visibility_off`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M607-627q25.65 25.65 38.79 58.95 13.14 33.29 11.78 68.46 0 16.68-11.96 28.25-11.96 11.58-28.63 11.58-16.68 0-28.25-11.58-11.58-11.57-11.58-28.25 4.28-21.45-2.28-41.03-6.57-19.58-20.7-33.71-14.13-14.13-33.7-21.57-19.58-7.45-42.03-3.17-16.2 0-27.66-11.95-11.45-11.96-11.45-28.15 0-16.2 11.45-27.66 11.46-11.45 27.66-11.45 34.89-1.85 68.3 11.29Q580.15-653.85 607-627Zm-127-93q-16.85 0-32.82 1.26-15.96 1.26-32.05 4.54-18.43 2.77-33.49-6.19-15.05-8.96-20.29-26.63-5.24-17.68 4.1-33.63 9.33-15.96 27.01-18.96 21.56-4.28 43.39-6.04 21.82-1.76 44.15-1.76 138.67 0 253.85 73.07 115.17 73.08 175.89 197.23 4.24 8.72 6.48 18.06 2.24 9.33 2.24 19.05t-1.62 19.17q-1.62 9.46-5.86 18.18-17.76 38.56-43.19 72.49-25.42 33.92-55.99 62.68-12.71 12.44-30.27 10.44-17.55-2-28.75-16.72-11.19-14.72-9.81-32.77 1.38-18.06 14.1-30.49 22.32-22.28 41.13-48.09 18.8-25.8 33.32-54.89-50.48-100.76-144.62-160.38Q592.76-720 480-720Zm0 527.41q-135.43 0-247.99-72.98-112.55-72.97-177.03-192.65-5.48-9.43-8.22-20.01-2.74-10.57-2.74-21.77t2.24-21.51q2.24-10.32 7.72-20.51 19.52-39.28 45.54-74.83 26.02-35.54 58.83-65.3l-80.61-81.37Q66.02-776 66.4-793.1q.38-17.1 12.1-28.81 11.72-11.72 29.32-11.72 17.59 0 29.31 11.72l681.2 681.19q11.71 11.72 12.09 28.82.38 17.1-12.09 29.57-11.72 11.72-29.2 11.72-17.48 0-29.2-11.72l-134.5-132.74q-35.23 11.48-71.71 16.98t-73.72 5.5ZM219.85-621.37q-28.05 26-51.09 56.28-23.04 30.29-40.04 65.09 50 101 144.26 160.5Q367.24-280 480-280q18.8 0 36.85-2.26 18.04-2.26 36.85-5.02l-36-38q-9.81 2.76-18.85 4.02Q489.8-320 480-320q-75 0-127.5-52.5T300-500q0-9.8 1.14-18.85 1.14-9.04 3.66-18.85l-84.95-83.67Zm324.74 88.46Zm-157.94 78.58Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_figure_run.xml b/apps/android/design/src/main/res/drawable/sf_figure_run.xml
new file mode 100644
index 00000000..1e3f1459
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_figure_run.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `directions_run`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M516.41-80v-198.09l-78.26-74.5-29.08 129.63q-4.48 18.16-19.78 27.97-15.29 9.82-33.68 6.34l-196.57-39.76q-18.43-3.48-28.27-18.56-9.84-15.07-6.36-33.51 3.48-18.43 18.68-28.77 15.19-10.34 33.63-6.1l148.41 31.28 62.09-314.43-65.79 25.37v93.61q0 18.43-12.57 31.01-12.58 12.58-31.01 12.58-18.44 0-31.13-12.7-12.7-12.7-12.7-31.13v-120.33q0-13.91 7.58-24.84 7.57-10.94 20.25-16.66l134.72-57.28q35.71-15 52.45-19.74 16.74-4.74 30.98-4.74 22.2 0 40.67 11.72 18.48 11.72 30.2 30.43l40.48 64q20.28 32.81 52.82 56.97 32.55 24.16 75.83 32.4 18.43 3.48 31.01 16.68 12.58 13.19 12.58 31.63 0 18.43-12.7 30.63-12.69 12.19-30.37 9.72-53.28-8-99.44-32.55-46.17-24.54-78.93-60.63l-22.08 111.63 69.6 65.85q6.96 6.72 10.44 15.29 3.48 8.58 3.48 17.78V-80q0 18.43-12.58 31.01Q578.43-36.41 560-36.41t-31.01-12.58Q516.41-61.57 516.41-80Zm24.07-663.59q-34.68 0-59.25-24.57-24.58-24.58-24.58-59.25 0-34.68 24.58-59.13Q505.8-911 540.48-911q34.67 0 59.13 24.46 24.46 24.45 24.46 59.13 0 34.67-24.46 59.25-24.46 24.57-59.13 24.57Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_folder.xml b/apps/android/design/src/main/res/drawable/sf_folder.xml
new file mode 100644
index 00000000..c5215a81
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_folder.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `folder`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M162.87-151.87q-37.78 0-64.39-26.61t-26.61-64.39v-474.26q0-37.78 26.61-64.39t64.39-26.61h196q18.21 0 34.71 6.84 16.51 6.83 29.18 19.51L480-724.54h317.13q37.78 0 64.39 26.61 26.61 26.6 26.61 64.39v390.67q0 37.78-26.61 64.39t-64.39 26.61H162.87Zm0-91h634.26v-390.67H442.46l-83.59-83.59h-196v474.26Zm0 0v-474.26 474.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_function.xml b/apps/android/design/src/main/res/drawable/sf_function.xml
new file mode 100644
index 00000000..7ac9974f
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_function.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `function`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M209.52-112.35q-47.15 0-76.82-25.43-29.68-25.44-29.68-67.11 0-33.2 18.08-53.65Q139.17-279 166.85-279q26.67 0 45.13 18.2 18.45 18.19 18.45 44.1 0 4.53-.38 8.17-.38 3.64-1.14 8.16 5-.76 8.38-5.02 3.38-4.26 5.14-11.54l62.72-341.64H230.2q-18.2 0-30.66-12.45-12.45-12.46-12.45-30.65 0-18.2 12.45-30.66 12.46-12.45 30.66-12.45h91.15l20.28-106.83q8.44-43.26 41.21-69.89 32.77-26.63 78.36-26.63 46.39 0 76.06 26.96 29.67 26.95 29.67 67.87 0 31.67-18.07 52.13-18.08 20.45-45.75 20.45-26.68 0-45.13-18.19-18.46-18.2-18.46-44.87 0-4.52.38-8.17.38-3.64 1.14-8.16-5.76 1.52-8.88 5.4-3.12 3.88-4.88 11.17l-17.71 98.76h154.02q18.19 0 30.65 12.45 12.46 12.46 12.46 30.66 0 15.47-9.38 26.95-9.39 11.48-23.39 14.44l52.05 57.61 52.28-57.61q-14-2.96-23.5-14.44t-9.5-26.95q0-18.2 12.46-30.66 12.45-12.45 30.65-12.45h124.54q18.2 0 30.66 12.45 12.45 12.46 12.45 30.66 0 18.19-12.45 30.65-12.46 12.45-30.66 12.45h-22.24L683.04-439.52l107.87 119.28h22q18.2 0 30.66 12.46 12.45 12.45 12.45 30.65t-12.45 30.65q-12.46 12.46-30.66 12.46H688.37q-18.2 0-30.65-12.46-12.46-12.45-12.46-30.65 0-15.48 9.5-26.96t23.5-14.43l-52.28-58.37-52.28 58.37q14 2.95 23.5 14.43t9.5 26.96q0 18.2-12.46 30.65-12.46 12.46-30.65 12.46H439.04q-18.19 0-30.65-12.46-12.46-12.45-12.46-30.65t12.46-30.65q12.46-12.46 30.65-12.46h22.24l107.39-119.28-107.39-119.05h-67.91l-63.52 342.09q-9.2 48.59-40.83 76.36-31.63 27.77-79.5 27.77Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_gearshape.xml b/apps/android/design/src/main/res/drawable/sf_gearshape.xml
new file mode 100644
index 00000000..6e1b9409
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_gearshape.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `settings`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M428.46-71.87q-28.2 0-48.54-18.6-20.33-18.6-24.33-45.79l-9-66.24q-11.09-4.28-21.04-10.33-9.94-6.04-19.51-12.84l-61.76 26q-25.95 11.24-52.15 2.12-26.2-9.12-40.67-33.32l-51.55-90.37q-14.48-23.96-8.36-51.03 6.12-27.08 28.08-44.56l52.76-40q-.76-6.04-.76-11.58v-23.18q0-5.54.76-11.58l-52.76-39.76q-22.2-17.48-28.2-44.56-6-27.08 8.48-51.27l51.55-90.13q14.47-23.96 40.55-33.2 26.08-9.24 52.03 2l62.48 26q9.57-6.8 19.65-12.73 10.09-5.92 20.42-10.2l9-66.48q4-27.43 24.33-46.03 20.34-18.6 48.54-18.6h103.08q28.2 0 48.54 18.6 20.33 18.6 24.33 46.03l9 66.48q11.09 4.28 21.04 10.2 9.94 5.93 19.51 12.73l61.76-26q25.95-11.24 52.15-2t40.67 33.2l51.55 90.13q14.48 24.19 8.48 51.27-6 27.08-28.2 44.56l-53 39.76q.76 6.04.76 11.58V-480q0 6.04-.12 11.59-.12 5.54-1.64 11.58l53 39.76q22.2 17.48 28.2 44.56 6 27.08-8.48 51.27l-52.55 90.37q-14.47 23.96-40.55 33.2-26.08 9.24-52.03-2l-60.48-26q-9.57 6.8-19.65 12.84-10.09 6.05-20.42 10.33l-9 66.24q-4 27.19-24.33 45.79-20.34 18.6-48.54 18.6H428.46Zm14.17-91h73.5l14.24-105.52q31.24-8 58.34-23.62 27.09-15.62 49.09-38.58l98.77 41 36.13-63.69-85.29-64.52q5-14.48 7.24-30.22 2.24-15.74 2.24-31.98 0-16.24-2.24-31.98-2.24-15.74-7.24-30.22l85.76-64.52-36.6-63.69-98.53 42q-22-23.72-49.09-39.58-27.1-15.86-58.58-23.62l-13-105.52h-73.98l-13.52 105.28q-31.72 7.76-58.94 23.62-27.21 15.86-49.45 38.82l-98.28-41-36.37 63.69 85.04 63.29q-5 15.47-7.24 30.83-2.24 15.36-2.24 32.6 0 16.24 2.24 31.72t7.24 30.95l-85.04 64.05 36.37 63.69 98.28-41.76q22.24 23.48 49.57 39.34 27.34 15.86 58.82 23.86l12.76 105.28ZM481.28-340q58 0 99-41t41-99q0-58-41-99t-99-41q-58.76 0-99.38 41t-40.62 99q0 58 40.62 99t99.38 41ZM480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_gearshape_fill.xml b/apps/android/design/src/main/res/drawable/sf_gearshape_fill.xml
new file mode 100644
index 00000000..e7f93be8
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_gearshape_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `settings` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M428.46-71.87q-28.2 0-48.54-18.6-20.33-18.6-24.33-45.79l-9-66.24q-11.09-4.28-21.04-10.33-9.94-6.04-19.51-12.84l-61.76 26q-25.95 11.24-52.15 2.12-26.2-9.12-40.67-33.32l-51.55-90.37q-14.48-23.96-8.36-51.03 6.12-27.08 28.08-44.56l52.76-40q-.76-6.04-.76-11.58v-23.18q0-5.54.76-11.58l-52.76-39.76q-22.2-17.48-28.2-44.56-6-27.08 8.48-51.27l51.55-90.13q14.47-23.96 40.55-33.2 26.08-9.24 52.03 2l62.48 26q9.57-6.8 19.65-12.73 10.09-5.92 20.42-10.2l9-66.48q4-27.43 24.33-46.03 20.34-18.6 48.54-18.6h103.08q28.2 0 48.54 18.6 20.33 18.6 24.33 46.03l9 66.48q11.09 4.28 21.04 10.2 9.94 5.93 19.51 12.73l61.76-26q25.95-11.24 52.15-2t40.67 33.2l51.55 90.13q14.48 24.19 8.48 51.27-6 27.08-28.2 44.56l-53 39.76q.76 6.04.76 11.58V-480q0 6.04-.12 11.59-.12 5.54-1.64 11.58l53 39.76q22.2 17.48 28.2 44.56 6 27.08-8.48 51.27l-52.55 90.37q-14.47 23.96-40.55 33.2-26.08 9.24-52.03-2l-60.48-26q-9.57 6.8-19.65 12.84-10.09 6.05-20.42 10.33l-9 66.24q-4 27.19-24.33 45.79-20.34 18.6-48.54 18.6H428.46ZM481.28-340q58 0 99-41t41-99q0-58-41-99t-99-41q-58.76 0-99.38 41t-40.62 99q0 58 40.62 99t99.38 41Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_globe.xml b/apps/android/design/src/main/res/drawable/sf_globe.xml
new file mode 100644
index 00000000..21b7adf6
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_globe.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `language`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-71.87q-83.67 0-158.11-32.22-74.43-32.21-130.01-87.79-55.58-55.58-87.79-130.01Q71.87-396.33 71.87-480q0-84.43 32.22-158.49 32.21-74.05 87.79-129.63 55.58-55.58 130.01-87.79 74.44-32.22 158.11-32.22 84.43 0 158.49 32.22 74.05 32.21 129.63 87.79 55.58 55.58 87.79 129.63 32.22 74.06 32.22 158.49 0 83.67-32.22 158.11-32.21 74.43-87.79 130.01-55.58 55.58-129.63 87.79Q564.43-71.87 480-71.87Zm-.48-92.76q25.05-35.52 44.05-74.4 19-38.88 31-82.4H405.2q12 43.52 30.64 82.4t43.68 74.4Zm-102.8-16q-18.48-32.52-31.5-68.02-13.02-35.5-22.02-72.78H206.63q28.28 49.52 71.42 86.28 43.15 36.76 98.67 54.52Zm205.85 0q55.52-17.76 98.9-54.52 43.38-36.76 71.66-86.28H636.57q-9 37.28-22.27 72.78-13.26 35.5-31.73 68.02Zm-409.7-220.09H307.2q-3-20-4.5-39.26-1.5-19.26-1.5-40.02 0-21 1.5-40.14t4.5-39.14H172.87q-5 19.76-7.5 39.02t-2.5 40.26q0 20.76 2.5 40.14t7.5 39.14Zm214.33 0h185.37q3-20 4.26-39.26 1.26-19.26 1.26-40.02 0-21-1.26-40.14t-4.26-39.14H387.2q-3 20-4.5 39.14T381.2-480q0 20.76 1.5 40.02t4.5 39.26Zm265.37 0h134.08q5-19.76 7.5-39.14t2.5-40.14q0-21-2.5-40.26-2.5-19.26-7.5-39.02H652.57q2.76 20 4.14 39.14t1.38 40.14q0 20.76-1.38 40.02t-4.14 39.26Zm-16-238.08h116.56q-28.28-49.53-71.66-86.17-43.38-36.64-98.9-54.4 18.47 32.52 31.73 67.9 13.27 35.38 22.27 72.67Zm-231.37 0h149.37q-11.77-43.53-30.77-82.29-19-38.76-44.28-74.28-25.04 35.52-43.68 74.28T405.2-638.8Zm-198.57 0H323.2q9-37.29 22.02-72.67t31.5-67.9q-55.52 17.76-98.67 54.4-43.14 36.64-71.42 86.17Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_hand_point_up_left.xml b/apps/android/design/src/main/res/drawable/sf_hand_point_up_left.xml
new file mode 100644
index 00000000..1db46b48
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_hand_point_up_left.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `touch_app`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M411.59-71.87q-31.92 0-59.85-13.68-27.93-13.69-47.31-38.78l-198.6-252.84q-9.92-11.63-8.32-27.36 1.6-15.73 12.47-25.64l.95-.72q22.4-21.72 52.91-25.48 30.51-3.76 56.9 12.44l67.3 40.45V-721.2q0-18.67 12.82-31.48 12.81-12.82 31.5-12.82 18.68 0 31.87 12.82 13.18 12.81 13.18 31.48v394.5q0 26.35-23.13 39.29-23.13 12.93-46-.5l-36.95-22.24L375.8-177.63q6.72 7.96 15.87 12.55 9.15 4.6 19.44 4.6h232.72q31.22 0 53.46-22.23 22.23-22.24 22.23-53.46v-151.87q0-20.11-13.89-34t-34-13.89H501.72q-18.68 0-31.49-12.82-12.82-12.82-12.82-31.49 0-18.67 12.82-31.49 12.81-12.81 31.49-12.81h169.91q56.7 0 96.6 39.9 39.9 39.9 39.9 96.6v151.87q0 67.91-48.2 116.1-48.19 48.2-116.1 48.2H411.59Zm83.95-270.76ZM474.93-594.5q-18.67 0-31.48-12.82-12.82-12.81-12.82-31.48 0-3.2 5.72-22.16 8-14 12-28.5t4-31.5q0-50-35-85t-85-35q-50 0-85 35t-35 85q0 17 4 31.5t12 28.5q3.24 5.48 4.48 11 1.24 5.53 1.24 11.05 0 18.78-12.44 31.59-12.43 12.82-31.11 12.82-12.43 0-22.77-6.6t-16.05-16.79q-13.24-22.96-20.6-48.97-7.36-26.01-7.36-54.1 0-86.57 61.02-147.59 61.02-61.02 147.6-61.02 86.57 0 147.59 61.03 61.01 61.03 61.01 147.61 0 28.17-7.36 54.13-7.36 25.95-20.6 48.91-5.72 10.19-15.67 16.79-9.96 6.6-22.4 6.6Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_hand_raised.xml b/apps/android/design/src/main/res/drawable/sf_hand_raised.xml
new file mode 100644
index 00000000..47ffdc8a
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_hand_raised.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `front_hand`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M518.33-929.57q18.19 0 30.65 12.46 12.45 12.46 12.45 30.65v353.07q0 18.19-12.45 30.65-12.46 12.46-30.65 12.46-18.2 0-30.66-12.46-12.45-12.46-12.45-30.65v-353.07q0-18.19 12.45-30.65 12.46-12.46 30.66-12.46Zm-161.68 41.44q18.2 0 30.65 12.46 12.46 12.45 12.46 30.65v311.63q0 18.19-12.46 30.65-12.45 12.46-30.65 12.46-18.19 0-30.65-12.46-12.46-12.46-12.46-30.65v-311.63q0-18.2 12.46-30.65 12.46-12.46 30.65-12.46ZM500.03-31.87q-145.38 0-246.77-101.37Q151.87-234.6 151.87-380v-385.02q0-18.2 12.46-30.65 12.45-12.46 30.65-12.46 18.19 0 30.65 12.46 12.46 12.45 12.46 30.65V-380q0 109.8 76.04 185.86 76.03 76.05 185.81 76.05t185.88-76.05Q761.91-270.2 761.91-380v-136.89H760q-15.68 0-26.29 10.64-10.6 10.64-10.6 26.37v111.03q0 19.15-13.18 32.33-13.17 13.17-32.32 13.17H600q-31.72 0-54.3 22.59-22.59 22.59-22.59 54.3v40q0 18.2-12.46 30.66-12.45 12.45-30.65 12.45t-30.65-12.45q-12.46-12.46-12.46-30.66v-40q0-67.43 47.84-115.27 47.84-47.84 115.27-47.84h36.89v-395.45q0-18.2 12.46-30.65 12.45-12.46 30.65-12.46t30.65 12.46q12.46 12.45 12.46 30.65v207.95q9.28-2.76 18.02-4.4 8.75-1.64 18.87-1.64h42.63q19.15 0 32.33 13.18 13.17 13.17 13.17 32.32V-380q0 145.4-101.36 246.76Q645.42-31.87 500.03-31.87Zm43.08-328.85Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_hand_raised_fill.xml b/apps/android/design/src/main/res/drawable/sf_hand_raised_fill.xml
new file mode 100644
index 00000000..3e3bf444
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_hand_raised_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `front_hand` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M500-31.87q-145.35 0-246.74-101.39Q151.87-234.65 151.87-380v-385.02q0-18.2 12.46-30.65 12.45-12.46 30.65-12.46 18.19 0 30.65 12.46 12.46 12.45 12.46 30.65v248.13h75.45v-328.13q0-18.2 12.46-30.65 12.46-12.46 30.65-12.46 18.2 0 30.65 12.46 12.46 12.45 12.46 30.65v328.13h75.46v-369.57q0-18.19 12.45-30.65 12.46-12.46 30.66-12.46 18.19 0 30.65 12.46 12.45 12.46 12.45 30.65v369.57h75.46v-288.13q0-18.2 12.46-30.65 12.45-12.46 30.65-12.46t30.65 12.46q12.46 12.45 12.46 30.65v236.93q-31.63 20.76-48.21 54.44-16.57 33.67-16.57 71.06v39.24h-50.72q-62.52 0-105.9 43.38t-43.38 105.9v47.61q0 13.96 9.21 23.18 9.22 9.21 23.18 9.21 13.95 0 23.17-9.21 9.22-9.22 9.22-23.18v-47.61q0-35.6 24.44-60.05 24.45-24.45 60.06-24.45h70q19.15 0 32.32-13.17 13.18-13.17 13.18-32.33v-58.52q0-37.76 25.88-63.64 25.88-25.88 63.64-25.88 15.15 0 25.33 10.18 10.17 10.17 10.17 25.32V-380q0 145.35-101.39 246.74Q645.35-31.87 500-31.87Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_hand_raised_slash.xml b/apps/android/design/src/main/res/drawable/sf_hand_raised_slash.xml
new file mode 100644
index 00000000..d59520b9
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_hand_raised_slash.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `do_not_touch`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M761.91-338.65v-426.37q0-18.2 12.46-30.65 12.46-12.46 30.65-12.46 18.2 0 30.65 12.46 12.46 12.45 12.46 30.65v427.13q0 21.43-13.46 32.27-13.45 10.84-29.65 10.84-16.19 0-29.65-11.22-13.46-11.22-13.46-32.65ZM277.85-796.46v-28.08q0-18.2 12.57-30.66Q303-867.65 320-867.65q18.2 0 30.65 12.45 12.46 12.46 12.46 30.66v28.08q0 17.96-12.34 30.3-12.34 12.33-30.29 12.33-17.96 0-30.3-12.33-12.33-12.34-12.33-30.3Zm160.72 148.81v-238.81q0-18.19 12.45-30.65 12.46-12.46 30.65-12.46 18.2 0 30.66 12.46 12.45 12.46 12.45 30.65v239.57q0 18.19-12.45 30.27-12.46 12.08-30.66 11.84-18.19-.24-30.65-12.46-12.45-12.22-12.45-30.41ZM600.24-496.5v-348.52q0-18.2 12.46-30.65 12.45-12.46 30.65-12.46 18.19 0 30.65 12.46 12.46 12.45 12.46 30.65v348.52q0 18.2-12.46 30.65-12.46 12.46-30.65 12.46-18.2 0-30.65-12.46-12.46-12.45-12.46-30.65Zm118.67 369.61L363.11-482.7v135.77q0 27.34-24.37 40.4-24.37 13.05-47.24-2.86l-70.41-49.72 150.54 224.22q4.76 7.28 12.92 11.92 8.17 4.64 17.45 4.64h283.02q9.05 0 17.83-2.14 8.78-2.14 16.06-6.42ZM402-32.11q-30.72 0-57.55-13.86-26.84-13.86-44.08-39.57L65.8-437.04q-8-12.48-6.64-26.84 1.36-14.36 12.84-24.36 20.2-19 47.27-22.12 27.08-3.12 51.43 13.79l106.19 73.59v-145.93L55-790.8q-12.48-12.48-12.48-29.7T55-850.2q12.48-12.47 29.7-12.47 17.21 0 29.69 12.47l738.63 738.63q12.48 12.48 12.36 29.32-.12 16.84-12.84 29.55-12.47 12.48-29.33 12.48T793.87-52.7l-12.41-11.65q-20.24 15.24-44.6 23.74-24.36 8.5-51.84 8.5H402Zm139.39-273.06Zm68.65-166.4Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_heart_fill.xml b/apps/android/design/src/main/res/drawable/sf_heart_fill.xml
new file mode 100644
index 00000000..d19c47c5
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_heart_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `favorite` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M479.76-139.83q-16.15 0-32.44-5.83-16.3-5.84-28.97-18.27l-69.48-63.48Q243.35-323.7 157.61-420.03 71.87-516.37 71.87-634q0-97.59 65.15-162.98 65.15-65.39 162.74-65.39 52.52 0 99.28 21.42 46.76 21.43 80.72 59.47 33.96-38.04 80.72-59.47 46.76-21.42 99.28-21.42 97.59 0 163.1 65.39 65.51 65.39 65.51 162.98 0 117.63-85.6 214.47-85.6 96.83-193.12 193.36l-68.24 62.47q-12.67 12.44-29.08 18.16-16.42 5.71-32.57 5.71Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_info_circle.xml b/apps/android/design/src/main/res/drawable/sf_info_circle.xml
new file mode 100644
index 00000000..81efc005
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_info_circle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `info`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-276.41q18.52 0 31.06-12.53 12.53-12.54 12.53-31.06v-156.41q0-18.53-12.53-31.06Q498.52-520 480-520t-31.06 12.53q-12.53 12.53-12.53 31.06V-320q0 18.52 12.53 31.06 12.54 12.53 31.06 12.53Zm0-318.81q19.03 0 31.91-12.87 12.87-12.88 12.87-31.91t-12.87-31.91q-12.88-12.87-31.91-12.87t-31.91 12.87q-12.87 12.88-12.87 31.91t12.87 31.91q12.88 12.87 31.91 12.87Zm0 523.35q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Zm0-91q133.04 0 225.09-92.04 92.04-92.05 92.04-225.09 0-133.04-92.04-225.09-92.05-92.04-225.09-92.04-133.04 0-225.09 92.04-92.04 92.05-92.04 225.09 0 133.04 92.04 225.09 92.05 92.04 225.09 92.04ZM480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_italic.xml b/apps/android/design/src/main/res/drawable/sf_italic.xml
new file mode 100644
index 00000000..648aa848
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_italic.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `format_italic`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M249.52-192.11q-23.15 0-39.32-16.17-16.18-16.18-16.18-39.33t16.18-39.32q16.17-16.18 39.32-16.18h105.94l117.84-353.3H370.96q-23.16 0-39.33-16.18-16.17-16.17-16.17-39.32 0-23.16 16.17-39.33 16.17-16.17 39.33-16.17h300q23.15 0 39.32 16.17 16.18 16.17 16.18 39.33 0 23.15-16.18 39.32-16.17 16.18-39.32 16.18h-85.94l-117.85 353.3h82.35q23.15 0 39.33 16.18 16.17 16.17 16.17 39.32t-16.17 39.33q-16.18 16.17-39.33 16.17h-300Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_key.xml b/apps/android/design/src/main/res/drawable/sf_key.xml
new file mode 100644
index 00000000..3a059cf3
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_key.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `key`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M280.03-396.41q-34.46 0-59.04-24.55-24.58-24.54-24.58-59.01 0-34.46 24.55-59.04 24.54-24.58 59.01-24.58 34.46 0 59.04 24.55 24.58 24.54 24.58 59.01 0 34.46-24.55 59.04-24.54 24.58-59.01 24.58ZM280-232.59q-102.87 0-175.14-72.27Q32.59-377.13 32.59-480q0-102.87 72.27-175.14 72.27-72.27 175.14-72.27 69.63 0 125.92 34.43 56.3 34.44 88.3 89.39h331.65q9.08 0 17.59 3.48 8.52 3.48 15.24 10.2l78.32 78.08q6.91 6.86 9.8 14.87 2.88 8 2.88 16.96t-2.88 16.96q-2.89 8.01-9.8 14.87l-124.61 124.6q-5.69 5.77-13.66 9.22-7.97 3.46-15.86 4.46-7.9 1-15.8-1.36-7.89-2.36-14.85-7.84l-48.65-36.37-53.66 40.37q-5.71 4.48-12.61 6.84-6.9 2.36-13.79 2.36-6.9 0-14.18-2.24-7.27-2.24-12.87-6.72l-58.85-41.56h-43.41q-31.76 54.71-88.18 89.27-56.41 34.55-126.04 34.55Zm0-87.41q56.96 0 99.7-34.72 42.73-34.71 56.02-88.87h129.06l56.81 40.05v.38-.38h-.12.12l82-61 70.76 54.52 71.17-69.02h-.38.38l-37.13-37.37q0-.76.12-.38t-.12.38H435.48q-12.57-53.44-55.64-88.51Q336.76-640 280-640q-66 0-113 47t-47 113q0 66 47 113t113 47Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_key_fill.xml b/apps/android/design/src/main/res/drawable/sf_key_fill.xml
new file mode 100644
index 00000000..f2e23efd
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_key_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `key` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M280-360q-50 0-85-35t-35-85q0-50 35-85t85-35q50 0 85 35t35 85q0 50-35 85t-85 35Zm0 127.41q78.67 0 142.59-44.83 63.91-44.84 89.87-118.99h12.56l46.26 46.5q6.96 6.71 15.04 9.57 8.07 2.86 17.03 2.86 8.95 0 16.91-2.86 7.96-2.86 14.91-9.81l50.33-50.33 64.5 52.61q6.96 5.96 15.29 8.94 8.34 2.97 17.3 2.21 8.95-.76 16.53-4.38 7.58-3.62 13.77-10.57l87.13-97.26q6.2-6.96 9.06-14.92 2.85-7.95 2.85-16.91t-3.23-16.65q-3.24-7.7-9.44-13.89l-39.09-38.85q-6.71-6.72-15.05-10.08-8.34-3.36-17.53-3.36H512.22q-24.24-70.15-86.89-116.99-62.66-46.83-145.33-46.83-103.11 0-175.26 72.15Q32.59-583.11 32.59-480q0 102.87 72.27 175.14 72.27 72.27 175.14 72.27Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_keyboard.xml b/apps/android/design/src/main/res/drawable/sf_keyboard.xml
new file mode 100644
index 00000000..540107c3
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_keyboard.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keyboard`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M160-189q-37.78 0-64.39-26.61T69-280v-400q0-37.78 26.61-64.39T160-771h640q37.78 0 64.39 26.61T891-680v400q0 37.78-26.61 64.39T800-189H160Zm0-91h640v-400H160v400Zm200-40h240q17 0 28.5-11.5T640-360q0-17-11.5-28.5T600-400H360q-17 0-28.5 11.5T320-360q0 17 11.5 28.5T360-320Zm-200 40v-400 400Zm80-280q17 0 28.5-11.5T280-600q0-17-11.5-28.5T240-640q-17 0-28.5 11.5T200-600q0 17 11.5 28.5T240-560Zm120 0q17 0 28.5-11.5T400-600q0-17-11.5-28.5T360-640q-17 0-28.5 11.5T320-600q0 17 11.5 28.5T360-560Zm120 0q17 0 28.5-11.5T520-600q0-17-11.5-28.5T480-640q-17 0-28.5 11.5T440-600q0 17 11.5 28.5T480-560Zm120 0q17 0 28.5-11.5T640-600q0-17-11.5-28.5T600-640q-17 0-28.5 11.5T560-600q0 17 11.5 28.5T600-560Zm120 0q17 0 28.5-11.5T760-600q0-17-11.5-28.5T720-640q-17 0-28.5 11.5T680-600q0 17 11.5 28.5T720-560ZM240-440q17 0 28.5-11.5T280-480q0-17-11.5-28.5T240-520q-17 0-28.5 11.5T200-480q0 17 11.5 28.5T240-440Zm120 0q17 0 28.5-11.5T400-480q0-17-11.5-28.5T360-520q-17 0-28.5 11.5T320-480q0 17 11.5 28.5T360-440Zm120 0q17 0 28.5-11.5T520-480q0-17-11.5-28.5T480-520q-17 0-28.5 11.5T440-480q0 17 11.5 28.5T480-440Zm120 0q17 0 28.5-11.5T640-480q0-17-11.5-28.5T600-520q-17 0-28.5 11.5T560-480q0 17 11.5 28.5T600-440Zm120 0q17 0 28.5-11.5T760-480q0-17-11.5-28.5T720-520q-17 0-28.5 11.5T680-480q0 17 11.5 28.5T720-440Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_keyboard_chevron_compact_down.xml b/apps/android/design/src/main/res/drawable/sf_keyboard_chevron_compact_down.xml
new file mode 100644
index 00000000..19cdeb49
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_keyboard_chevron_compact_down.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keyboard_hide`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m464.09-48.5-112-112q-11.2-11.2-5.48-24.99 5.72-13.79 21.39-13.79h224q15.67 0 21.39 13.79 5.72 13.79-5.48 24.99l-112 112q-6.71 6.72-15.91 6.72t-15.91-6.72ZM162.87-275.7q-37.78 0-64.39-26.6-26.61-26.61-26.61-64.4v-394.02q0-37.78 26.61-64.39t64.39-26.61h634.26q37.78 0 64.39 26.61t26.61 64.39v394.02q0 37.79-26.61 64.4-26.61 26.6-64.39 26.6H162.87Zm0-91h634.26v-394.02H162.87v394.02ZM360-404.78h240q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5H360q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5ZM162.87-366.7v-394.02 394.02Zm79.28-276.89q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm119.05 0q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm118.8 0q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm118.8 0q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm119.05 0q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm-475.7 120q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm119.05 0q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm118.8 0q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm118.8 0q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm119.05 0q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_laptopcomputer.xml b/apps/android/design/src/main/res/drawable/sf_laptopcomputer.xml
new file mode 100644
index 00000000..dc412254
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_laptopcomputer.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `laptop_mac`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M83.59-148.28q-34.48 0-59.04-24.56Q0-197.39 0-231.87h162.87q-37.78 0-64.39-26.61t-26.61-64.39v-434.26q0-37.78 26.61-64.39t64.39-26.61h634.26q37.78 0 64.39 26.61t26.61 64.39v434.26q0 37.78-26.61 64.39t-64.39 26.61H960q0 34.44-24.55 59.01-24.56 24.58-59.04 24.58H83.59ZM480-200q17 0 28.5-11.5T520-240q0-17-11.5-28.5T480-280q-17 0-28.5 11.5T440-240q0 17 11.5 28.5T480-200ZM162.87-322.87h634.26v-434.26H162.87v434.26Zm0 0v-434.26 434.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_list_bullet.xml b/apps/android/design/src/main/res/drawable/sf_list_bullet.xml
new file mode 100644
index 00000000..4df0bed4
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_list_bullet.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `format_list_bulleted`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M407.17-194.5q-19.15 0-32.32-13.17-13.18-13.18-13.18-32.33t13.18-32.33q13.17-13.17 32.32-13.17h395.46q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H407.17Zm0-240q-19.15 0-32.32-13.17-13.18-13.18-13.18-32.33t13.18-32.33q13.17-13.17 32.32-13.17h395.46q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H407.17Zm0-240q-19.15 0-32.32-13.17-13.18-13.18-13.18-32.33t13.18-32.33q13.17-13.17 32.32-13.17h395.46q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H407.17ZM196.59-154.98q-35.09 0-60.02-24.99-24.94-24.99-24.94-60.09 0-35.09 24.99-60.03 24.99-24.93 60.09-24.93 35.09 0 60.03 24.99 24.93 24.99 24.93 60.09 0 35.09-24.99 60.03-24.99 24.93-60.09 24.93Zm0-240q-35.09 0-60.02-24.99-24.94-24.99-24.94-60.09 0-35.09 24.99-60.03 24.99-24.93 60.09-24.93 35.09 0 60.03 24.99 24.93 24.99 24.93 60.09 0 35.09-24.99 60.03-24.99 24.93-60.09 24.93Zm0-240q-35.09 0-60.02-24.99-24.94-24.99-24.94-60.09 0-35.09 24.99-60.03 24.99-24.93 60.09-24.93 35.09 0 60.03 24.99 24.93 24.99 24.93 60.09 0 35.09-24.99 60.03-24.99 24.93-60.09 24.93Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_list_bullet_rectangle.xml b/apps/android/design/src/main/res/drawable/sf_list_bullet_rectangle.xml
new file mode 100644
index 00000000..cb9cb367
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_list_bullet_rectangle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `list_alt`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M320-281.43q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5ZM320-440q17 0 28.5-11.5T360-480q0-17-11.5-28.5T320-520q-17 0-28.5 11.5T280-480q0 17 11.5 28.5T320-440Zm0-158.57q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm160 317.14h160q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5H480q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5ZM480-440h160q17 0 28.5-11.5T680-480q0-17-11.5-28.5T640-520H480q-17 0-28.5 11.5T440-480q0 17 11.5 28.5T480-440Zm0-158.57h160q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5H480q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm-277.13 486.7q-37.78 0-64.39-26.61t-26.61-64.39v-554.26q0-37.78 26.61-64.39t64.39-26.61h554.26q37.78 0 64.39 26.61t26.61 64.39v554.26q0 37.78-26.61 64.39t-64.39 26.61H202.87Zm0-91h554.26v-554.26H202.87v554.26Zm0-554.26v554.26-554.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_lock_display.xml b/apps/android/design/src/main/res/drawable/sf_lock_display.xml
new file mode 100644
index 00000000..c115b8d1
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_lock_display.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `screen_lock_landscape`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M394-320q-14 0-24-10t-10-24v-132q0-14 10-24t24-10h6v-40q0-33 23.5-56.5T480-640q33 0 56.5 23.5T560-560v40h6q14 0 24 10t10 24v132q0 14-10 24t-24 10H394Zm46-200h80v-40q0-17-11.5-28.5T480-600q-17 0-28.5 11.5T440-560v40ZM123.59-192.59q-37.79 0-64.39-26.61-26.61-26.6-26.61-64.39v-392.82q0-37.79 26.61-64.39 26.6-26.61 64.39-26.61h712.82q37.79 0 64.39 26.61 26.61 26.6 26.61 64.39v392.82q0 37.79-26.61 64.39-26.6 26.61-64.39 26.61H123.59Zm40-91v-392.82h-40v392.82h40Zm80 0h472.82v-392.82H243.59v392.82Zm552.82 0h40v-392.82h-40v392.82ZM163.59-676.41h-40 40Zm632.82 0h40-40Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_lock_fill.xml b/apps/android/design/src/main/res/drawable/sf_lock_fill.xml
new file mode 100644
index 00000000..d746be06
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_lock_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `lock` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M242.87-72.59q-37.54 0-64.27-26.73-26.73-26.73-26.73-64.27v-394.26q0-37.54 26.73-64.27 26.73-26.73 64.27-26.73h33.54v-73.06q0-84.92 59.46-144.61 59.46-59.7 144.13-59.7 84.67 0 144.13 59.7 59.46 59.69 59.46 144.61v73.06h33.54q37.54 0 64.27 26.73 26.73 26.73 26.73 64.27v394.26q0 37.54-26.73 64.27-26.73 26.73-64.27 26.73H242.87ZM480-280.72q33 0 56.5-23.5t23.5-56.5q0-33-23.5-56.5t-56.5-23.5q-33 0-56.5 23.5t-23.5 56.5q0 33 23.5 56.5t56.5 23.5ZM367.41-648.85h225.18v-73.06q0-47.21-32.73-80.26-32.73-33.05-79.86-33.05t-79.86 33.05q-32.73 33.05-32.73 80.26v73.06Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_lock_rectangle.xml b/apps/android/design/src/main/res/drawable/sf_lock_rectangle.xml
new file mode 100644
index 00000000..4ee5f893
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_lock_rectangle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `password`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M120-285.5h720q19.15 0 32.33 13.17Q885.5-259.15 885.5-240t-13.17 32.33Q859.15-194.5 840-194.5H120q-19.15 0-32.33-13.17Q74.5-220.85 74.5-240t13.17-32.33Q100.85-285.5 120-285.5Zm36.41-212.91-17.32 31.13q-6.48 11.71-19.2 15.07-12.72 3.36-24.43-3.12-11.72-6.47-14.96-19.19-3.24-12.72 3.24-24.44l17.33-31.13H66.41q-13.71 0-22.81-9.09-9.1-9.1-9.1-22.82t9.1-22.82q9.1-9.09 22.81-9.09h34.66l-17.33-29.13q-6.48-11.72-3.24-24.44t14.96-19.19q11.71-6.48 24.43-3.24 12.72 3.24 19.2 14.95l17.32 29.37 17.33-29.37q6.48-11.71 19.08-14.95 12.59-3.24 24.31 3.24 11.72 6.47 14.96 19.19 3.24 12.72-3.24 24.44l-17.33 29.13h34.65q13.72 0 22.82 9.09 9.1 9.1 9.1 22.82t-9.1 22.82q-9.1 9.09-22.82 9.09h-34.65l17.57 31.37q6.48 11.72 3.24 24.32t-14.96 19.07q-11.72 6.48-24.44 3.12-12.71-3.36-19.19-15.07l-17.33-31.13Zm323.59 0-17.33 31.13q-6.47 11.71-19.19 15.07-12.72 3.36-24.44-3.12-11.71-6.47-14.95-19.19-3.24-12.72 3.24-24.44l17.32-31.13H390q-13.72 0-22.82-9.09-9.09-9.1-9.09-22.82t9.09-22.82q9.1-9.09 22.82-9.09h34.65l-17.32-29.13q-6.48-11.72-3.24-24.44t14.95-19.19q11.72-6.48 24.44-3.24t19.19 14.95L480-625.59l17.33-29.37q6.47-11.71 19.19-14.95 12.72-3.24 24.44 3.24 11.71 6.47 14.95 19.19 3.24 12.72-3.24 24.44l-17.32 29.13H570q13.72 0 22.82 9.09 9.09 9.1 9.09 22.82t-9.09 22.82q-9.1 9.09-22.82 9.09h-34.65l17.56 31.13q6.48 11.72 3.24 24.44t-14.95 19.19q-11.72 6.48-24.56 3.12-12.84-3.36-19.31-15.07L480-498.41Zm323.59 0-17.57 31.37q-6.48 11.71-19.07 14.95-12.6 3.24-24.32-3.24-11.72-6.47-14.96-19.07-3.24-12.6 3.24-24.32l17.57-31.37h-34.65q-13.72 0-22.82-9.09-9.1-9.1-9.1-22.82t9.1-22.82q9.1-9.09 22.82-9.09h34.65l-17.33-29.37q-6.48-11.72-3.36-24.32 3.12-12.6 14.84-19.07 11.72-6.48 24.44-3.24 12.71 3.24 19.19 14.95l17.33 29.37 17.32-29.37q6.48-11.71 19.2-14.95 12.72-3.24 24.43 3.24 11.72 6.47 14.96 19.19 3.24 12.72-3.24 24.44l-17.33 29.13h34.66q13.71 0 22.81 9.09 9.1 9.1 9.1 22.82t-9.1 22.82q-9.1 9.09-22.81 9.09h-34.66l17.57 31.13q6.48 11.72 3.24 24.44t-14.96 19.19q-11.71 6.48-24.55 3.12-12.84-3.36-19.32-15.07l-17.32-31.13Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_lock_shield.xml b/apps/android/design/src/main/res/drawable/sf_lock_shield.xml
new file mode 100644
index 00000000..1e2f56d6
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_lock_shield.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `shield_lock`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M405.5-320h149q19.15 0 32.33-13.17Q600-346.35 600-365.5V-480q0-17-11.5-28.5T560-520v-40q0-33-23.5-56.5T480-640q-33 0-56.5 23.5T400-560v40q-17 0-28.5 11.5T360-480v114.5q0 19.15 13.17 32.33Q386.35-320 405.5-320ZM440-520v-40q0-17 11.5-28.5T480-600q17 0 28.5 11.5T520-560v40h-80Zm40 443.65q-7.72 0-14.67-1.12-6.96-1.12-13.92-3.36-136.67-45.47-218.11-169.6Q151.87-374.57 151.87-516v-186.85q0-28.58 16.41-51.45 16.42-22.87 42.76-33.07l237.13-88.8q15.68-5.72 31.83-5.72t31.83 5.72l237.13 88.8q26.34 10.2 42.76 33.07 16.41 22.87 16.41 51.45V-516q0 141.43-81.43 265.57-81.44 124.13-218.11 169.6-6.96 2.24-13.92 3.36-6.95 1.12-14.67 1.12Zm0-90.28q102.33-34.44 169.73-132 67.4-97.57 67.4-217.26v-186.96L480-791.65l-237.13 88.92V-516q0 119.8 67.4 217.37 67.4 97.56 169.73 132Zm0-312.89Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_lock_slash.xml b/apps/android/design/src/main/res/drawable/sf_lock_slash.xml
new file mode 100644
index 00000000..5358ce3a
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_lock_slash.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `lock_open`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M242.87-72.59q-37.54 0-64.27-26.73-26.73-26.73-26.73-64.27v-394.26q0-37.54 26.73-64.27 26.73-26.73 64.27-26.73h349.72v-73.06q0-47.21-32.73-80.26-32.73-33.05-79.86-33.05-38.27 0-66.97 22.51-28.7 22.51-39.7 56.21-5.68 15.67-20.09 25.13-14.41 9.46-31.43 9.46-19.29 0-31.98-13.39-12.7-13.4-8.5-31.03 15.67-68.28 70.79-114.08 55.12-45.81 127.88-45.81 84.67 0 144.13 59.7 59.46 59.69 59.46 144.61v73.06h33.54q37.54 0 64.27 26.73 26.73 26.73 26.73 64.27v394.26q0 37.54-26.73 64.27-26.73 26.73-64.27 26.73H242.87Zm0-91h474.26v-394.26H242.87v394.26ZM480-280.72q33 0 56.5-23.5t23.5-56.5q0-33-23.5-56.5t-56.5-23.5q-33 0-56.5 23.5t-23.5 56.5q0 33 23.5 56.5t56.5 23.5ZM242.87-163.59v-394.26 394.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_magnifyingglass.xml b/apps/android/design/src/main/res/drawable/sf_magnifyingglass.xml
new file mode 100644
index 00000000..48dcdc19
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_magnifyingglass.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `search`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M378.09-314.5q-111.16 0-188.33-77.17-77.17-77.18-77.17-188.33t77.17-188.33q77.17-77.17 188.33-77.17 111.15 0 188.32 77.17 77.18 77.18 77.18 188.33 0 44.48-13.52 83.12-13.53 38.64-36.57 68.16l222.09 222.33q12.67 12.91 12.67 31.94 0 19.04-12.91 31.71-12.68 12.67-31.83 12.67t-31.82-12.67L529.85-364.59q-29.76 23.05-68.64 36.57-38.88 13.52-83.12 13.52Zm0-91q72.84 0 123.67-50.83 50.83-50.82 50.83-123.67t-50.83-123.67q-50.83-50.83-123.67-50.83-72.85 0-123.68 50.83-50.82 50.82-50.82 123.67t50.82 123.67q50.83 50.83 123.68 50.83Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_map_fill.xml b/apps/android/design/src/main/res/drawable/sf_map_fill.xml
new file mode 100644
index 00000000..d952f4ca
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_map_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `map` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M570.41-121.83 360-195.63l-186.48 72.48q-11.43 4.48-22.25 2.86-10.81-1.62-19.77-7.34-8.96-5.72-14.29-15.41-5.34-9.7-5.34-22.13V-730q0-15.63 9.05-27.78 9.06-12.15 24.45-17.87l185.04-62.52q6.96-2.24 14.3-3.48 7.33-1.24 15.29-1.24 7.96 0 15.29 1.12 7.34 1.12 14.3 3.6L600-764.37l186.48-72.48q11.43-4.48 22.25-2.86 10.81 1.62 19.77 7.34 8.96 5.72 14.29 15.41 5.34 9.7 5.34 22.13V-230q0 15.63-9.05 27.78-9.06 12.15-24.45 17.87l-185.04 62.52q-6.96 2.24-14.3 3.48-7.33 1.24-15.29 1.24-7.96 0-15.29-1.12-7.34-1.12-14.3-3.6ZM560-221.35v-461.3l-160-56v461.3l160 56Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_mic.xml b/apps/android/design/src/main/res/drawable/sf_mic.xml
new file mode 100644
index 00000000..d89d033f
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_mic.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `mic`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M479.97-389q-53.8 0-91.43-37.65-37.63-37.65-37.63-91.44v-238.32q0-53.79 37.66-91.44t91.46-37.65q53.8 0 91.43 37.65 37.63 37.65 37.63 91.44v238.32q0 53.79-37.66 91.44T479.97-389Zm.03-248.37ZM436.41-149v-80.37Q341.07-242.61 273.29-310q-67.77-67.39-82.49-163.5-2.47-18.43 9.72-31.51 12.2-13.08 30.63-13.08 18.44 0 31.25 12.7 12.82 12.69 17.3 31.13 15.19 70.96 71.77 116.08 56.57 45.11 128.52 45.11 72.97 0 129.04-45.61 56.08-45.62 71.27-115.58 4.48-18.44 17.3-31.13 12.81-12.7 31.25-12.7 18.43 0 30.51 13.2 12.08 13.19 9.6 31.63-14.72 94.11-81.87 162.38-67.16 68.27-163.5 81.51V-149q0 18.52-12.53 31.06-12.54 12.53-31.06 12.53t-31.06-12.53q-12.53-12.54-12.53-31.06ZM480-480q16.19 0 27.14-10.95t10.95-27.14v-238.32q0-16.19-10.95-27.14T480-794.5q-16.19 0-27.14 10.95t-10.95 27.14v238.32q0 16.19 10.95 27.14T480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_mic_fill.xml b/apps/android/design/src/main/res/drawable/sf_mic_fill.xml
new file mode 100644
index 00000000..1eb9fc79
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_mic_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `mic` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-389q-53.83 0-91.46-37.63-37.63-37.63-37.63-91.46v-238.32q0-53.83 37.63-91.46Q426.17-885.5 480-885.5q53.83 0 91.46 37.63 37.63 37.63 37.63 91.46v238.32q0 53.83-37.63 91.46Q533.83-389 480-389Zm-43.59 240v-80.37Q341.07-242.61 273.29-310q-67.77-67.39-82.49-163.5-2.47-18.43 9.72-31.51 12.2-13.08 30.63-13.08 18.44 0 31.25 12.7 12.82 12.69 17.3 31.13 15.19 70.96 71.77 116.08 56.57 45.11 128.53 45.11 72.96 0 129.03-45.61 56.08-45.62 71.27-115.58 4.48-18.44 17.3-31.13 12.81-12.7 31.25-12.7 18.43 0 30.51 13.2 12.08 13.19 9.6 31.63-14.72 94.11-81.87 162.38-67.16 68.27-163.5 81.51V-149q0 18.44-12.58 31.01-12.58 12.58-31.01 12.58t-31.01-12.58q-12.58-12.57-12.58-31.01Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_mic_slash.xml b/apps/android/design/src/main/res/drawable/sf_mic_slash.xml
new file mode 100644
index 00000000..07da5dde
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_mic_slash.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `mic_off`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M682.52-373.89q-15.43-8.72-19.91-26.41-4.48-17.7 3.76-33.13 6.28-10.29 10.54-21.83 4.26-11.54 6.26-23.59 4.48-18.43 18.13-29.31 13.66-10.88 32.09-9.45 17.24 1.2 28.12 14.03 10.88 12.84 8.64 30.08-3 21.8-9.9 42.73-6.9 20.92-17.95 40.2-8.71 15.44-26.53 20.42-17.81 4.98-33.25-3.74ZM481.2-603.57Zm0-281.93q53.82 0 91.57 37.63 37.75 37.63 37.75 91.46v172.54q0 22.87-14.17 34.19-14.18 11.31-31.33 11.31-16.91 0-31.2-11.7-14.3-11.69-14.3-34.56v-171.78q0-16.05-11.02-27.07t-27.3-11.02q-16.29 0-27.19 11.02-10.9 11.02-10.9 27.07v22.82q0 20.72-13.58 31.08-13.57 10.36-30.01 10.36-21.45 0-34.43-15.17-12.98-15.16-10.83-38.75v-22.06q3.11-48.57 39.54-82.97 36.44-34.4 87.4-34.4ZM437.61-149v-80.37q-95.35-12.48-163.12-80.25Q206.72-377.39 192-473.5q-2.48-18.43 9.72-31.51 12.19-13.08 30.63-13.08 18.43 0 31.63 12.7 13.19 12.69 16.91 31.13 15.2 71.72 71.39 116.46 56.2 44.73 128.92 44.73 36.15 0 68.56-11.69 32.41-11.7 58.37-32.61l62.5 62.5q-30.43 25.39-67.21 42.71-36.77 17.31-78.64 22.79V-149q0 18.44-12.57 31.01-12.58 12.58-31.01 12.58-18.44 0-31.02-12.58-12.57-12.57-12.57-31.01Zm324 61.89L84-764.72q-11.72-11.71-11.72-29.19T84-823.11q11.72-11.72 29.2-11.72 17.47 0 29.19 11.72L820-145.5q11.72 11.72 11.72 29.2 0 17.47-11.72 29.19-11.72 11.72-29.2 11.72-17.47 0-29.19-11.72Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_move.xml b/apps/android/design/src/main/res/drawable/sf_move.xml
new file mode 100644
index 00000000..befc1728
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_move.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `open_with`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M434.5-240.22v-112.37q0-19.15 13.17-32.32 13.18-13.18 32.33-13.18t32.33 13.18q13.17 13.17 13.17 32.32v111.37l33.91-34.67q13.44-13.68 32.59-13.68 19.15 0 32.83 13.68 13.67 13.67 13.67 32.82 0 19.16-13.67 32.83L512.07-97.48q-6.72 6.72-14.92 9.82-8.19 3.1-17.15 3.1-8.96 0-17.15-3.1-8.2-3.1-14.92-9.82L334.17-211.24Q320.5-224.91 321-243.57q.5-18.65 14.17-32.32 13.68-13.68 32.33-13.68t32.33 13.68l34.67 35.67ZM241.22-434.5l34.67 33.91q13.68 13.44 13.68 32.59 0 19.15-13.68 32.83-13.67 13.67-32.82 13.67-19.16 0-32.83-13.67L97.48-447.93q-6.72-6.72-9.82-14.92-3.1-8.19-3.1-17.15 0-8.96 3.1-17.15 3.1-8.2 9.82-14.92l112.76-112.76q13.67-13.67 32.33-13.67 18.65 0 32.32 13.67 13.68 13.68 13.68 32.33t-13.68 32.33l-34.67 34.67h112.37q19.15 0 32.32 13.17 13.18 13.18 13.18 32.33t-13.18 32.33q-13.17 13.17-32.32 13.17H241.22Zm478.56 0H607.41q-19.15 0-32.32-13.17-13.18-13.18-13.18-32.33t13.18-32.33q13.17-13.17 32.32-13.17h111.37l-34.67-33.91q-13.68-13.44-13.68-32.59 0-19.15 13.68-32.83 13.67-13.67 32.82-13.67 19.16 0 32.83 13.67l112.76 112.76q6.72 6.72 9.82 14.92 3.1 8.19 3.1 17.15 0 8.96-3.1 17.15-3.1 8.2-9.82 14.92L748.76-334.17Q735.09-320.5 716.93-321q-18.15-.5-31.82-14.17-13.68-13.68-13.68-32.33t13.68-32.33l34.67-34.67ZM434.5-719.78l-35.67 35.67q-13.68 13.68-31.83 13.56-18.15-.12-31.83-13.8-13.67-13.67-13.67-32.32 0-18.66 13.67-32.33l112.76-113.52q6.72-6.72 14.92-9.82 8.19-3.1 17.15-3.1 8.96 0 17.15 3.1 8.2 3.1 14.92 9.82l113.76 113.76q13.67 13.67 13.67 31.83 0 18.15-13.67 31.82-13.68 13.68-32.33 13.68t-32.33-13.68l-35.67-34.67v112.37q0 19.15-13.17 32.32-13.18 13.18-32.33 13.18t-32.33-13.18q-13.17-13.17-13.17-32.32v-112.37Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_music_note.xml b/apps/android/design/src/main/res/drawable/sf_music_note.xml
new file mode 100644
index 00000000..47dd64ac
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_music_note.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `music_note`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M397.37-110.91q-68.15 0-116.83-48.68-48.67-48.67-48.67-116.82 0-68.16 48.67-116.83 48.68-48.67 116.83-48.67 21.33 0 39.39 4.78 18.07 4.78 35.11 14.35v-380.81q0-19.15 13.17-32.32 13.18-13.18 32.33-13.18h165.5q19.15 0 32.33 13.18 13.17 13.17 13.17 32.32v80q0 19.16-13.17 32.33-13.18 13.17-32.33 13.17h-120v401.68q0 68.15-48.67 116.82-48.68 48.68-116.83 48.68Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_network.xml b/apps/android/design/src/main/res/drawable/sf_network.xml
new file mode 100644
index 00000000..4c7b314c
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_network.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `public`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480.24-71.87q-84.65 0-159.1-32.1-74.44-32.1-129.64-87.29-55.2-55.2-87.29-129.65-32.1-74.46-32.1-159.11 0-84.65 32.1-159.09 32.09-74.43 87.29-129.63 55.2-55.19 129.65-87.29 74.46-32.1 159.11-32.1 84.65 0 158.97 32.1 74.31 32.1 129.51 87.29 55.19 55.2 87.29 129.65 32.1 74.46 32.1 159.11 0 84.65-32.1 159.09-32.1 74.43-87.29 129.63-55.2 55.19-129.57 87.29-74.37 32.1-158.93 32.1Zm-39.76-93v-77.76q-32.76 0-56.03-23.27-23.26-23.26-23.26-55.93v-39.6L171.11-551.52q-3 17.76-5.5 35.52t-2.5 35.63q0 120.1 78.78 210.42t198.59 105.08Zm273.61-101.04q20-21.76 35.64-47.02 15.64-25.27 26.14-52.65t15.88-56.22q5.38-28.84 5.38-58.68 0-97.01-53.78-177.19-53.78-80.18-144.07-115.7v15.52q0 32.71-23.5 56-23.5 23.28-56.15 23.28h-79.15v79.22q0 16.83-11.5 28.33t-28.33 11.5h-79.22v79.04h237.99q16.86 0 28.36 11.5t11.5 28.32v118.75h39.29q26 0 46.79 15.5 20.8 15.5 28.73 40.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_note_text.xml b/apps/android/design/src/main/res/drawable/sf_note_text.xml
new file mode 100644
index 00000000..13869a9f
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_note_text.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `sticky_note_2`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M202.87-202.87h354.26v-154.5q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17h154.5v-354.26H202.87v554.26Zm0 91q-37.54 0-64.27-26.73-26.73-26.73-26.73-64.27v-554.26q0-37.54 26.73-64.27 26.73-26.73 64.27-26.73h554.26q37.54 0 64.27 26.73 26.73 26.73 26.73 64.27v360.78q0 18.21-6.84 34.72-6.83 16.5-19.51 29.17L627.54-138.22q-12.67 12.68-29.17 19.51-16.51 6.84-34.72 6.84H202.87Zm236.17-285.26h-114.5q-17.71 0-29.69-12.05t-11.98-29.86q0-17.71 12.05-29.7 12.05-11.98 29.86-11.98h114.26q17.71 0 29.7 11.99 11.98 11.98 11.98 29.69t-11.98 29.81q-11.99 12.1-29.7 12.1Zm196.42-163.59H324.54q-17.71 0-29.69-12.05t-11.98-29.86q0-17.71 12.05-29.69t29.86-11.98h310.68q17.71 0 29.69 11.98t11.98 29.69q0 17.72-11.98 29.81-11.98 12.1-29.69 12.1ZM202.87-202.87v-554.26 554.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_option.xml b/apps/android/design/src/main/res/drawable/sf_option.xml
new file mode 100644
index 00000000..c481de93
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_option.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keyboard_option_key`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M640.35-194.5q-24.87 0-45.5-12.05-20.63-12.06-33.07-33.45L310.89-674.5H157.61q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33t13.17-32.33q13.18-13.17 32.33-13.17h153.04q24.87 0 45.5 12.05 20.63 12.06 33.07 33.45l250.89 434.5h162.52q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H640.35Zm-.35-480q-19.15 0-32.33-13.17Q594.5-700.85 594.5-720t13.17-32.33Q620.85-765.5 640-765.5h162.63q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H640Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_paintbrush.xml b/apps/android/design/src/main/res/drawable/sf_paintbrush.xml
new file mode 100644
index 00000000..802caeae
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_paintbrush.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `brush`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M238.09-112.35q-46.44 0-92.95-24.03-46.51-24.03-76.62-66.25 28.39 0 55.63-19.54 27.24-19.55 28.2-59.26 1.19-50.96 37.27-86.8 36.08-35.84 88.47-35.84t89.18 36.75q36.8 36.74 36.8 89.23 0 68.63-48.68 117.19-48.67 48.55-117.3 48.55Zm0-85.74q33 0 56.5-23.5t23.5-56.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 23-5.5 42t-14.5 36q5 2 10 2h10Zm236.69-159.28L357.37-474.78l369-369q11-11 27.5-11.5t28.5 11.5l61.41 61.41q12 12 12 28t-12 28l-369 369Zm-196.69 79.28Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_paintpalette.xml b/apps/android/design/src/main/res/drawable/sf_paintpalette.xml
new file mode 100644
index 00000000..4d0d8fbd
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_paintpalette.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `palette`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-71.87q-83.63 0-158.09-32.22-74.45-32.21-130.03-87.79-55.58-55.58-87.79-130.04-32.22-74.46-32.22-158.09 0-84.66 32.98-159.1 32.98-74.43 89.55-129.63 56.58-55.19 132-87.29 75.41-32.1 161.02-32.1 81.54 0 154.09 28.1 72.56 28.1 127.37 77.67 54.82 49.58 87.03 117.44 32.22 67.86 32.22 146.44 0 116.44-70.36 181.52-70.36 65.09-173.47 65.09h-68.5q-8.04 0-11.42 4.52-3.38 4.52-3.38 10.28 0 11.53 13.57 31.16 13.56 19.63 13.56 47.43 0 51.91-30.13 79.26-30.13 27.35-78 27.35ZM480-480Zm-217.13 40q26 0 43-17t17-43q0-26-17-43t-43-17q-26 0-43 17t-17 43q0 26 17 43t43 17Zm118.56-157.85q26 0 43-17t17-43q0-26-17-43t-43-17q-26 0-43 17t-17 43q0 26 17 43t43 17Zm197.14 0q26 0 43-17t17-43q0-26-17-43t-43-17q-26 0-43 17t-17 43q0 26 17 43t43 17ZM696.41-440q26 0 43-17t17-43q0-26-17-43t-43-17q-26 0-43 17t-17 43q0 26 17 43t43 17ZM478.57-162.87q8.46 0 13.63-4.73 5.17-4.74 5.17-12.31 0-14-15.12-32.17-15.12-18.16-15.12-55.2 0-43.2 29.83-69.39 29.83-26.2 73.04-26.2h74.3q65.53 0 109.18-38.26 43.65-38.26 43.65-115.67 0-121-92.02-200.67-92.02-79.66-217.69-79.66-134.57 0-229.56 92.28-94.99 92.28-94.99 224.96 0 131.69 92.3 224.36 92.31 92.66 223.4 92.66Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_pause_fill.xml b/apps/android/design/src/main/res/drawable/sf_pause_fill.xml
new file mode 100644
index 00000000..820b37cc
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_pause_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `pause` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M647.17-185.41q-37.54 0-64.27-26.73-26.73-26.74-26.73-64.27v-407.18q0-37.53 26.74-64.27 26.73-26.73 64.27-26.73 37.54 0 64.27 26.73 26.72 26.74 26.72 64.27v407.18q0 37.53-26.73 64.27-26.73 26.73-64.27 26.73Zm-334.35 0q-37.54 0-64.27-26.73-26.72-26.74-26.72-64.27v-407.18q0-37.53 26.73-64.27 26.73-26.73 64.27-26.73 37.54 0 64.27 26.73 26.73 26.74 26.73 64.27v407.18q0 37.53-26.74 64.27-26.73 26.73-64.27 26.73Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_pencil.xml b/apps/android/design/src/main/res/drawable/sf_pencil.xml
new file mode 100644
index 00000000..b9f68531
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_pencil.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `edit`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M202.63-202.87h57.24l374.74-374.74-56.76-57-375.22 375.22v56.52Zm-45.26 91q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33v-102.26q0-18.15 6.84-34.69 6.83-16.53 19.51-29.2l501.17-500.41q12.48-11.72 27.7-17.96 15.21-6.24 31.93-6.24 16.48 0 32.2 6.24 15.71 6.24 27.67 18.72l65.28 65.56q12.48 11.72 18.34 27.56 5.86 15.83 5.86 31.79 0 16.72-5.86 32.05-5.86 15.34-18.34 27.82L324-138.22q-12.67 12.68-29.21 19.51-16.53 6.84-34.68 6.84H157.37Zm597.37-586.39-56.24-56.48 56.24 56.48Zm-148.89 92.41-28-28.76 56.76 57-28.76-28.24Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_person_2.xml b/apps/android/design/src/main/res/drawable/sf_person_2.xml
new file mode 100644
index 00000000..02aaaa36
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_person_2.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `group`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M32.59-268.41q0-36.23 18.74-66.59 18.74-30.37 49.8-46.35 62.72-31.24 127.66-46.98 64.95-15.74 131.93-15.74 67.43 0 132.39 15.62 64.96 15.62 127.19 46.86 31.06 15.95 49.81 46.25 18.74 30.3 18.74 66.93v29.61q0 37.78-26.61 64.39t-64.39 26.61H123.59q-37.79 0-64.39-26.61-26.61-26.61-26.61-64.39v-29.61ZM836.41-147.8h-94.58q13.63-20.16 20.32-43.41 6.7-23.25 6.7-47.59v-35.7q0-45.67-24.5-89.4-24.5-43.73-72.85-74.88 49.33 6.24 94.92 21.33 45.6 15.1 84.36 35.86 36.96 20 56.8 47.21 19.83 27.2 19.83 59.4v36.18q0 37.78-26.61 64.39-26.6 26.61-64.39 26.61ZM360.72-484.07q-67.92 0-115.99-48.07-48.08-48.08-48.08-115.99t48.08-115.99q48.07-48.08 115.99-48.08 67.91 0 115.99 48.08 48.07 48.08 48.07 115.99t-48.07 115.99q-48.08 48.07-115.99 48.07Zm411.72-164.06q0 67.67-48.19 115.87-48.18 48.19-115.84 48.19-11.28 0-28.04-2.61-16.76-2.62-28.72-6.1 27.48-32.48 42.1-72.4 14.62-39.92 14.62-82.92 0-42.99-14.62-82.94-14.62-39.96-42.1-72.44 14.24-5.24 28.24-6.98 14-1.74 28.37-1.74 67.72 0 115.95 48.2 48.23 48.19 48.23 115.87ZM123.59-238.8h474.26v-28.42q0-10.77-5.5-19.58-5.5-8.81-14.5-13.7-52.57-26.04-106.85-39.3-54.28-13.27-110.28-13.27-55.52 0-110.29 13.27-54.76 13.26-106.84 39.3-9 4.89-14.5 13.7-5.5 8.81-5.5 19.58v28.42Zm237.09-332.68q31.6 0 54.15-22.5 22.54-22.51 22.54-54.11 0-31.61-22.51-54.15-22.5-22.54-54.1-22.54-31.61 0-54.15 22.5-22.54 22.51-22.54 54.11 0 31.6 22.5 54.15 22.51 22.54 54.11 22.54Zm.04 332.68Zm0-409.33Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_person_crop_circle.xml b/apps/android/design/src/main/res/drawable/sf_person_crop_circle.xml
new file mode 100644
index 00000000..bad8a415
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_person_crop_circle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `account_circle`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M235.2-279.59q51-38.52 113.52-60.54 62.52-22.02 131.33-22.02t131.64 22.38q62.83 22.38 113.11 60.42 34.29-41.24 53.31-91.92 19.02-50.69 19.02-108.73 0-131.57-92.78-224.35T480-797.13q-131.57 0-224.35 92.78T162.87-480q0 57.8 18.9 108.49 18.9 50.68 53.43 91.92ZM480-437.85q-59.96 0-100.93-40.86-40.98-40.86-40.98-100.81 0-59.96 40.98-100.94 40.97-40.97 100.93-40.97 59.96 0 100.93 40.97 40.98 40.98 40.98 100.94 0 59.95-40.98 100.81-40.97 40.86-100.93 40.86Zm-.02 365.98q-84.65 0-159.09-32.1-74.43-32.1-129.63-87.29-55.19-55.2-87.29-129.65-32.1-74.46-32.1-159.11 0-84.65 32.1-159.09 32.1-74.43 87.29-129.63 55.2-55.19 129.65-87.29 74.46-32.1 159.11-32.1 84.65 0 159.09 32.1 74.43 32.1 129.63 87.29 55.19 55.2 87.29 129.65 32.1 74.46 32.1 159.11 0 84.65-32.1 159.09-32.1 74.43-87.29 129.63-55.2 55.19-129.65 87.29-74.46 32.1-159.11 32.1Zm.02-91q51.8 0 97.37-14.9 45.56-14.9 84.56-42.95-39.47-28.28-84.44-43.06-44.97-14.79-97.49-14.79-52.52 0-97.37 14.79-44.85 14.78-84.33 43.06 39 28.05 84.45 42.95 45.45 14.9 97.25 14.9Zm0-358.56q25.04 0 41.57-16.53 16.52-16.52 16.52-41.56 0-25.05-16.52-41.69-16.53-16.64-41.57-16.64t-41.57 16.64q-16.52 16.64-16.52 41.69 0 25.04 16.52 41.56 16.53 16.53 41.57 16.53Zm0-58.09Zm.24 358.8Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_person_crop_circle_badge_checkmark.xml b/apps/android/design/src/main/res/drawable/sf_person_crop_circle_badge_checkmark.xml
new file mode 100644
index 00000000..7ba55670
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_person_crop_circle_badge_checkmark.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `how_to_reg`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M161.91-147.8q-37.78 0-64.39-26.61T70.91-238.8v-29.61q0-35.17 18.44-66.08 18.43-30.9 50.11-46.86 51-26 116.79-44.36t142.79-18.36q8.75 0 19.68.5t19.67 1.5q17.91 2 29.85 17.16 11.93 15.15 9.69 33.57-2.23 16.12-14.75 27.2-12.51 11.07-31.66 11.07h-32.48q-70.04 0-126.54 17t-90.59 35.57q-9 5-14.5 13.64t-5.5 19.64v28.42H431.2q19.15 0 32.32 13.17 13.18 13.17 13.18 32.33 0 19.15-13.18 32.32-13.17 13.18-32.32 13.18H161.91Zm466.55-106.29 172.8-172.8q11.72-11.72 29.2-11.72 17.47 0 29.19 11.72 11.72 11.72 11.72 29.31 0 17.6-11.72 29.32L660.52-169.13q-13.76 13.67-32.11 13.67-18.34 0-32.02-13.67l-79.37-79.37q-11.72-11.72-11.6-29.2.12-17.47 11.84-29.19 11.72-11.72 29.2-11.72 17.47 0 29.19 11.72l52.81 52.8ZM399.04-484.07q-69.58 0-118.86-49.27-49.27-49.27-49.27-118.86 0-69.58 49.27-118.74 49.28-49.15 118.86-49.15 69.59 0 118.86 49.15 49.27 49.16 49.27 118.74 0 69.59-49.27 118.86-49.27 49.27-118.86 49.27Zm6.66 245.27Zm-6.66-336.27q31.81 0 54.47-22.65t22.66-54.47q0-31.81-22.65-54.35-22.66-22.55-54.47-22.55t-54.47 22.59q-22.67 22.59-22.67 54.3 0 31.82 22.66 54.48 22.65 22.65 54.47 22.65Zm0-77.13Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_person_fill.xml b/apps/android/design/src/main/res/drawable/sf_person_fill.xml
new file mode 100644
index 00000000..aeabe2c7
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_person_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `person` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-484.07q-69.59 0-118.86-49.27-49.27-49.27-49.27-118.86 0-69.58 49.27-118.74 49.27-49.15 118.86-49.15t118.86 49.15q49.27 49.16 49.27 118.74 0 69.59-49.27 118.86-49.27 49.27-118.86 49.27ZM151.87-238.8v-29.61q0-36.16 18.7-66.57 18.69-30.41 49.84-46.37 62.72-31.24 127.68-46.98 64.95-15.74 131.91-15.74 67.43 0 132.39 15.62 64.96 15.62 127.2 46.86 31.15 15.96 49.84 46.25 18.7 30.3 18.7 66.93v29.61q0 37.78-26.61 64.39t-64.39 26.61H242.87q-37.78 0-64.39-26.61t-26.61-64.39Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_phone_fill.xml b/apps/android/design/src/main/res/drawable/sf_phone_fill.xml
new file mode 100644
index 00000000..34f0281f
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_phone_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `call` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M798.48-111.87q-126.44 0-249.87-55.1-123.44-55.1-224.87-156.29Q222.3-424.7 167.21-548.25q-55.1-123.55-55.1-249.99 0-21.35 14.15-35.62 14.15-14.27 35.5-14.27h161.76q19.5 0 33.37 11.53 13.87 11.53 17.31 29.56l25.76 134.97q2.95 19.59-.88 33.22-3.84 13.63-14.71 23.78l-98.44 96.09q19.05 34.37 45.11 66.96 26.07 32.59 58.11 63.63 29.81 29.8 61.42 54.63 31.6 24.83 66.26 44.91l95.67-94.95q11.63-11.4 28.52-16.37 16.89-4.98 34.48-2.03l131.54 27.29q19.03 5.43 30.06 18.44 11.03 13.01 11.03 31.04v163.67q0 21.35-14.27 35.62-14.27 14.27-35.38 14.27Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_photo.xml b/apps/android/design/src/main/res/drawable/sf_photo.xml
new file mode 100644
index 00000000..084d95b3
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_photo.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `image`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M202.87-111.87q-37.78 0-64.39-26.61t-26.61-64.39v-554.26q0-37.78 26.61-64.39t64.39-26.61h554.26q37.78 0 64.39 26.61t26.61 64.39v554.26q0 37.78-26.61 64.39t-64.39 26.61H202.87Zm0-91h554.26v-554.26H202.87v554.26Zm0 0v-554.26 554.26Zm78.09-74.26h398.08q13.92 0 20.39-12.44 6.48-12.43-2.23-23.86l-109.05-147q-6.72-9.2-18.15-9.32-11.43-.12-18.39 9.08L450-324.78l-71.61-95.89q-6.96-9.2-18.39-9.08-11.43.12-18.15 9.32l-79.05 107q-8.71 11.43-2.23 23.86 6.47 12.44 20.39 12.44Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_photo_fill.xml b/apps/android/design/src/main/res/drawable/sf_photo_fill.xml
new file mode 100644
index 00000000..66047caa
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_photo_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `image` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M202.87-111.87q-37.78 0-64.39-26.61t-26.61-64.39v-554.26q0-37.78 26.61-64.39t64.39-26.61h554.26q37.78 0 64.39 26.61t26.61 64.39v554.26q0 37.78-26.61 64.39t-64.39 26.61H202.87Zm78.09-165.26h398.08q13.92 0 20.39-12.44 6.48-12.43-2.23-23.86l-109.05-147q-6.72-9.2-18.15-9.32-11.43-.12-18.39 9.08L450-324.78l-71.61-95.89q-6.96-9.2-18.39-9.08-11.43.12-18.15 9.32l-79.05 107q-8.71 11.43-2.23 23.86 6.47 12.44 20.39 12.44Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_photo_on_rectangle.xml b/apps/android/design/src/main/res/drawable/sf_photo_on_rectangle.xml
new file mode 100644
index 00000000..dbaa171e
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_photo_on_rectangle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `photo_library`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m535.5-465.5-43.85-57.13q-6.95-8.96-18.15-8.96t-18.15 8.96l-61.5 80.59q-8.96 11.43-2.75 23.99 6.22 12.55 20.9 12.55h307q14.68 0 20.9-12.55 6.21-12.56-2.75-23.99l-91.5-119.59q-6.95-8.96-18.15-8.96t-18.15 8.96L535.5-465.5ZM328.37-237.37q-37.78 0-64.39-26.61t-26.61-64.39v-474.26q0-37.78 26.61-64.39t64.39-26.61h474.26q37.78 0 64.39 26.61t26.61 64.39v474.26q0 37.78-26.61 64.39t-64.39 26.61H328.37Zm0-91h474.26v-474.26H328.37v474.26Zm-171 262q-37.78 0-64.39-26.61t-26.61-64.39v-519.76q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v519.76h519.76q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H157.37Zm171-736.26v474.26-474.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_pin.xml b/apps/android/design/src/main/res/drawable/sf_pin.xml
new file mode 100644
index 00000000..b662d5dd
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_pin.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keep`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M648.13-763.11v274.74l66.57 66.57q6.71 6.71 10.07 15.05 3.36 8.34 3.36 17.53v26.59q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17H525.5v219.89q0 9.2-3.36 17.53-3.36 8.34-10.07 15.06L495.91-48.5q-6.71 6.72-15.91 6.72t-15.91-6.72l-16.16-16.15q-6.71-6.72-10.07-15.06-3.36-8.33-3.36-17.53v-219.89H277.37q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33v-26.59q0-9.19 3.36-17.53 3.36-8.34 10.07-15.05l66.57-66.57v-274.74q-17-1.67-28.5-14.25-11.5-12.57-11.5-30.29 0-19.15 13.17-32.33 13.18-13.17 32.33-13.17h325.26q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33 0 17.72-11.5 30.29-11.5 12.58-28.5 14.25Zm-287.2 354.98h238.14l-41.94-41.94v-312.08H402.87v312.08l-41.94 41.94Zm119.07 0Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_pin_fill.xml b/apps/android/design/src/main/res/drawable/sf_pin_fill.xml
new file mode 100644
index 00000000..26b3978e
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_pin_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keep` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M648.13-763.11v274.74l66.57 66.57q6.71 6.71 10.07 15.05 3.36 8.34 3.36 17.53v26.59q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17H525.5v219.89q0 9.2-3.36 17.53-3.36 8.34-10.07 15.06L495.91-48.5q-6.71 6.72-15.91 6.72t-15.91-6.72l-16.16-16.15q-6.71-6.72-10.07-15.06-3.36-8.33-3.36-17.53v-219.89H277.37q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33v-26.59q0-9.19 3.36-17.53 3.36-8.34 10.07-15.05l66.57-66.57v-274.74q-17-1.67-28.5-14.25-11.5-12.57-11.5-30.29 0-19.15 13.17-32.33 13.18-13.17 32.33-13.17h325.26q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33 0 17.72-11.5 30.29-11.5 12.58-28.5 14.25Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_pin_slash.xml b/apps/android/design/src/main/res/drawable/sf_pin_slash.xml
new file mode 100644
index 00000000..6bde77e2
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_pin_slash.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keep_off`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M557.13-762.15H402.87v80.54L294.3-790.65q-5.47-5.72-8.21-12.2-2.74-6.48-2.74-12.95 0-14.2 10.07-25.78 10.08-11.57 26.51-11.57h322.7q19.15 0 32.33 13.77 13.17 13.77 13.17 37.23 0 16.24-13.78 23.93-13.78 7.7-26.22 16.07v227.56q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17t-32.33-13.17q-13.17-13.18-13.17-32.33v-227.56ZM434.5-78.09v-239.04H290.98q-27.39 0-44.07-19.05-16.67-19.06-16.67-43.21 0-11.72 4.62-23.32 4.62-11.59 14.86-22.07l62.15-63.59v-46.72L74.91-774.28Q63.2-786 62.93-803.1q-.26-17.1 12.22-29.57 11.72-11.72 29.2-11.72 17.48 0 29.19 11.72l690.72 690.71q12.48 12.48 12.1 29.58-.38 17.1-12.86 29.58-12.48 11.71-29.32 12.09-16.83.38-29.31-12.09L530.3-317.13l-4.8.48v238.56q0 19.16-13.17 32.33Q499.15-32.59 480-32.59t-32.33-13.17Q434.5-58.93 434.5-78.09Zm-73.8-330.04h78.37l-38.03-37.78-1.52-1.52-38.82 39.3ZM480-604.72Zm-78.96 158.81Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_play_circle.xml b/apps/android/design/src/main/res/drawable/sf_play_circle.xml
new file mode 100644
index 00000000..2e452f5d
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_play_circle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `play_circle`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m430.54-330.72 188.31-120.69q15.91-10.32 15.91-28.65t-15.91-28.53L430.54-629.28q-16.91-11.2-34.68-1.54t-17.77 30.12v241.4q0 20.46 17.77 30.12t34.68-1.54ZM480-71.87q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Zm0-91q133.04 0 225.09-92.04 92.04-92.05 92.04-225.09 0-133.04-92.04-225.09-92.05-92.04-225.09-92.04-133.04 0-225.09 92.04-92.04 92.05-92.04 225.09 0 133.04 92.04 225.09 92.05 92.04 225.09 92.04ZM480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_play_circle_fill.xml b/apps/android/design/src/main/res/drawable/sf_play_circle_fill.xml
new file mode 100644
index 00000000..a05d315c
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_play_circle_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `play_circle` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m430.54-330.72 188.31-120.69q15.91-10.32 15.91-28.65t-15.91-28.53L430.54-629.28q-16.91-11.2-34.68-1.54t-17.77 30.12v241.4q0 20.46 17.77 30.12t34.68-1.54ZM480-71.87q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_play_fill.xml b/apps/android/design/src/main/res/drawable/sf_play_fill.xml
new file mode 100644
index 00000000..ea978920
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_play_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `play_arrow` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M311.87-268.46v-423.08q0-19.63 13.67-32.57 13.68-12.93 31.83-12.93 5.72 0 12.05 1.62 6.34 1.62 12.06 5.09l333.17 211.79q10.2 6.71 15.42 17.03 5.21 10.31 5.21 21.51 0 11.2-5.21 21.51-5.22 10.32-15.42 17.03L381.48-229.67q-5.72 3.47-12.06 5.09-6.33 1.62-12.05 1.62-18.15 0-31.83-12.93-13.67-12.94-13.67-32.57Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_plus.xml b/apps/android/design/src/main/res/drawable/sf_plus.xml
new file mode 100644
index 00000000..f297eabd
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_plus.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `add`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M440-440H240q-17 0-28.5-11.5T200-480q0-17 11.5-28.5T240-520h200v-200q0-17 11.5-28.5T480-760q17 0 28.5 11.5T520-720v200h200q17 0 28.5 11.5T760-480q0 17-11.5 28.5T720-440H520v200q0 17-11.5 28.5T480-200q-17 0-28.5-11.5T440-240v-200Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_plus_circle.xml b/apps/android/design/src/main/res/drawable/sf_plus_circle.xml
new file mode 100644
index 00000000..15b89763
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_plus_circle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `add_circle`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M438.09-438.09V-320q0 17.81 12.05 29.86T480-278.09q17.81 0 29.86-12.05T521.91-320v-118.09H640q17.81 0 29.86-12.05T681.91-480q0-17.81-12.05-29.86T640-521.91H521.91V-640q0-17.81-12.05-29.86T480-681.91q-17.81 0-29.86 12.05T438.09-640v118.09H320q-17.81 0-29.86 12.05T278.09-480q0 17.81 12.05 29.86T320-438.09h118.09ZM480-71.87q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Zm0-91q133.04 0 225.09-92.04 92.04-92.05 92.04-225.09 0-133.04-92.04-225.09-92.05-92.04-225.09-92.04-133.04 0-225.09 92.04-92.04 92.05-92.04 225.09 0 133.04 92.04 225.09 92.05 92.04 225.09 92.04ZM480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_plus_rectangle_on_rectangle.xml b/apps/android/design/src/main/res/drawable/sf_plus_rectangle_on_rectangle.xml
new file mode 100644
index 00000000..4af66991
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_plus_rectangle_on_rectangle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `library_add`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M565.5-405.5q17 0 28.5-11.5t11.5-28.5v-80h80q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5h-80v-80q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5v80h-80q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5h80v80q0 17 11.5 28.5t28.5 11.5ZM328.37-237.37q-37.78 0-64.39-26.61t-26.61-64.39v-474.26q0-37.78 26.61-64.39t64.39-26.61h474.26q37.78 0 64.39 26.61t26.61 64.39v474.26q0 37.78-26.61 64.39t-64.39 26.61H328.37Zm0-91h474.26v-474.26H328.37v474.26Zm-171 262q-37.78 0-64.39-26.61t-26.61-64.39v-519.76q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v519.76h519.76q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H157.37Zm171-736.26v474.26-474.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_point_3_connected_trianglepath_dotted.xml b/apps/android/design/src/main/res/drawable/sf_point_3_connected_trianglepath_dotted.xml
new file mode 100644
index 00000000..ce257382
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_point_3_connected_trianglepath_dotted.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `hub`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M238.07-29q-53.09 0-90.12-37.17-37.04-37.16-37.04-90.26 0-53.09 37.1-90.12 37.09-37.04 90.08-37.04 14 0 26.71 2.88 12.72 2.88 23.48 7.64l52.7-66.45q-27.05-30.52-38.16-69.28-11.12-38.77-5.36-76.81l-75.5-26.76q-17.48 25.24-44.74 40.6-27.26 15.36-60.81 15.36-53.09 0-90.25-37.1Q-11-530.6-11-583.59q0-53.09 37.17-90.25Q63.33-711 116.43-711q53.09 0 90.12 37.16 37.04 37.16 37.04 90.25v7.29l75.02 27.76q20-35.29 53.38-60.17 33.38-24.88 74.42-32.12v-81.97q-39-11.24-66.41-44.3-27.41-33.05-27.41-78.4 0-53.09 37.16-90.25 37.17-37.16 90.26-37.16 53.1 0 90.25 37.16t37.15 90.25q0 45.35-27.79 78.4-27.79 33.06-66.03 44.3v81.97q41.04 7.48 74.42 32.36t53.38 60.17l75.02-28v-7.29q0-53.09 37.1-90.25Q790.6-711 843.59-711q53.09 0 90.25 37.17Q971-636.67 971-583.57q0 53.09-37.16 90.12-37.16 37.04-90.25 37.04-33.53 0-61.3-15.48-27.77-15.48-44.49-40.72l-75.5 27q5.29 38.52-5.35 76.43-10.65 37.9-37.93 69.66l52.94 65.93q10.76-5 23.36-7.5 12.59-2.5 26.59-2.5 52.99 0 90.08 37.1 37.1 37.09 37.1 90.08 0 53.09-37.1 90.25Q774.9-29 721.91-29q-53.09 0-90.25-37.16t-37.16-90.25q0-21.01 6.74-40.44 6.74-19.43 17.74-34.67l-52.46-66.46Q526-275.7 479.5-275.7q-46.5 0-87.02-22.28l-51.46 66.46q11 15.24 17.74 34.67 6.74 19.43 6.74 40.44 0 53.09-37.17 90.25Q291.17-29 238.07-29ZM116.41-543.59q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm121.68 427.18q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5ZM480-805.5q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5T480-885.5q-17 0-28.5 11.5T440-845.5q0 17 11.5 28.5t28.5 11.5Zm-.04 438.8q39.17 0 66.26-27.04 27.08-27.05 27.08-66.22t-27.04-66.26q-27.05-27.08-66.22-27.08t-66.26 27.04q-27.08 27.05-27.08 66.22t27.04 66.26q27.05 27.08 66.22 27.08Zm241.95 250.29q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5Zm121.68-427.18q17 0 28.5-11.5t11.5-28.5q0-17-11.5-28.5t-28.5-11.5q-17 0-28.5 11.5t-11.5 28.5q0 17 11.5 28.5t28.5 11.5ZM480-845.5ZM116.41-583.59ZM480-460Zm363.59-123.59Zm-605.5 427.18Zm483.82 0Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_power.xml b/apps/android/design/src/main/res/drawable/sf_power.xml
new file mode 100644
index 00000000..a9c2b89e
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_power.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `power_settings_new`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M434.5-485.5v-317.13q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v317.13q0 19.15-13.17 32.33Q499.15-440 480-440t-32.33-13.17q-13.17-13.18-13.17-32.33ZM480-111.87q-75.67 0-142.73-29.1-67.05-29.1-117.13-79.17-50.07-50.08-79.17-117.13-29.1-67.06-29.1-142.73 0-69 24.66-132.62 24.67-63.62 69.71-113.86 12.43-14.15 31.83-14.39 19.39-.24 33.3 13.67 12.67 12.68 11.91 31.45-.76 18.77-12.95 33.68-32.09 37.29-49.78 83.87-17.68 46.59-17.68 98.2 0 114.8 81.16 195.97Q365.2-202.87 480-202.87q115.8 0 196.47-81.16Q757.13-365.2 757.13-480q0-51.85-17.8-99.32-17.81-47.46-50.9-84.98-12.19-14.16-12.69-32.67t12.17-31.18q13.92-13.92 33.19-13.8 19.27.12 31.7 14.04 46.29 50.95 70.81 114.81 24.52 63.86 24.52 133.1 0 75.67-29.1 142.73-29.1 67.05-78.79 117.13-49.7 50.07-116.63 79.17-66.94 29.1-143.61 29.1Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_qrcode.xml b/apps/android/design/src/main/res/drawable/sf_qrcode.xml
new file mode 100644
index 00000000..001251ae
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_qrcode.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `qr_code_2`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M525.5-98v-85.5H611V-98h-85.5ZM440-183.5v-211h85.5v211H440Zm334.59-127.41V-480h85.5v169.09h-85.5ZM689.09-480v-85.5h85.5v85.5h-85.5ZM183.5-394.5V-480H269v85.5h-85.5ZM98-480v-85.5h85.5v85.5H98Zm382-296.5V-862h85.5v85.5H480ZM165.41-672.91h121.68v-121.68H165.41v121.68ZM98-651v-165.5q0-19.15 13.17-32.33Q124.35-862 143.5-862H309q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33V-651q0 19.15-13.17 32.33Q328.15-605.5 309-605.5H143.5q-19.15 0-32.33-13.17Q98-631.85 98-651Zm67.41 485.59h121.68v-121.68H165.41v121.68ZM98-143.5V-309q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17H309q19.15 0 32.33 13.17Q354.5-328.15 354.5-309v165.5q0 19.15-13.17 32.33Q328.15-98 309-98H143.5q-19.15 0-32.33-13.17Q98-124.35 98-143.5Zm574.91-529.41h121.68v-121.68H672.91v121.68ZM605.5-651v-165.5q0-19.15 13.17-32.33Q631.85-862 651-862h165.5q19.15 0 32.33 13.17Q862-835.65 862-816.5V-651q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17H651q-19.15 0-32.33-13.17Q605.5-631.85 605.5-651Zm87.41 553v-127.41h-83.82v-85.5h165.5v127.41h85.5V-98H692.91ZM525.5-394.5V-480h163.59v85.5H525.5Zm-171 0V-480H269v-85.5h256.5v85.5H440v85.5h-85.5Zm40-211v-171H480v87.41h85.5v83.59h-171Zm-197.41-99.09v-58.32h58.32v58.32h-58.32Zm0 507.5v-58.32h58.32v58.32h-58.32Zm507.5-507.5v-58.32h58.32v58.32h-58.32Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_qrcode_viewfinder.xml b/apps/android/design/src/main/res/drawable/sf_qrcode_viewfinder.xml
new file mode 100644
index 00000000..7b48ff73
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_qrcode_viewfinder.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `qr_code_scanner`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M117.37-676.41q-19.15 0-32.33-13.18-13.17-13.17-13.17-32.32v-120.72q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17h120.72q19.15 0 32.32 13.17 13.18 13.18 13.18 32.33t-13.18 32.33q-13.17 13.17-32.32 13.17h-75.22v75.22q0 19.15-13.17 32.32-13.18 13.18-32.33 13.18Zm0 604.54q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33v-120.72q0-19.15 13.17-32.32 13.18-13.18 32.33-13.18t32.33 13.18q13.17 13.17 13.17 32.32v75.22h75.22q19.15 0 32.32 13.17 13.18 13.18 13.18 32.33t-13.18 32.33q-13.17 13.17-32.32 13.17H117.37Zm604.54 0q-19.15 0-32.32-13.17-13.18-13.18-13.18-32.33t13.18-32.33q13.17-13.17 32.32-13.17h75.22v-75.22q0-19.15 13.17-32.32 13.18-13.18 32.33-13.18t32.33 13.18q13.17 13.17 13.17 32.32v120.72q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17H721.91Zm120.72-604.54q-19.15 0-32.33-13.18-13.17-13.17-13.17-32.32v-75.22h-75.22q-19.15 0-32.32-13.17-13.18-13.18-13.18-32.33t13.18-32.33q13.17-13.17 32.32-13.17h120.72q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33v120.72q0 19.15-13.17 32.32-13.18 13.18-32.33 13.18ZM700-200v-60h60v60h-60Zm0-120v-60h60v60h-60Zm-60 60v-60h60v60h-60Zm-60 60v-60h60v60h-60Zm-60-60v-60h60v60h-60Zm120-120v-60h60v60h-60Zm-60 60v-60h60v60h-60Zm-60-60v-60h60v60h-60Zm45.5-140q-19.15 0-32.33-13.17Q520-546.35 520-565.5v-149q0-19.15 13.17-32.33Q546.35-760 565.5-760h149q19.15 0 32.33 13.17Q760-733.65 760-714.5v149q0 19.15-13.17 32.33Q733.65-520 714.5-520h-149Zm-320 320q-19.15 0-32.33-13.17Q200-226.35 200-245.5v-149q0-19.15 13.17-32.33Q226.35-440 245.5-440h149q19.15 0 32.33 13.17Q440-413.65 440-394.5v149q0 19.15-13.17 32.33Q413.65-200 394.5-200h-149Zm0-320q-19.15 0-32.33-13.17Q200-546.35 200-565.5v-149q0-19.15 13.17-32.33Q226.35-760 245.5-760h149q19.15 0 32.33 13.17Q440-733.65 440-714.5v149q0 19.15-13.17 32.33Q413.65-520 394.5-520h-149Zm18.09 256.41h112.82v-112.82H263.59v112.82Zm0-320h112.82v-112.82H263.59v112.82Zm320 0h112.82v-112.82H583.59v112.82Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_rectangle_and_hand_point_up_left.xml b/apps/android/design/src/main/res/drawable/sf_rectangle_and_hand_point_up_left.xml
new file mode 100644
index 00000000..1db46b48
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_rectangle_and_hand_point_up_left.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `touch_app`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M411.59-71.87q-31.92 0-59.85-13.68-27.93-13.69-47.31-38.78l-198.6-252.84q-9.92-11.63-8.32-27.36 1.6-15.73 12.47-25.64l.95-.72q22.4-21.72 52.91-25.48 30.51-3.76 56.9 12.44l67.3 40.45V-721.2q0-18.67 12.82-31.48 12.81-12.82 31.5-12.82 18.68 0 31.87 12.82 13.18 12.81 13.18 31.48v394.5q0 26.35-23.13 39.29-23.13 12.93-46-.5l-36.95-22.24L375.8-177.63q6.72 7.96 15.87 12.55 9.15 4.6 19.44 4.6h232.72q31.22 0 53.46-22.23 22.23-22.24 22.23-53.46v-151.87q0-20.11-13.89-34t-34-13.89H501.72q-18.68 0-31.49-12.82-12.82-12.82-12.82-31.49 0-18.67 12.82-31.49 12.81-12.81 31.49-12.81h169.91q56.7 0 96.6 39.9 39.9 39.9 39.9 96.6v151.87q0 67.91-48.2 116.1-48.19 48.2-116.1 48.2H411.59Zm83.95-270.76ZM474.93-594.5q-18.67 0-31.48-12.82-12.82-12.81-12.82-31.48 0-3.2 5.72-22.16 8-14 12-28.5t4-31.5q0-50-35-85t-85-35q-50 0-85 35t-35 85q0 17 4 31.5t12 28.5q3.24 5.48 4.48 11 1.24 5.53 1.24 11.05 0 18.78-12.44 31.59-12.43 12.82-31.11 12.82-12.43 0-22.77-6.6t-16.05-16.79q-13.24-22.96-20.6-48.97-7.36-26.01-7.36-54.1 0-86.57 61.02-147.59 61.02-61.02 147.6-61.02 86.57 0 147.59 61.03 61.01 61.03 61.01 147.61 0 28.17-7.36 54.13-7.36 25.95-20.6 48.91-5.72 10.19-15.67 16.79-9.96 6.6-22.4 6.6Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_rectangle_portrait_and_arrow_right.xml b/apps/android/design/src/main/res/drawable/sf_rectangle_portrait_and_arrow_right.xml
new file mode 100644
index 00000000..b361bc3e
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_rectangle_portrait_and_arrow_right.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `logout`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M202.87-111.87q-37.78 0-64.39-26.61t-26.61-64.39v-554.26q0-37.78 26.61-64.39t64.39-26.61h233.54q19.16 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.17 13.17-32.33 13.17H202.87v554.26h233.54q19.16 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.17 13.17-32.33 13.17H202.87ZM674.56-434.5H403.59q-19.16 0-32.33-13.17-13.17-13.18-13.17-32.33t13.17-32.33q13.17-13.17 32.33-13.17h270.97L605.07-595q-12.68-12.67-12.68-31.07 0-18.39 12.68-31.82 12.67-13.68 31.7-14.06 19.03-.38 32.71 13.3L816.3-511.83q13.44 13.68 13.44 31.83t-13.44 31.83L669.48-301.35q-13.44 13.68-32.21 13.3-18.77-.38-32.2-14.06-12.68-13.43-12.3-32.21.38-18.77 13.06-31.44l68.73-68.74Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_rectangle_stack_fill.xml b/apps/android/design/src/main/res/drawable/sf_rectangle_stack_fill.xml
new file mode 100644
index 00000000..fbcc0bfc
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_rectangle_stack_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `stacks` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-413.87q-11.43 0-22.25-2.74t-21.01-8.46L105.67-605q-12.43-6.72-17.77-17.15-5.33-10.44-5.33-22.87 0-12.44 5.33-22.75 5.34-10.32 17.77-17.03l331.07-179.94q10.19-5.72 21.01-8.46 10.82-2.73 22.25-2.73t22.25 2.73q10.82 2.74 21.01 8.46L854.33-684.8q12.43 6.71 17.77 17.03 5.33 10.31 5.33 22.75 0 12.43-5.33 22.87-5.34 10.43-17.77 17.15L523.26-425.07q-10.19 5.72-21.01 8.46-10.82 2.74-22.25 2.74Zm0 76.17 312.57-169.8q2.71-1.48 21.15-5.48 18.67 0 31.49 12.82 12.81 12.81 12.81 31.49 0 11.95-5.6 22.15-5.59 10.19-17.55 16.67L523.26-260.28q-10.19 5.71-21.01 8.45-10.82 2.74-22.25 2.74t-22.25-2.86q-10.82-2.85-21.01-8.57L125.37-429.85q-11.96-6.48-17.55-16.67-5.6-10.2-5.6-22.15 0-18.68 12.81-31.49 12.82-12.82 31.49-12.82 5.72 0 10.7 1.5 4.98 1.5 10.45 3.98L480-337.7Zm0 164.79 312.57-169.81q3.19-1.71 21.15-5.24 18.67 0 31.49 12.82 12.81 12.81 12.81 31.49 0 11.95-5.6 22.15-5.59 10.2-17.55 16.67L523.26-95.5q-10.19 5.72-21.01 8.46Q491.43-84.3 480-84.3t-22.25-2.74q-10.82-2.74-21.01-8.46L125.37-264.83q-11.96-6.47-17.55-16.67-5.6-10.2-5.6-22.15 0-18.68 12.81-31.49 12.82-12.82 31.49-12.82 5.48 0 10.58 1.5t10.57 3.98L480-172.91Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_return.xml b/apps/android/design/src/main/res/drawable/sf_return.xml
new file mode 100644
index 00000000..195ce5a6
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_return.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keyboard_return`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m284.91-434.5 106.68 106.67q12.67 12.68 12.67 31.83t-12.67 31.83q-12.68 12.67-31.83 12.67t-31.83-12.67l-184-183.76q-6.71-6.72-9.81-14.92-3.1-8.19-3.1-17.15 0-8.96 3.1-17.15 3.1-8.2 9.81-14.92l184-183.76q12.68-12.67 31.83-12.67t31.83 12.67q12.67 12.68 12.67 31.83t-12.67 31.83L284.91-525.5h472.22V-640q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v114.5q0 37.78-26.61 64.39t-64.39 26.61H284.91Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_rotate_right.xml b/apps/android/design/src/main/res/drawable/sf_rotate_right.xml
new file mode 100644
index 00000000..6ecef1dc
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_rotate_right.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `rotate_right`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M792.15-475.37q-13.91 0-27.08-9.81-13.18-9.82-17.37-24.73-4.29-16.37-10.71-32-6.42-15.63-14.99-30.24-7.72-13.15-5.36-28.81 2.36-15.65 12.79-25.84 16.92-15.92 38.81-13.68t32.85 21.39q12.04 20.81 21.68 42.61 9.64 21.81 15.4 45.37 5.96 21.91-8.21 38.83-14.18 16.91-37.81 16.91ZM522-125.46q0-13.91 9.93-27.08 9.94-13.18 24.85-17.37 16.13-4.29 31.64-10.59 15.51-6.3 29.88-14.87 13.16-7.72 28.81-5.48 15.65 2.24 26.09 12.68 16.15 16.91 14.03 38.8-2.12 21.89-21.27 32.85-21.57 12.04-43.49 21.3-21.93 9.26-44.73 15.79-22.15 5.95-38.95-7.84Q522-101.07 522-125.46Zm207.67-118.71q-10.19-9.44-12.55-25.71-2.36-16.27 5.36-29.42 8.56-14.37 14.75-29.88 6.18-15.52 10.47-31.65 4.19-14.91 16.98-24.72 12.8-9.82 27.47-9.82 24.39 0 38.07 16.67 13.67 16.68 7.71 38.83-6.52 22.8-15.66 44.73-9.14 21.92-21.18 43.49-10.96 19.15-32.73 21.39-21.77 2.24-38.69-13.91ZM387.02-80.91q-120.19-33.44-196.67-131.11-76.48-97.68-76.48-223.35 0-151.91 105.36-258.83 105.36-106.91 256.79-108.82h5.05l-28.55-28.78q-10.76-12.44-10.52-30.52.24-18.07 13.67-31.51 12.68-12.67 31.83-12.67t32.59 12.67l103.24 104q6.71 6.72 9.69 14.8Q636-766.96 636-758t-2.98 17.03q-2.98 8.08-9.69 14.8l-104 104q-12.68 12.67-31.83 12.67t-31.83-12.67Q443-634.85 442.64-652.8q-.36-17.96 9.93-29.92l29.3-29.3h-6.57q-113.65 2.87-192.04 82.93-78.39 80.07-78.39 193.72 0 94.13 56.73 167.08 56.73 72.94 145.86 98.14 15.15 4.19 24.84 16.99 9.7 12.79 9.7 27.7 0 23.63-16.41 37.07-16.42 13.43-38.57 7.48Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_safari.xml b/apps/android/design/src/main/res/drawable/sf_safari.xml
new file mode 100644
index 00000000..868d4af5
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_safari.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `explore`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-440q-17 0-28.5-11.5T440-480q0-17 11.5-28.5T480-520q17 0 28.5 11.5T520-480q0 17-11.5 28.5T480-440Zm0 368.13q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Zm0-91q133.04 0 225.09-92.04 92.04-92.05 92.04-225.09 0-133.04-92.04-225.09-92.05-92.04-225.09-92.04-133.04 0-225.09 92.04-92.04 92.05-92.04 225.09 0 133.04 92.04 225.09 92.05 92.04 225.09 92.04ZM480-480ZM297.72-277.96l248.8-112.45q7.44-3.48 13.51-9.56 6.08-6.07 9.56-13.51l112.45-248.8q4.76-9.76-2.62-17.14-7.38-7.38-17.14-2.62l-248.8 112.45q-7.44 3.48-13.51 9.56-6.08 6.07-9.56 13.51l-112.45 248.8q-4.76 9.76 2.62 17.14 7.38 7.38 17.14 2.62Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_shippingbox.xml b/apps/android/design/src/main/res/drawable/sf_shippingbox.xml
new file mode 100644
index 00000000..e6db3b18
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_shippingbox.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `package_2`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M435.7-188.74v-265.87L202.87-589.54v265.87L435.7-188.74Zm88.6 0 232.83-134.93v-265.87L524.3-454.61v265.87ZM434.5-84.78 157.37-244.11q-21.39-12.43-33.45-33.06-12.05-20.63-12.05-45.5v-314.66q0-24.87 12.05-45.5 12.06-20.63 33.45-33.06L434.5-875.22q21.39-12.43 45.5-12.43t45.5 12.43l277.13 159.33q21.39 12.43 33.45 33.06 12.05 20.63 12.05 45.5v314.66q0 24.87-12.05 45.5-12.06 20.63-33.45 33.06L525.5-84.78Q504.11-72.35 480-72.35t-45.5-12.43Zm204.78-538.76 70.55-40.42L480-796.65l-71.3 41.17 230.58 131.94ZM480-531.02l71.54-41.18-230.06-132.69-71.31 40.93L480-531.02Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_square_and_arrow_down.xml b/apps/android/design/src/main/res/drawable/sf_square_and_arrow_down.xml
new file mode 100644
index 00000000..2e065df6
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_square_and_arrow_down.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `download`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-342.02q-8.96 0-17.15-3.1-8.2-3.1-14.92-9.81L300.35-502.52q-13.44-13.44-13.06-31.83.38-18.39 13.06-31.82 13.67-13.68 32.32-14.06 18.66-.38 32.33 13.29l69.5 69.5v-265.19q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v265.19l69.5-69.5q13.43-13.67 32.09-13.41 18.65.26 32.32 13.94 12.92 13.67 13.3 31.94.38 18.27-13.3 31.95L512.07-354.93q-6.72 6.71-14.92 9.81-8.19 3.1-17.15 3.1ZM242.87-151.87q-37.78 0-64.39-26.61t-26.61-64.39v-74.5q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v74.5h474.26v-74.5q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v74.5q0 37.78-26.61 64.39t-64.39 26.61H242.87Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_square_and_arrow_up.xml b/apps/android/design/src/main/res/drawable/sf_square_and_arrow_up.xml
new file mode 100644
index 00000000..bed57d05
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_square_and_arrow_up.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `ios_share`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M242.87-30.43q-37.78 0-64.39-26.61t-26.61-64.39v-423.74q0-37.79 26.61-64.4 26.61-26.6 64.39-26.6H309q19.15 0 32.33 13.17 13.17 13.17 13.17 32.33 0 19.15-13.17 32.32-13.18 13.18-32.33 13.18h-66.13v423.74h474.26v-423.74H651q-19.15 0-32.33-13.18-13.17-13.17-13.17-32.32 0-19.16 13.17-32.33 13.18-13.17 32.33-13.17h66.13q37.78 0 64.39 26.6 26.61 26.61 26.61 64.4v423.74q0 37.78-26.61 64.39t-64.39 26.61H242.87ZM434.5-755.76l-32.17 32.17q-13.44 13.44-31.83 13.06-18.39-.38-31.83-13.82-12.67-13.43-13.05-31.82-.38-18.4 13.05-31.83l109.26-109.5q13.68-13.67 32.07-13.67t32.07 13.67L621.33-788Q634-775.33 634-756.55q0 18.77-12.67 32.2-13.44 13.44-32.21 13.44-18.77 0-32.21-13.44l-31.41-31.41v398.63q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17t-32.33-13.17q-13.17-13.18-13.17-32.33v-398.63Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_square_and_pencil.xml b/apps/android/design/src/main/res/drawable/sf_square_and_pencil.xml
new file mode 100644
index 00000000..59a7528a
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_square_and_pencil.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `edit_square`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M202.87-111.87q-37.78 0-64.39-26.61t-26.61-64.39v-554.26q0-37.78 26.61-64.39t64.39-26.61h247.37q22.75 0 34.12 14.18 11.38 14.19 11.38 31.21 0 17.02-11.7 31.32-11.69 14.29-34.56 14.29H202.87v554.26h554.26V-450q0-22.75 14.24-34.12 14.24-11.38 31.33-11.38 17.08 0 31.26 11.38 14.17 11.37 14.17 34.12v247.13q0 37.78-26.61 64.39t-64.39 26.61H202.87ZM480-480Zm-123.83 78.33v-92.46q0-18.21 6.84-34.71 6.84-16.51 19.51-29.18l337.07-336.83q13.67-13.67 30.58-20.39 16.92-6.72 34.07-6.72 17.91 0 34.44 6.72 16.54 6.72 30.21 20.39l45.96 46.72q12.91 13.67 19.63 30.23 6.72 16.56 6.72 33.69 0 17.12-6.3 33.74-6.31 16.61-20.05 30.36L558.02-383.28q-12.67 12.67-29.18 19.89-16.5 7.22-34.71 7.22h-92.46q-19.15 0-32.32-13.18-13.18-13.17-13.18-32.32Zm481.72-382.57L785-836.89l52.89 52.65Zm-395.5 341.85h52.65l229.85-229.85-26.24-26.33-27.17-26.32-229.09 228.85v53.65Zm256.26-256.18-27.17-26.32 27.17 26.32 26.24 26.33-26.24-26.33Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_square_grid_2x2.xml b/apps/android/design/src/main/res/drawable/sf_square_grid_2x2.xml
new file mode 100644
index 00000000..085a5a7f
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_square_grid_2x2.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `grid_view`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M202.87-520q-37.54 0-64.27-26.73-26.73-26.73-26.73-64.27v-146.13q0-37.54 26.73-64.27 26.73-26.73 64.27-26.73H349q37.54 0 64.27 26.73Q440-794.67 440-757.13V-611q0 37.54-26.73 64.27Q386.54-520 349-520H202.87Zm0 408.13q-37.54 0-64.27-26.73-26.73-26.73-26.73-64.27V-349q0-37.54 26.73-64.27Q165.33-440 202.87-440H349q37.54 0 64.27 26.73Q440-386.54 440-349v146.13q0 37.54-26.73 64.27-26.73 26.73-64.27 26.73H202.87ZM611-520q-37.54 0-64.27-26.73Q520-573.46 520-611v-146.13q0-37.54 26.73-64.27 26.73-26.73 64.27-26.73h146.13q37.54 0 64.27 26.73 26.73 26.73 26.73 64.27V-611q0 37.54-26.73 64.27Q794.67-520 757.13-520H611Zm0 408.13q-37.54 0-64.27-26.73Q520-165.33 520-202.87V-349q0-37.54 26.73-64.27Q573.46-440 611-440h146.13q37.54 0 64.27 26.73 26.73 26.73 26.73 64.27v146.13q0 37.54-26.73 64.27-26.73 26.73-64.27 26.73H611ZM202.87-611H349v-146.13H202.87V-611ZM611-611h146.13v-146.13H611V-611Zm0 408.13h146.13V-349H611v146.13Zm-408.13 0H349V-349H202.87v146.13ZM611-611Zm0 262Zm-262 0Zm0-262Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_square_grid_3x3.xml b/apps/android/design/src/main/res/drawable/sf_square_grid_3x3.xml
new file mode 100644
index 00000000..61333055
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_square_grid_3x3.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `apps`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M236.44-152.59q-34.46 0-59.16-24.69-24.69-24.7-24.69-59.16 0-34.47 24.69-59.02Q201.98-320 236.44-320q34.47 0 59.02 24.54Q320-270.91 320-236.44q0 34.46-24.54 59.16-24.55 24.69-59.02 24.69Zm243.59 0q-34.46 0-59.04-24.69-24.58-24.7-24.58-59.16 0-34.47 24.55-59.02Q445.5-320 479.97-320q34.46 0 59.04 24.54 24.58 24.55 24.58 59.02 0 34.46-24.55 59.16-24.54 24.69-59.01 24.69Zm243.53 0q-34.47 0-59.02-24.69Q640-201.98 640-236.44q0-34.47 24.54-59.02Q689.09-320 723.56-320q34.46 0 59.16 24.54 24.69 24.55 24.69 59.02 0 34.46-24.69 59.16-24.7 24.69-59.16 24.69ZM236.44-396.41q-34.46 0-59.16-24.55-24.69-24.54-24.69-59.01 0-34.46 24.69-59.04 24.7-24.58 59.16-24.58 34.47 0 59.02 24.55Q320-514.5 320-480.03q0 34.46-24.54 59.04-24.55 24.58-59.02 24.58Zm243.59 0q-34.46 0-59.04-24.55-24.58-24.54-24.58-59.01 0-34.46 24.55-59.04 24.54-24.58 59.01-24.58 34.46 0 59.04 24.55 24.58 24.54 24.58 59.01 0 34.46-24.55 59.04-24.54 24.58-59.01 24.58Zm243.53 0q-34.47 0-59.02-24.55Q640-445.5 640-479.97q0-34.46 24.54-59.04 24.55-24.58 59.02-24.58 34.46 0 59.16 24.55 24.69 24.54 24.69 59.01 0 34.46-24.69 59.04-24.7 24.58-59.16 24.58ZM236.44-640q-34.46 0-59.16-24.54-24.69-24.55-24.69-59.02 0-34.46 24.69-59.16 24.7-24.69 59.16-24.69 34.47 0 59.02 24.69Q320-758.02 320-723.56q0 34.47-24.54 59.02Q270.91-640 236.44-640Zm243.59 0q-34.46 0-59.04-24.54-24.58-24.55-24.58-59.02 0-34.46 24.55-59.16 24.54-24.69 59.01-24.69 34.46 0 59.04 24.69 24.58 24.7 24.58 59.16 0 34.47-24.55 59.02Q514.5-640 480.03-640Zm243.53 0q-34.47 0-59.02-24.54Q640-689.09 640-723.56q0-34.46 24.54-59.16 24.55-24.69 59.02-24.69 34.46 0 59.16 24.69 24.69 24.7 24.69 59.16 0 34.47-24.69 59.02Q758.02-640 723.56-640Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_square_on_square.xml b/apps/android/design/src/main/res/drawable/sf_square_on_square.xml
new file mode 100644
index 00000000..c2733c7e
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_square_on_square.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `content_copy`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M368.37-237.37q-37.78 0-64.39-26.61t-26.61-64.39v-474.26q0-37.78 26.61-64.39t64.39-26.61h354.26q37.78 0 64.39 26.61t26.61 64.39v474.26q0 37.78-26.61 64.39t-64.39 26.61H368.37Zm0-91h354.26v-474.26H368.37v474.26Zm-171 262q-37.78 0-64.39-26.61t-26.61-64.39v-519.76q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v519.76h399.76q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H197.37Zm171-262v-474.26 474.26Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_stop_fill.xml b/apps/android/design/src/main/res/drawable/sf_stop_fill.xml
new file mode 100644
index 00000000..867cbb97
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_stop_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `stop` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M231.87-322.87v-314.26q0-37.78 26.61-64.39t64.39-26.61h314.26q37.78 0 64.39 26.61t26.61 64.39v314.26q0 37.78-26.61 64.39t-64.39 26.61H322.87q-37.78 0-64.39-26.61t-26.61-64.39Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_tab.xml b/apps/android/design/src/main/res/drawable/sf_tab.xml
new file mode 100644
index 00000000..9220fe67
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_tab.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `keyboard_tab`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M842.63-234.5q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33v-400q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v400q0 19.15-13.17 32.33-13.18 13.17-32.33 13.17Zm-299.3-200H117.37q-19.15 0-32.33-13.17Q71.87-460.85 71.87-480t13.17-32.33q13.18-13.17 32.33-13.17h425.96L437.65-632.17q-12.67-12.68-13.05-31.45-.38-18.77 13.05-32.21 12.68-12.67 31.83-12.67t31.82 12.67l183.77 183.76q6.71 6.72 9.81 14.92 3.1 8.19 3.1 17.15 0 8.96-3.1 17.15-3.1 8.2-9.81 14.92L501.3-264.17q-12.67 12.67-31.32 12.79-18.65.12-32.33-12.55-13.67-13.68-13.79-32.45-.12-18.77 13.55-32.45L543.33-434.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_terminal.xml b/apps/android/design/src/main/res/drawable/sf_terminal.xml
new file mode 100644
index 00000000..4ae2c635
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_terminal.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `terminal`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M162.87-151.87q-37.78 0-64.39-26.61t-26.61-64.39v-474.26q0-37.78 26.61-64.39t64.39-26.61h634.26q37.78 0 64.39 26.61t26.61 64.39v474.26q0 37.78-26.61 64.39t-64.39 26.61H162.87Zm0-91h634.26v-394.26H162.87v394.26ZM347-440l-76-76q-12-12-11.5-28t12.5-28q12-11 28-11.5t28 11.5l99.93 99.93q13.68 13.68 13.68 32.07t-13.68 32.07L328-308q-11 11-27.5 11.5T272-308q-11-11-11-28t11-28l75-76Zm173 160q-17 0-28.5-11.5T480-320q0-17 11.5-28.5T520-360h160q17 0 28.5 11.5T720-320q0 17-11.5 28.5T680-280H520Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_text_bubble.xml b/apps/android/design/src/main/res/drawable/sf_text_bubble.xml
new file mode 100644
index 00000000..a4ebdcbc
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_text_bubble.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `chat`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m231.87-231.87-82.44 82.44q-21.63 21.63-49.59 9.77-27.97-11.86-27.97-42.36v-615.11q0-37.78 26.61-64.39t64.39-26.61h634.26q37.78 0 64.39 26.61t26.61 64.39v474.26q0 37.78-26.61 64.39t-64.39 26.61H231.87Zm-34-91h599.26v-474.26H162.87v508.5l35-34.24Zm-35 0v-474.26 474.26ZM280-400h240q17 0 28.5-11.5T560-440q0-17-11.5-28.5T520-480H280q-17 0-28.5 11.5T240-440q0 17 11.5 28.5T280-400Zm0-120h400q17 0 28.5-11.5T720-560q0-17-11.5-28.5T680-600H280q-17 0-28.5 11.5T240-560q0 17 11.5 28.5T280-520Zm0-120h400q17 0 28.5-11.5T720-680q0-17-11.5-28.5T680-720H280q-17 0-28.5 11.5T240-680q0 17 11.5 28.5T280-640Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_trash.xml b/apps/android/design/src/main/res/drawable/sf_trash.xml
new file mode 100644
index 00000000..70f1350e
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_trash.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `delete`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M277.37-111.87q-37.78 0-64.39-26.61t-26.61-64.39v-514.5q-19.15 0-32.33-13.17-13.17-13.18-13.17-32.33t13.17-32.33q13.18-13.17 32.33-13.17H354.5q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17h159.52q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33h168.61q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17v514.5q0 37.78-26.61 64.39t-64.39 26.61H277.37Zm405.26-605.5H277.37v514.5h405.26v-514.5ZM398.57-280.24q17.95 0 30.29-12.34 12.34-12.33 12.34-30.29v-274.74q0-17.96-12.34-30.29-12.34-12.34-30.29-12.34-17.96 0-30.42 12.34-12.45 12.33-12.45 30.29v274.74q0 17.96 12.45 30.29 12.46 12.34 30.42 12.34Zm163.1 0q17.96 0 30.3-12.34 12.33-12.33 12.33-30.29v-274.74q0-17.96-12.33-30.29-12.34-12.34-30.3-12.34-17.95 0-30.41 12.34-12.46 12.33-12.46 30.29v274.74q0 17.96 12.46 30.29 12.46 12.34 30.41 12.34Zm-284.3-437.13v514.5-514.5Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_waveform.xml b/apps/android/design/src/main/res/drawable/sf_waveform.xml
new file mode 100644
index 00000000..05fef22e
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_waveform.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `graphic_eq`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M274.02-277.85v-404.54q0-18.53 12.7-31.06 12.69-12.53 31.13-12.53 18.43 0 31.01 12.53 12.57 12.53 12.57 31.06v404.78q0 18.53-12.53 31.06-12.53 12.53-31.05 12.53-18.44 0-31.13-12.7-12.7-12.69-12.7-31.13Zm162.39 162.39v-729.08q0-18.53 12.53-31.06 12.54-12.53 31.06-12.53t31.06 12.53q12.53 12.53 12.53 31.06v729.08q0 18.53-12.53 31.06Q498.52-71.87 480-71.87T448.94-84.4q-12.53-12.53-12.53-31.06ZM111.87-440.24V-520q0-18.52 12.7-31.06 12.69-12.53 31.13-12.53 18.43 0 31.01 12.7 12.57 12.69 12.57 31.13V-440q0 18.52-12.53 31.06-12.53 12.53-31.05 12.53-18.44 0-31.13-12.7-12.7-12.69-12.7-31.13Zm486.46 162.39v-404.54q0-18.53 12.69-31.06 12.7-12.53 31.13-12.53 18.44 0 31.01 12.53 12.58 12.53 12.58 31.06v404.78q0 18.53-12.53 31.06-12.53 12.53-31.06 12.53-18.43 0-31.13-12.7-12.69-12.69-12.69-31.13Zm162.39-162.39V-520q0-18.52 12.69-31.06 12.7-12.53 31.13-12.53 18.44 0 31.01 12.7 12.58 12.69 12.58 31.13V-440q0 18.52-12.53 31.06-12.53 12.53-31.06 12.53-18.43 0-31.13-12.7-12.69-12.69-12.69-31.13Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_wifi.xml b/apps/android/design/src/main/res/drawable/sf_wifi.xml
new file mode 100644
index 00000000..f79675f7
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_wifi.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `wifi`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-120q-42 0-71-29t-29-71q0-42 29-71t71-29q42 0 71 29t29 71q0 42-29 71t-71 29Zm0-440q74.28 0 140.95 23.52 66.66 23.52 121.42 64.57 20.96 15.48 21.58 41.41.62 25.93-18.34 44.89-18.2 18.2-44.63 19.06-26.44.85-47.87-13.62-36.81-24.57-80.53-38.49-43.73-13.93-92.58-13.93-48.61 0-92.22 13.81-43.61 13.8-80.41 38.37-21.67 14.48-48.23 13.36-26.55-1.12-44.75-19.32-18.19-18.96-17.96-44.77.24-25.82 21.2-41.29 54.76-41.05 121.42-64.31Q405.72-560 480-560Zm0-240q124.04 0 233.71 40.52 109.66 40.52 197.42 114.33 21.2 17.72 22.44 44.03 1.23 26.32-17.96 45.51-18.2 18.2-44.63 18.82-26.44.62-47.87-16.1-71.04-57.09-158.15-88.39-87.11-31.31-184.96-31.31-97.85 0-184.96 31.31-87.11 31.3-158.15 88.39-21.43 16.72-47.75 16.1-26.31-.62-44.51-18.82-19.2-19.19-18.08-45.51 1.12-26.31 22.32-44.03 87.76-73.81 197.42-114.33Q355.96-800 480-800Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_wifi_exclamationmark.xml b/apps/android/design/src/main/res/drawable/sf_wifi_exclamationmark.xml
new file mode 100644
index 00000000..c0670bc0
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_wifi_exclamationmark.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `signal_wifi_bad`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="m766.46-200.52-52.18 51.41q-12.67 12.68-31.32 12.94-18.66.26-32.33-13.18-12.91-12.67-12.91-31.82 0-19.16 12.91-32.07l51.94-51.93-52.18-52.18q-12.91-12.91-12.79-31.94.12-19.04 13.03-31.95t31.95-12.91q19.03 0 31.94 12.91l51.94 52.17 52.17-52.17q12.91-12.91 31.57-12.91 18.65 0 32.32 12.91 13.68 13.68 13.68 32.33t-13.68 32.32l-51.41 51.42L882.52-213q12.68 12.67 13.06 31.33.38 18.65-13.3 32.32-12.67 12.68-31.82 12.8-19.16.12-31.83-12.56l-52.17-51.41ZM480-804.07q111.33 0 215.53 35.39 104.21 35.38 191.25 102.94 16.92 12.44 25.25 30.85 8.34 18.41 8.34 37.56 0 18.44-6.74 35.99-6.74 17.56-20.7 32.23l-41.45 42.41q-13.2 13.16-32.09 14.02-18.89.85-32.8-12.34-13.92-13.2-14.39-31.97-.48-18.77 12.71-32.68l44.98-46.18q-76.13-57.61-165.42-87.41-89.3-29.81-184.47-29.81t-184.47 29.81q-89.29 29.8-165.42 87.41L480-235.2l8.37-8.37q14.15-10.32 31.73-9.36 17.57.95 30.05 13.91 13.2 13.43 13.32 31.85.12 18.41-12.84 32.08l-8.37 8.37q-12.96 13.44-29.27 20.16-16.32 6.71-32.99 6.71t-32.99-6.71q-16.31-6.72-29.27-20.16L67.78-529.11q-13.95-14.43-20.43-31.61-6.48-17.17-6.48-35.61 0-19.39 7.96-37.8 7.95-18.41 24.63-31.85 87.04-67.56 191.13-102.82Q368.67-804.07 480-804.07Zm0 329.94Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_wifi_slash.xml b/apps/android/design/src/main/res/drawable/sf_wifi_slash.xml
new file mode 100644
index 00000000..15d6be0a
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_wifi_slash.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `wifi_off`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M758.65-82.8 415.91-427.07q-29.32 6.77-56.03 17.81t-50.03 26.61q-22.92 14.48-49.73 14.98-26.82.5-45.25-18.7-19.2-19.2-17.82-46.13 1.38-26.93 22.82-42.65 21.56-15.81 45.39-28.97 23.83-13.16 49.15-24.45l-84.5-84.5q-24.56 13.53-47.51 27.95-22.94 14.42-44.51 30.99-21.43 16.72-48.25 16.72-26.81 0-45.01-19.2-19.2-19.19-18.08-45.51 1.12-26.31 22.32-43.27 20.8-17.04 42.37-32.35 21.56-15.3 45.41-28.35l-54.08-54.08q-11.72-11.72-11.6-29.2.12-17.48 11.83-29.2 11.72-11.71 29.32-11.71t29.31 11.71l676.61 676.61q12.48 12.48 12.48 29.58 0 17.1-12.48 29.58-12.47 11.71-29.69 12.09-17.22.38-29.7-12.09ZM480-120q-42 0-71-29.5T380-220q0-42 29-71t71-29q42 0 71 29t29 71q0 41-29 70.5T480-120Zm274.43-276.43q-15.52 15.52-36.18 15.14-20.66-.38-36.18-15.91-5-5-10.24-10.23l-10.24-10.24-90.98-90.74q-13.24-13.24-4.88-27.48t27.64-9.24q43.33 11.24 82.15 30.88 38.83 19.64 72.39 45.68 17.29 13.53 19.67 35.07 2.38 21.54-13.15 37.07Zm161.18-159.94q-18.2 18.96-44.63 19.58-26.44.62-47.87-16.1-71.04-57.09-158.15-88.39-87.11-31.31-184.96-31.31-17.89 0-34.64 1.14-16.75 1.15-33.88 3.67-26.68 3.76-47.51-12.06-20.84-15.81-24.6-42.49-3.76-26.67 12.31-47.63 16.08-20.95 42.76-24.47 20.89-3.29 42.28-4.43Q458.11-800 480-800q124.28 0 234.07 41.02 109.78 41.02 197.78 113.78 20.72 17.48 21.72 43.68 1 26.19-17.96 45.15Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_wrench_and_screwdriver.xml b/apps/android/design/src/main/res/drawable/sf_wrench_and_screwdriver.xml
new file mode 100644
index 00000000..0edaa16d
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_wrench_and_screwdriver.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `build`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M356.41-354.5q-102.87 0-175.14-72.27Q109-499.04 109-601.91q0-20 3.24-40T123-680.39q5.24-10.72 13.46-16.44 8.21-5.71 18.17-7.71t20.17.74q10.22 2.73 18.7 11.21L296.59-589.5l72-72L265.5-764.59q-8.48-8.48-11.22-18.77-2.74-10.3-.74-20.06 2-9.75 7.6-17.97 5.6-8.22 16.32-13.46 18.47-7.76 38.83-11t40.12-3.24q102.99 0 175.08 72.1 72.1 72.09 72.1 175.08 0 22.4-3.64 42.36-3.65 19.96-11.17 39.96l206.07 204.07Q826-284.37 826-239.5t-31.1 76.02q-31.1 31.15-76.14 31.15t-76.19-31.91L438.5-369.3q-19.28 7.28-38.95 11.04-19.66 3.76-43.14 3.76Zm0-87.41q26 0 52-8t47-25L705.83-224.5q5 5 13.5 4.5t13.5-5.5q5-5 5-13.5t-5-13.5L482.41-501.91q18-20 26-46.5t8-53.5q0-60-38.5-104.5t-95.5-53.5l69.94 69.93q13.67 13.76 13.67 32.11t-13.67 32.02L332.48-505.98q-13.76 13.68-32.11 13.68t-32.02-13.68l-69.94-69.93q9 57 53.5 95.5t104.5 38.5ZM469-489.09Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_xmark.xml b/apps/android/design/src/main/res/drawable/sf_xmark.xml
new file mode 100644
index 00000000..a6f084aa
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_xmark.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `close`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-416.35 287.83-224.17Q275.15-211.5 256-211.5t-31.83-12.67Q211.5-236.85 211.5-256t12.67-31.83L416.35-480 224.17-672.17Q211.5-684.85 211.5-704t12.67-31.83Q236.85-748.5 256-748.5t31.83 12.67L480-543.65l192.17-192.18Q684.85-748.5 704-748.5t31.83 12.67Q748.5-723.15 748.5-704t-12.67 31.83L543.65-480l192.18 192.17Q748.5-275.15 748.5-256t-12.67 31.83Q723.15-211.5 704-211.5t-31.83-12.67L480-416.35Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_xmark_circle.xml b/apps/android/design/src/main/res/drawable/sf_xmark_circle.xml
new file mode 100644
index 00000000..b67010e1
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_xmark_circle.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `cancel`, Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-421.37 592.17-309.2q11.72 11.72 29.32 11.6 17.6-.12 29.31-11.83 11.72-11.72 11.72-29.32t-11.72-29.32L538.63-480 650.8-592.17q11.72-11.72 11.72-29.32T650.8-650.8q-11.71-11.72-29.31-11.72-17.6 0-29.32 11.72L480-538.63 367.83-650.8q-11.72-11.72-29.2-11.72-17.48 0-29.2 11.72-11.71 11.71-11.71 29.31 0 17.6 11.71 29.32L421.37-480 309.2-367.83q-11.72 11.72-11.6 29.2.12 17.48 11.83 29.2 11.72 11.71 29.32 11.71t29.32-11.71L480-421.37Zm0 349.5q-84.91 0-159.35-32.1-74.43-32.1-129.51-87.17-55.07-55.08-87.17-129.51-32.1-74.44-32.1-159.35t32.1-159.35q32.1-74.43 87.17-129.51 55.08-55.07 129.51-87.17 74.44-32.1 159.35-32.1t159.35 32.1q74.43 32.1 129.51 87.17 55.07 55.08 87.17 129.51 32.1 74.44 32.1 159.35t-32.1 159.35q-32.1 74.43-87.17 129.51-55.08 55.07-129.51 87.17-74.44 32.1-159.35 32.1Zm0-91q133.04 0 225.09-92.04 92.04-92.05 92.04-225.09 0-133.04-92.04-225.09-92.05-92.04-225.09-92.04-133.04 0-225.09 92.04-92.04 92.05-92.04 225.09 0 133.04 92.04 225.09 92.05 92.04 225.09 92.04ZM480-480Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/drawable/sf_xmark_circle_fill.xml b/apps/android/design/src/main/res/drawable/sf_xmark_circle_fill.xml
new file mode 100644
index 00000000..8ac63e93
--- /dev/null
+++ b/apps/android/design/src/main/res/drawable/sf_xmark_circle_fill.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Material Symbols Rounded `cancel` (filled), Generated by tools/symbols.py. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">
+ <group android:translateY="960">
+ <path android:fillColor="#FF000000" android:pathData="M480-421.37 592.17-309.2q11.72 11.72 29.32 11.6 17.6-.12 29.31-11.83 11.72-11.72 11.72-29.32t-11.72-29.32L538.63-480 650.8-592.17q11.72-11.72 11.72-29.32T650.8-650.8q-11.71-11.72-29.31-11.72-17.6 0-29.32 11.72L480-538.63 367.83-650.8q-11.72-11.72-29.2-11.72-17.48 0-29.2 11.72-11.71 11.71-11.71 29.31 0 17.6 11.71 29.32L421.37-480 309.2-367.83q-11.72 11.72-11.6 29.2.12 17.48 11.83 29.2 11.72 11.71 29.32 11.71t29.32-11.71L480-421.37Zm0 349.5q-84.91 0-159.35-32.1-74.43-32.1-129.51-87.17-55.07-55.08-87.17-129.51-32.1-74.44-32.1-159.35t32.1-159.35q32.1-74.43 87.17-129.51 55.08-55.07 129.51-87.17 74.44-32.1 159.35-32.1t159.35 32.1q74.43 32.1 129.51 87.17 55.07 55.08 87.17 129.51 32.1 74.44 32.1 159.35t-32.1 159.35q-32.1 74.43-87.17 129.51-55.08 55.07-129.51 87.17-74.44 32.1-159.35 32.1Z"/>
+ </group>
+</vector>
diff --git a/apps/android/design/src/main/res/font/inter.ttf b/apps/android/design/src/main/res/font/inter.ttf
new file mode 100644
index 00000000..4ab79e01
Binary files /dev/null and b/apps/android/design/src/main/res/font/inter.ttf differ
diff --git a/apps/android/design/src/test/kotlin/com/codync/android/design/ThinkingOrbGeometryTest.kt b/apps/android/design/src/test/kotlin/com/codync/android/design/ThinkingOrbGeometryTest.kt
new file mode 100644
index 00000000..c3723251
--- /dev/null
+++ b/apps/android/design/src/test/kotlin/com/codync/android/design/ThinkingOrbGeometryTest.kt
@@ -0,0 +1,38 @@
+package com.codync.android.design
+
+import java.io.File
+import kotlin.math.abs
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.double
+import kotlinx.serialization.json.int
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** The port draws exactly what thinking-orbs' golden frames (shared with the iOS tests) hold. */
+class ThinkingOrbGeometryTest {
+ @Test fun `frames match the upstream golden vectors`() {
+ val fixture = Json.parseToJsonElement(File(System.getProperty("codync.orbs")).readText()).jsonObject
+ val tolerance = fixture.getValue("tolerance").jsonPrimitive.double
+ for (case in fixture.getValue("cases").jsonArray.map { it.jsonObject }) {
+ val key = case.getValue("key").jsonPrimitive.content
+ val state = ThinkingOrbState.valueOf(case.getValue("state").jsonPrimitive.content.replaceFirstChar(Char::uppercase))
+ val frame = ThinkingOrbGeometry.frame(state, case.getValue("size").jsonPrimitive.double, case.getValue("t").jsonPrimitive.double)
+ assertEquals("$key dots", case.getValue("dotCount").jsonPrimitive.int, frame.dots.size)
+ assertEquals("$key lines", case.getValue("lineCount").jsonPrimitive.int, frame.lines.size)
+ for (sample in case.getValue("dots").jsonArray.map { it.jsonObject }) {
+ val d = frame.dots.getOrNull(sample.getValue("index").jsonPrimitive.int) ?: continue
+ listOf(d.x, d.y, d.z, d.radius, d.white, d.alpha).zip(sample.getValue("values").jsonArray.map { it.jsonPrimitive.double })
+ .forEach { (actual, expected) -> assertTrue("$key dot: $actual != $expected", abs(actual - expected) <= tolerance) }
+ }
+ for (sample in case["lines"]?.jsonArray.orEmpty().map { it.jsonObject }) {
+ val l = frame.lines.getOrNull(sample.getValue("index").jsonPrimitive.int) ?: continue
+ listOf(l.x1, l.y1, l.x2, l.y2, l.white, l.alpha, l.width).zip(sample.getValue("values").jsonArray.map { it.jsonPrimitive.double })
+ .forEach { (actual, expected) -> assertTrue("$key line: $actual != $expected", abs(actual - expected) <= tolerance) }
+ }
+ }
+ }
+}
diff --git a/apps/android/gradle.properties b/apps/android/gradle.properties
new file mode 100644
index 00000000..964d8e6a
--- /dev/null
+++ b/apps/android/gradle.properties
@@ -0,0 +1,4 @@
+org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
+android.useAndroidX=true
+kotlin.code.style=official
+
diff --git a/apps/android/gradle/libs.versions.toml b/apps/android/gradle/libs.versions.toml
new file mode 100644
index 00000000..c28f5e01
--- /dev/null
+++ b/apps/android/gradle/libs.versions.toml
@@ -0,0 +1,76 @@
+[versions]
+agp = "9.4.1"
+kotlin = "2.4.20"
+compose = "2026.09.00"
+activity = "1.12.2"
+lifecycle = "2.10.0"
+coroutines = "1.10.2"
+serialization = "1.9.0"
+okhttp = "4.12.0"
+bouncycastle = "1.86"
+junit = "4.13.2"
+androidx-test = "1.7.0"
+androidx-junit = "1.3.0"
+commonmark = "0.30.0"
+desugar = "2.1.5"
+coil = "3.4.0"
+clerk = "1.1.11"
+firebase = "34.19.0"
+google-services = "4.5.0"
+work = "2.12.0"
+camera = "1.6.2"
+zxing = "3.5.4"
+vosk = "0.3.75"
+jna = "5.18.1"
+glance = "1.2.0"
+backdrop = "2.0.1"
+kyant-shapes = "1.2.1"
+
+[libraries]
+compose-bom = { module = "androidx.compose:compose-bom", version.ref = "compose" }
+compose-ui = { module = "androidx.compose.ui:ui" }
+compose-foundation = { module = "androidx.compose.foundation:foundation" }
+compose-material3 = { module = "androidx.compose.material3:material3" }
+compose-tooling = { module = "androidx.compose.ui:ui-tooling" }
+compose-test = { module = "androidx.compose.ui:ui-test-junit4" }
+compose-test-manifest = { module = "androidx.compose.ui:ui-test-manifest" }
+activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activity" }
+lifecycle-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }
+lifecycle-viewmodel = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycle" }
+coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
+coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutines" }
+coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
+serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization" }
+okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }
+mockwebserver = { module = "com.squareup.okhttp3:mockwebserver", version.ref = "okhttp" }
+bouncycastle = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" }
+junit = { module = "junit:junit", version.ref = "junit" }
+androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidx-test" }
+androidx-test-junit = { module = "androidx.test.ext:junit", version.ref = "androidx-junit" }
+commonmark = { module = "org.commonmark:commonmark", version.ref = "commonmark" }
+commonmark-tables = { module = "org.commonmark:commonmark-ext-gfm-tables", version.ref = "commonmark" }
+commonmark-strikethrough = { module = "org.commonmark:commonmark-ext-gfm-strikethrough", version.ref = "commonmark" }
+desugar = { module = "com.android.tools:desugar_jdk_libs", version.ref = "desugar" }
+coil-compose = { module = "io.coil-kt.coil3:coil-compose", version.ref = "coil" }
+coil-network = { module = "io.coil-kt.coil3:coil-network-okhttp", version.ref = "coil" }
+clerk = { module = "com.clerk:clerk-android-api", version.ref = "clerk" }
+firebase-bom = { module = "com.google.firebase:firebase-bom", version.ref = "firebase" }
+firebase-messaging = { module = "com.google.firebase:firebase-messaging" }
+work = { module = "androidx.work:work-runtime", version.ref = "work" }
+camera-core = { module = "androidx.camera:camera-core", version.ref = "camera" }
+camera-camera2 = { module = "androidx.camera:camera-camera2", version.ref = "camera" }
+camera-lifecycle = { module = "androidx.camera:camera-lifecycle", version.ref = "camera" }
+camera-view = { module = "androidx.camera:camera-view", version.ref = "camera" }
+zxing = { module = "com.google.zxing:core", version.ref = "zxing" }
+vosk = { module = "com.alphacephei:vosk-android", version.ref = "vosk" }
+glance = { module = "androidx.glance:glance-appwidget", version.ref = "glance" }
+backdrop = { module = "io.github.kyant0:backdrop", version.ref = "backdrop" }
+kyant-shapes = { module = "io.github.kyant0:shapes", version.ref = "kyant-shapes" }
+
+[plugins]
+android-application = { id = "com.android.application", version.ref = "agp" }
+android-library = { id = "com.android.library", version.ref = "agp" }
+kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
+kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
+kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
+google-services = { id = "com.google.gms.google-services", version.ref = "google-services" }
diff --git a/apps/android/gradle/wrapper/gradle-wrapper.jar b/apps/android/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 00000000..b1b8ef56
Binary files /dev/null and b/apps/android/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/apps/android/gradle/wrapper/gradle-wrapper.properties b/apps/android/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 00000000..65d8749e
--- /dev/null
+++ b/apps/android/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,10 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionSha256Sum=bbaeb2fef8710818cf0e261201dab964c572f92b942812df0c3620d62a529a01
+distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip
+networkTimeout=10000
+retries=0
+retryBackOffMs=500
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/apps/android/gradlew b/apps/android/gradlew
new file mode 100755
index 00000000..249efbb0
--- /dev/null
+++ b/apps/android/gradlew
@@ -0,0 +1,248 @@
+#!/bin/sh
+
+#
+# Copyright © 2015 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# gradlew start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh gradlew
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/apps/android/gradlew.bat b/apps/android/gradlew.bat
new file mode 100644
index 00000000..8508ef68
--- /dev/null
+++ b/apps/android/gradlew.bat
@@ -0,0 +1,82 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem gradlew startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables, and ensure extensions are enabled
+setlocal EnableExtensions
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+"%COMSPEC%" /c exit 1
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+"%COMSPEC%" /c exit 1
+
+:execute
+@rem Setup the command line
+
+
+
+@rem Execute gradlew
+@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
+@rem which allows us to clear the local environment before executing the java command
+endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
+
+:exitWithErrorLevel
+@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
+"%COMSPEC%" /c exit %ERRORLEVEL%
diff --git a/apps/android/settings.gradle.kts b/apps/android/settings.gradle.kts
new file mode 100644
index 00000000..683e2de1
--- /dev/null
+++ b/apps/android/settings.gradle.kts
@@ -0,0 +1,25 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ ivy {
+ name = "VoskModels"
+ url = uri("https://alphacephei.com/vosk/models")
+ patternLayout { artifact("[artifact]-[revision].[ext]") }
+ metadataSources { artifact() }
+ content { includeGroup("com.alphacephei.models") }
+ }
+ }
+}
+
+rootProject.name = "CodyncAndroid"
+include(":app", ":core", ":design")
diff --git a/apps/android/tools/agent_icons.py b/apps/android/tools/agent_icons.py
new file mode 100644
index 00000000..fa13c7bc
--- /dev/null
+++ b/apps/android/tools/agent_icons.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python3
+"""Regenerates the Android agent logos from the desktop app's one-color SVGs.
+
+Each `apps/desktop/src/renderer/assets/agents/<registry>.svg` made only of paths becomes
+`app/src/main/res/drawable/agent_<registry>.xml` (tinted at runtime, as the iOS template images
+are); logos with other shapes fall back to the terminal glyph. Also writes `AgentIcons.kt`, the
+`agentIconRes("claude-acp")` lookup.
+
+Run from apps/android: python3 tools/agent_icons.py
+"""
+import pathlib
+import re
+import xml.etree.ElementTree as ET
+
+ROOT = pathlib.Path(__file__).resolve().parent.parent
+SOURCE = ROOT.parent / "desktop/src/renderer/assets/agents"
+DRAWABLES = ROOT / "app/src/main/res/drawable"
+KOTLIN = ROOT / "app/src/main/kotlin/com/codync/android/AgentIcons.kt"
+SVG = "{http://www.w3.org/2000/svg}"
+IGNORED = {"title", "desc"}
+
+
+def resource(registry: str) -> str:
+ return "agent_" + re.sub(r"[^a-z0-9]", "_", registry.lower())
+
+
+def compact(d: str, size: float) -> str:
+ """Rounds path numbers to what a 24dp icon can show (lint flags long paths)."""
+ places = max(1, 4 - len(str(int(size))))
+ return re.sub(r"-?\d*\.\d+", lambda m: f"{float(m.group()):.{places}f}".rstrip("0").rstrip("."), d)
+
+
+def convert(svg: pathlib.Path) -> str | None:
+ root = ET.parse(svg).getroot()
+ shapes = [e for e in root.iter() if e is not root and e.tag.removeprefix(SVG) not in IGNORED]
+ if not shapes or any(e.tag.removeprefix(SVG) != "path" or "transform" in e.attrib for e in shapes):
+ return None
+ x, y, w, h = (float(v) for v in root.attrib["viewBox"].replace(",", " ").split())
+ body = []
+ for path in shapes:
+ fill = path.get("fill", root.get("fill", "black"))
+ stroke = path.get("stroke", root.get("stroke", "none"))
+ attrs = [f'android:pathData="{compact(path.attrib["d"], max(w, h))}"']
+ if fill != "none":
+ attrs.append('android:fillColor="#FF000000"')
+ if path.get("fill-rule", root.get("fill-rule")) == "evenodd":
+ attrs.append('android:fillType="evenOdd"')
+ if "fill-opacity" in path.attrib:
+ attrs.append(f'android:fillAlpha="{path.attrib["fill-opacity"]}"')
+ if stroke != "none":
+ attrs.append('android:strokeColor="#FF000000"')
+ attrs.append(f'android:strokeWidth="{path.get("stroke-width", root.get("stroke-width", "1"))}"')
+ for svg_name, android in (("stroke-linecap", "strokeLineCap"), ("stroke-linejoin", "strokeLineJoin")):
+ value = path.get(svg_name, root.get(svg_name))
+ if value:
+ attrs.append(f'android:{android}="{value}"')
+ body.append(" <path " + " ".join(attrs) + "/>\n")
+ group = f' <group android:translateX="{0.0 - x:g}" android:translateY="{0.0 - y:g}">\n'
+ return (
+ '<?xml version="1.0" encoding="utf-8"?>\n'
+ f"<!-- {svg.name} from the desktop app's agent logos. Generated by tools/agent_icons.py. -->\n"
+ '<vector xmlns:android="http://schemas.android.com/apk/res/android"\n'
+ f' android:width="24dp" android:height="24dp" android:viewportWidth="{w:g}" android:viewportHeight="{h:g}">\n'
+ f"{group}{''.join(body)} </group>\n"
+ "</vector>\n"
+ )
+
+
+def main() -> None:
+ for old in DRAWABLES.glob("agent_*.xml"):
+ old.unlink()
+ made = []
+ for svg in sorted(SOURCE.glob("*.svg")):
+ xml = convert(svg)
+ if xml is None:
+ continue
+ (DRAWABLES / f"{resource(svg.stem)}.xml").write_text(xml)
+ made.append(svg.stem)
+ cases = "\n".join(f' "{r}" -> R.drawable.{resource(r)}' for r in made)
+ KOTLIN.write_text(
+ "// Generated by tools/agent_icons.py: the agent logos converted from the desktop app's SVGs.\n"
+ "package com.codync.android\n\n"
+ "import androidx.annotation.DrawableRes\n\n"
+ "/** The logo for an agent's ACP registry id (or Codync's id for agents outside it), or null. */\n"
+ "@DrawableRes internal fun agentIconRes(registry: String?): Int? = when (registry) {\n"
+ f"{cases}\n"
+ " else -> null\n"
+ "}\n"
+ )
+ print(f"{len(made)} of {len(list(SOURCE.glob('*.svg')))} logos")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/apps/android/tools/fixtures/setup-agent.py b/apps/android/tools/fixtures/setup-agent.py
new file mode 100644
index 00000000..dbe84194
--- /dev/null
+++ b/apps/android/tools/fixtures/setup-agent.py
@@ -0,0 +1,47 @@
+#!/usr/bin/env python3
+"""Inert ACP provider for LiveTerminalTest; copy into the isolated fixture host."""
+import json
+import os
+import pathlib
+import sys
+import uuid
+
+directory = pathlib.Path(os.environ["CODYNC_HOME"]).resolve()
+if "codync-android-chat-" not in str(directory) or directory.name != "host":
+ raise RuntimeError("This provider requires the isolated Android acceptance host")
+marker = directory / "agents/android-setup-fixture/1/signed-in"
+
+if "--terminal" in sys.argv:
+ assert sys.stdin.isatty() and sys.stdout.isatty()
+ print("\033[32mFixture setup ready: café 🐈\033[0m", flush=True)
+ for value in sys.stdin:
+ if value.strip() == "fixture-answer":
+ marker.write_text("fixture")
+ print("Fixture answer accepted", flush=True)
+ sys.exit(0)
+ sys.exit(1)
+
+for line in sys.stdin:
+ request = json.loads(line)
+ if "id" not in request:
+ continue
+ method = request.get("method")
+ if method == "initialize":
+ result = {"protocolVersion": 1, "agentCapabilities": {}, "authMethods": [
+ {"id": "fixture-terminal", "name": "Fixture terminal sign-in", "_meta": {"terminal-auth": {
+ "command": sys.executable, "args": [__file__, "--terminal"]}}},
+ {"id": "fixture-keys", "name": "Fixture key", "type": "env_var", "vars": [
+ {"name": "CODYNC_ACCEPTANCE_KEY", "label": "Fixture key", "secret": True, "optional": False}]},
+ ]}
+ elif method == "session/new":
+ if not marker.exists() and os.environ.get("CODYNC_ACCEPTANCE_KEY") != "fixture-key":
+ print(json.dumps({"jsonrpc": "2.0", "id": request["id"], "error": {
+ "code": -32000, "message": "Fixture sign-in required"}}), flush=True)
+ continue
+ result = {"sessionId": str(uuid.uuid4())}
+ elif method == "authenticate":
+ marker.write_text("fixture")
+ result = {}
+ else:
+ result = {}
+ print(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}), flush=True)
diff --git a/apps/android/tools/launcher_icon.py b/apps/android/tools/launcher_icon.py
new file mode 100644
index 00000000..498b7874
--- /dev/null
+++ b/apps/android/tools/launcher_icon.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python3
+"""Regenerates the Android launcher and notification icons from the desktop app's icon.svg,
+so every platform shows the same dotted Codync face. Run from apps/android."""
+import pathlib
+import re
+
+ROOT = pathlib.Path(__file__).resolve().parent.parent
+svg = (ROOT / "../desktop/resources/icon.svg").read_text()
+dots = [tuple(map(float, m)) for m in re.findall(r'cx="([\d.]+)" cy="([\d.]+)" r="([\d.]+)"', svg)]
+
+
+def path(scale: float, dx: float) -> str:
+ out = []
+ for cx, cy, r in dots:
+ x, y, rr = cx * scale + dx, cy * scale + dx, r * scale
+ out.append(f"M{x - rr:.3f},{y:.3f}a{rr:.3f},{rr:.3f} 0 1,0 {2 * rr:.3f},0a{rr:.3f},{rr:.3f} 0 1,0 {-2 * rr:.3f},0")
+ return "".join(out)
+
+
+def vector(size: int, data: str, color: str) -> str:
+ return ('<?xml version="1.0" encoding="utf-8"?>\n<!-- Generated by tools/launcher_icon.py from desktop/resources/icon.svg. -->\n'
+ f'<vector xmlns:android="http://schemas.android.com/apk/res/android"\n'
+ f' android:width="{size}dp" android:height="{size}dp" android:viewportWidth="{size}" android:viewportHeight="{size}">\n'
+ f' <path android:fillColor="{color}" android:pathData="{data}"/>\n</vector>\n')
+
+
+res = ROOT / "app/src/main/res"
+# Adaptive icons draw on 108 dp and the mask shows the middle 72 dp; the face keeps its iOS proportion
+# inside round masks too.
+(res / "drawable/ic_launcher_foreground.xml").write_text(vector(108, path(64 / 256, 22), "#FFFFFFFF"))
+# The status bar icon: the face alone, filling its 24 dp box.
+(res / "drawable/ic_notification.xml").write_text(vector(24, path(24 / 196, -128 * 24 / 196 + 12), "#FFFFFFFF"))
+(res / "mipmap-anydpi-v26").mkdir(exist_ok=True)
+for name in ("ic_launcher", "ic_launcher_round"):
+ (res / f"mipmap-anydpi-v26/{name}.xml").write_text(
+ '<?xml version="1.0" encoding="utf-8"?>\n<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">\n'
+ ' <background android:drawable="@color/ic_launcher_background"/>\n'
+ ' <foreground android:drawable="@drawable/ic_launcher_foreground"/>\n'
+ ' <monochrome android:drawable="@drawable/ic_launcher_foreground"/>\n</adaptive-icon>\n')
+print(f"{len(dots)} dots")
diff --git a/apps/android/tools/symbols.py b/apps/android/tools/symbols.py
new file mode 100644
index 00000000..9e3bffe0
--- /dev/null
+++ b/apps/android/tools/symbols.py
@@ -0,0 +1,246 @@
+#!/usr/bin/env python3
+"""Regenerates the Android stand-ins for the SF Symbols the iOS app names.
+
+SF Symbols may only ship on Apple platforms, so Android draws Material Symbols Rounded
+(Apache-2.0) at weight 500, the closest match to SF's medium weight. Each SF name maps to
+one Material symbol; `.fill` names take the filled variant. Output:
+ design/src/main/res/drawable/sf_*.xml vector drawables
+ design/src/main/kotlin/.../Symbols.kt `symbolRes("chevron.down")` lookup
+
+Run from apps/android: python3 tools/symbols.py
+"""
+import pathlib
+import re
+import urllib.request
+
+# SF Symbol name -> Material Symbols name ("+" suffix: filled variant).
+MAP = {
+ "app": "apps",
+ "apple.logo": None, # drawn from the bundled brand mark, not a symbol
+ "arrow.clockwise": "refresh",
+ "arrow.counterclockwise": "replay",
+ "arrow.down": "arrow_downward",
+ "arrow.down.circle": "arrow_circle_down",
+ "arrow.down.circle.fill": "arrow_circle_down+",
+ "arrow.down.doc.on.clipboard": "content_paste_go",
+ "arrow.down.right.and.arrow.up.left": "close_fullscreen",
+ "arrow.down.to.line": "vertical_align_bottom",
+ "arrow.left": "arrow_back",
+ "arrow.left.arrow.right": "swap_horiz",
+ "arrow.right": "arrow_forward",
+ "arrow.right.doc.on.clipboard": "content_paste_go",
+ "arrow.right.to.line": "keyboard_tab",
+ "arrow.triangle.2.circlepath": "sync",
+ "arrow.triangle.branch": "call_split",
+ "arrow.up": "arrow_upward",
+ "arrow.up.doc.on.clipboard": "content_paste_go",
+ "arrow.up.right": "arrow_outward",
+ "arrowshape.turn.up.left": "reply",
+ "battery.100percent": "battery_full_alt",
+ "battery.75percent": "battery_horiz_075",
+ "bell": "notifications",
+ "bolt": "bolt",
+ "book.fill": "book+",
+ "book.pages": "menu_book",
+ "brain": "psychology",
+ "bubble.left.and.bubble.right": "forum",
+ "bubble.left.and.bubble.right.fill": "forum+",
+ "calendar": "calendar_today",
+ "camera.fill": "photo_camera+",
+ "chart.bar": "bar_chart",
+ "checklist": "checklist",
+ "checkmark": "check",
+ "checkmark.circle": "check_circle",
+ "checkmark.circle.fill": "check_circle+",
+ "checkmark.message": "mark_chat_read",
+ "checkmark.seal": "verified",
+ "chevron.down": "keyboard_arrow_down",
+ "chevron.left": "chevron_left",
+ "chevron.right": "chevron_right",
+ "chevron.up": "keyboard_arrow_up",
+ "circle": "radio_button_unchecked",
+ "circle.dotted": "motion_photos_on",
+ "clock": "schedule",
+ "clock.arrow.circlepath": "history",
+ "clock.fill": "schedule+",
+ "cloud": "cloud",
+ "cloud.sun.fill": "partly_cloudy_day+",
+ "command": "keyboard_command_key",
+ "control": "keyboard_control_key",
+ "crop": "crop",
+ "cursorarrow.motionlines": "arrow_selector_tool",
+ "desktopcomputer": "desktop_mac",
+ "desktopcomputer.trianglebadge.exclamationmark": "desktop_access_disabled",
+ "display": "monitor",
+ "display.2": "desktop_windows",
+ "doc": "draft",
+ "doc.badge.plus": "note_add",
+ "doc.on.clipboard": "content_paste",
+ "doc.on.clipboard.fill": "content_paste+",
+ "doc.on.doc": "content_copy",
+ "doc.richtext": "article",
+ "doc.text": "description",
+ "doc.zipper": "folder_zip",
+ "ellipsis": "more_horiz",
+ "envelope.fill": "mail+",
+ "escape": "keyboard_return",
+ "exclamationmark": "priority_high",
+ "exclamationmark.circle": "error",
+ "exclamationmark.circle.fill": "error+",
+ "exclamationmark.triangle": "warning",
+ "exclamationmark.triangle.fill": "warning+",
+ "eye": "visibility",
+ "eye.slash": "visibility_off",
+ "figure.run": "directions_run",
+ "folder": "folder",
+ "function": "function",
+ "gearshape": "settings",
+ "gearshape.fill": "settings+",
+ "globe": "language",
+ "hand.point.up.left": "touch_app",
+ "hand.raised": "front_hand",
+ "hand.raised.fill": "front_hand+",
+ "hand.raised.slash": "do_not_touch",
+ "heart.fill": "favorite+",
+ "info.circle": "info",
+ "italic": "format_italic",
+ "key": "key",
+ "key.fill": "key+",
+ "keyboard": "keyboard",
+ "keyboard.chevron.compact.down": "keyboard_hide",
+ "laptopcomputer": "laptop_mac",
+ "list.bullet": "format_list_bulleted",
+ "list.bullet.rectangle": "list_alt",
+ "lock.display": "screen_lock_landscape",
+ "lock.fill": "lock+",
+ "lock.rectangle": "password",
+ "lock.shield": "shield_lock",
+ "lock.slash": "lock_open",
+ "magnifyingglass": "search",
+ "map.fill": "map+",
+ "mic": "mic",
+ "mic.fill": "mic+",
+ "mic.slash": "mic_off",
+ "move": "open_with",
+ "music.note": "music_note",
+ "network": "public",
+ "note.text": "sticky_note_2",
+ "option": "keyboard_option_key",
+ "paintbrush": "brush",
+ "paintpalette": "palette",
+ "pause.fill": "pause+",
+ "pencil": "edit",
+ "person.2": "group",
+ "person.crop.circle": "account_circle",
+ "person.crop.circle.badge.checkmark": "how_to_reg",
+ "person.fill": "person+",
+ "phone.fill": "call+",
+ "photo": "image",
+ "photo.fill": "image+",
+ "photo.on.rectangle": "photo_library",
+ "pin": "keep",
+ "pin.fill": "keep+",
+ "pin.slash": "keep_off",
+ "play.circle": "play_circle",
+ "play.circle.fill": "play_circle+",
+ "play.fill": "play_arrow+",
+ "plus": "add",
+ "plus.circle": "add_circle",
+ "plus.rectangle.on.rectangle": "library_add",
+ "point.3.connected.trianglepath.dotted": "hub",
+ "power": "power_settings_new",
+ "qrcode": "qr_code_2",
+ "qrcode.viewfinder": "qr_code_scanner",
+ "rectangle.and.hand.point.up.left": "touch_app",
+ "rectangle.portrait.and.arrow.right": "logout",
+ "rectangle.stack.fill": "stacks+",
+ "return": "keyboard_return",
+ "rotate.right": "rotate_right",
+ "safari": "explore",
+ "shippingbox": "package_2",
+ "square.and.arrow.down": "download",
+ "square.and.arrow.up": "ios_share",
+ "square.and.pencil": "edit_square",
+ "square.grid.2x2": "grid_view",
+ "square.grid.3x3": "apps",
+ "square.on.square": "content_copy",
+ "stop.fill": "stop+",
+ "tab": "keyboard_tab",
+ "terminal": "terminal",
+ "text.bubble": "chat",
+ "trash": "delete",
+ "waveform": "graphic_eq",
+ "wifi": "wifi",
+ "wifi.exclamationmark": "signal_wifi_bad",
+ "wifi.slash": "wifi_off",
+ "wrench.and.screwdriver": "build",
+ "xmark": "close",
+ "xmark.circle": "cancel",
+ "xmark.circle.fill": "cancel+",
+}
+
+ROOT = pathlib.Path(__file__).resolve().parent.parent
+DRAWABLES = ROOT / "design/src/main/res/drawable"
+KOTLIN = ROOT / "design/src/main/kotlin/com/codync/android/design/Symbols.kt"
+BASE = "https://raw.githubusercontent.com/google/material-design-icons/master/symbols/web"
+# Symbols iOS draws at regular weight (the toolbar's plus).
+REGULAR = {"add"}
+
+
+def url(base: str, filled: bool) -> str:
+ variant = ("" if base in REGULAR else "wght500") + ("fill1" if filled else "")
+ return f"{BASE}/{base}/materialsymbolsrounded/{base}{'_' + variant if variant else ''}_24px.svg"
+
+
+def resource(name: str) -> str:
+ return "sf_" + re.sub(r"[^a-z0-9]", "_", name)
+
+
+def fetch(symbol: str) -> str:
+ filled = symbol.endswith("+")
+ base = symbol.rstrip("+")
+ with urllib.request.urlopen(url(base, filled)) as response:
+ svg = response.read().decode()
+ paths = re.findall(r'<path d="([^"]+)"', svg)
+ if not paths:
+ raise SystemExit(f"no path in {base}")
+ body = "".join(f' <path android:fillColor="#FF000000" android:pathData="{d}"/>\n' for d in paths)
+ return (
+ '<?xml version="1.0" encoding="utf-8"?>\n'
+ f"<!-- Material Symbols Rounded `{base}`{' (filled)' if filled else ''}, Generated by tools/symbols.py. -->\n"
+ '<vector xmlns:android="http://schemas.android.com/apk/res/android"\n'
+ ' android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">\n'
+ ' <group android:translateY="960">\n'
+ f"{body}"
+ " </group>\n"
+ "</vector>\n"
+ )
+
+
+def main() -> None:
+ DRAWABLES.mkdir(parents=True, exist_ok=True)
+ for old in DRAWABLES.glob("sf_*.xml"):
+ old.unlink()
+ cache: dict[str, str] = {}
+ for name, symbol in sorted(MAP.items()):
+ if symbol is None:
+ continue
+ if symbol not in cache:
+ cache[symbol] = fetch(symbol)
+ (DRAWABLES / f"{resource(name)}.xml").write_text(cache[symbol])
+ cases = "\n".join(f' "{n}" -> R.drawable.{resource(n)}' for n, s in sorted(MAP.items()) if s is not None)
+ KOTLIN.write_text(
+ "// Generated by tools/symbols.py: the Material Symbols standing in for SF Symbol names.\n"
+ "package com.codync.android.design\n\n"
+ "import androidx.annotation.DrawableRes\n\n"
+ "/** The drawable for an SF Symbol name the iOS app uses, or null when Android has none. */\n"
+ "@DrawableRes fun symbolRes(name: String): Int? = when (name) {\n"
+ f"{cases}\n"
+ " else -> null\n"
+ "}\n"
+ )
+ print(f"{len(cache)} symbols, {len(MAP)} names")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/apps/android/tools/vendor-terminal.py b/apps/android/tools/vendor-terminal.py
new file mode 100644
index 00000000..216448cd
--- /dev/null
+++ b/apps/android/tools/vendor-terminal.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python3
+"""Rebuild the offline terminal assets from integrity-pinned MIT npm releases."""
+import base64
+import hashlib
+import io
+import json
+import pathlib
+import subprocess
+import tarfile
+import tempfile
+import urllib.request
+
+DESTINATION = pathlib.Path(__file__).resolve().parents[1] / "app/src/main/assets/terminal"
+ESBUILD = "0.28.2"
+PACKAGES = [
+ ("@xterm/xterm", "6.0.0", "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==",
+ {"lib/xterm.js": "xterm.js", "css/xterm.css": "xterm.css", "LICENSE": "LICENSE.xterm"}),
+ ("@xterm/addon-fit", "0.11.0", "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==",
+ {"lib/addon-fit.js": "addon-fit.js", "LICENSE": "LICENSE.addon-fit"}),
+ ("@xterm/addon-web-links", "0.12.0", "sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw==",
+ {"lib/addon-web-links.js": "addon-web-links.js", "LICENSE": "LICENSE.addon-web-links"}),
+]
+
+def main():
+ files = {}
+ manifest = []
+ with tempfile.TemporaryDirectory(prefix="codync-terminal-vendor-") as temporary:
+ for package, version, integrity, selected in PACKAGES:
+ name = package.split("/")[-1]
+ url = f"https://registry.npmjs.org/{package}/-/{name}-{version}.tgz"
+ with urllib.request.urlopen(url, timeout=30) as response:
+ archive = response.read()
+ actual = "sha512-" + base64.b64encode(hashlib.sha512(archive).digest()).decode()
+ if actual != integrity:
+ raise ValueError(f"Integrity mismatch for {package}")
+ entry = {"package": package, "version": version, "integrity": integrity, "license": "MIT",
+ "source": "https://github.com/xtermjs/xterm.js/tree/6.0.0", "files": {}, "originalFiles": {}}
+ with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as tar:
+ for source, target in selected.items():
+ with tar.extractfile("package/" + source) as stream:
+ data = stream.read()
+ entry["originalFiles"][target] = hashlib.sha256(data).hexdigest()
+ if target.endswith(".js"):
+ # xterm 6 uses class static blocks; old Android WebViews cannot parse them.
+ result = subprocess.run(["npx", "--yes", f"esbuild@{ESBUILD}", "--target=chrome83",
+ "--minify", "--legal-comments=inline"], input=data,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True,
+ cwd=temporary)
+ data = result.stdout
+ files[target] = data
+ entry["files"][target] = hashlib.sha256(data).hexdigest()
+ entry["transform"] = {"tool": "esbuild", "version": ESBUILD, "target": "chrome83",
+ "options": ["--minify", "--legal-comments=inline"]}
+ manifest.append(entry)
+ for target, data in files.items():
+ (DESTINATION / target).write_bytes(data)
+ (DESTINATION / "vendor-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
+ print("Verified and rebuilt the bundled terminal assets.")
+
+if __name__ == "__main__":
+ main()
diff --git a/cloud/migrations/0004_android_devices.sql b/cloud/migrations/0004_android_devices.sql
new file mode 100644
index 00000000..4965bc80
--- /dev/null
+++ b/cloud/migrations/0004_android_devices.sql
@@ -0,0 +1,50 @@
+-- Keep IDs and authorization history. Rebuild the two referencing tables too:
+-- dropping/replacing a populated parent alone leaves D1's deferred FK counter
+-- violated even when the replacement has the same IDs.
+CREATE TABLE devices_android (
+ id TEXT PRIMARY KEY,
+ owner_user_id TEXT NOT NULL REFERENCES accounts(user_id),
+ sign_pub TEXT NOT NULL,
+ name TEXT NOT NULL,
+ platform TEXT NOT NULL CHECK (platform IN ('ios','macos','linux','windows','android')),
+ created_at INTEGER NOT NULL,
+ last_used_at INTEGER,
+ revoked_at INTEGER,
+ UNIQUE (owner_user_id, sign_pub)
+);
+INSERT INTO devices_android SELECT id, owner_user_id, sign_pub, name, platform, created_at, last_used_at, revoked_at FROM devices;
+CREATE TABLE grants_android (
+ id TEXT PRIMARY KEY,
+ computer_id TEXT NOT NULL REFERENCES computers(id),
+ device_id TEXT NOT NULL REFERENCES devices_android(id),
+ scopes TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('active','revoked')),
+ created_at INTEGER NOT NULL,
+ revoked_at INTEGER,
+ revoked_reason TEXT
+);
+INSERT INTO grants_android SELECT * FROM grants;
+CREATE TABLE access_requests_android (
+ id TEXT PRIMARY KEY,
+ computer_id TEXT NOT NULL REFERENCES computers(id),
+ device_id TEXT NOT NULL REFERENCES devices_android(id),
+ user_id TEXT NOT NULL REFERENCES accounts(user_id),
+ status TEXT NOT NULL CHECK (status IN ('pending','approved','denied','expired','cancelled')),
+ commit_hash TEXT NOT NULL,
+ host_nonce TEXT,
+ device_nonce TEXT,
+ created_at INTEGER NOT NULL,
+ expires_at INTEGER NOT NULL,
+ decided_at INTEGER,
+ grant_id TEXT
+);
+INSERT INTO access_requests_android SELECT * FROM access_requests;
+DROP TABLE grants;
+DROP TABLE access_requests;
+DROP TABLE devices;
+ALTER TABLE devices_android RENAME TO devices;
+ALTER TABLE grants_android RENAME TO grants;
+ALTER TABLE access_requests_android RENAME TO access_requests;
+CREATE UNIQUE INDEX grants_active ON grants(computer_id, device_id) WHERE status = 'active';
+CREATE INDEX access_requests_computer ON access_requests(computer_id, status);
+CREATE UNIQUE INDEX access_requests_one_pending ON access_requests(computer_id, device_id) WHERE status = 'pending';
diff --git a/cloud/src/routes/account.ts b/cloud/src/routes/account.ts
index b30557e3..049864d4 100644
--- a/cloud/src/routes/account.ts
+++ b/cloud/src/routes/account.ts
@@ -58,7 +58,7 @@ export async function registerDevice(c: Ctx) {
const s = await signed(c);
const b = body(c);
const name = str(b, "name");
- const platform = oneOf(b, "platform", ["ios", "macos", "linux", "windows"] as const);
+ const platform = oneOf(b, "platform", ["ios", "macos", "linux", "windows", "android"] as const);
const existing = await c.env.DB.prepare("SELECT * FROM devices WHERE owner_user_id = ? AND sign_pub = ?")
.bind(u.userId, s.kid)
.first<DeviceRow>();
diff --git a/cloud/test/android.test.ts b/cloud/test/android.test.ts
new file mode 100644
index 00000000..4ead288e
--- /dev/null
+++ b/cloud/test/android.test.ts
@@ -0,0 +1,52 @@
+import { applyD1Migrations } from "cloudflare:test";
+import { env as rawEnv } from "cloudflare:workers";
+import { describe, expect, it } from "vitest";
+import { call, clerkToken, env } from "./helpers";
+import * as ref from "./ref";
+
+describe("Android devices", () => {
+ it("registers a signed Android client and preserves revocation", async () => {
+ const userId = "user_android_" + ref.b64url(ref.random(8));
+ const token = await clerkToken(userId);
+ const key = ref.signKey();
+ const registered = await call("POST", "/v1/devices", { token, key, body: { name: "Samsung", platform: "android" } });
+ expect(registered.status).toBe(200);
+ expect(registered.body.device.platform).toBe("android");
+ const listed = await call("GET", "/v1/devices", { token });
+ expect(listed.body.devices[0].platform).toBe("android");
+ const revoked = await call("DELETE", "/v1/devices/" + registered.body.device.deviceId, { token });
+ expect(revoked.status).toBe(200);
+ const refused = await call("POST", "/v1/devices", { token, key, body: { name: "Samsung", platform: "android" } });
+ expect(refused.status).toBe(403);
+ });
+
+ it("adds Android after the existing desktop migration without losing authorizations or constraints", async () => {
+ const db = (rawEnv as unknown as { ANDROID_MIGRATION_DB: D1Database }).ANDROID_MIGRATION_DB;
+ const androidMigration = env.TEST_MIGRATIONS.findIndex(migration => migration.name === "0004_android_devices.sql");
+ expect(androidMigration).toBeGreaterThan(0);
+ await applyD1Migrations(db, env.TEST_MIGRATIONS.slice(0, androidMigration));
+ await db.batch([
+ db.prepare("INSERT INTO accounts(user_id,created_at) VALUES ('android-owner',1)"),
+ db.prepare("INSERT INTO computers(id,sign_pub,box_pub,owner_user_id,name,platform,version,created_at,updated_at) VALUES ('host','sign','box','android-owner','Host','linux','2.4.0',1,1)"),
+ ...["ios", "linux", "macos", "windows"].map(platform => db.prepare("INSERT INTO devices(id,owner_user_id,sign_pub,name,platform,created_at,last_used_at,revoked_at) VALUES (?, 'android-owner', ?, ?, ?, 1, 2, 3)").bind(platform, platform + "-key", platform, platform)),
+ db.prepare("INSERT INTO grants(id,computer_id,device_id,scopes,status,created_at) VALUES ('grant','host','ios','[\"control\"]','revoked',1)"),
+ db.prepare("INSERT INTO access_requests(id,computer_id,device_id,user_id,status,commit_hash,created_at,expires_at) VALUES ('request','host','windows','android-owner','denied','hash',1,2)"),
+ ]);
+ const tables = ["devices", "grants", "access_requests"];
+ const before = await Promise.all(tables.map(table => db.prepare(`SELECT * FROM ${table} ORDER BY id`).all()));
+ await applyD1Migrations(db, env.TEST_MIGRATIONS.slice(androidMigration));
+ const after = await Promise.all(tables.map(table => db.prepare(`SELECT * FROM ${table} ORDER BY id`).all()));
+ expect(after.map(result => result.results)).toEqual(before.map(result => result.results));
+ const old = await db.prepare("SELECT platform,created_at,last_used_at,revoked_at FROM devices ORDER BY platform").all();
+ expect(old.results).toEqual(["ios", "linux", "macos", "windows"].map(platform => ({ platform, created_at: 1, last_used_at: 2, revoked_at: 3 })));
+ const grant = await db.prepare("SELECT device_id FROM grants").first();
+ const request = await db.prepare("SELECT device_id FROM access_requests").first();
+ expect(grant).toEqual({ device_id: "ios" });
+ expect(request).toEqual({ device_id: "windows" });
+ const foreignKeys = await db.prepare("PRAGMA foreign_key_check").all();
+ expect(foreignKeys.results).toEqual([]);
+ await db.prepare("INSERT INTO devices(id,owner_user_id,sign_pub,name,platform,created_at) VALUES ('android','android-owner','android-key','Samsung','android',1)").run();
+ await expect(db.prepare("INSERT INTO devices(id,owner_user_id,sign_pub,name,platform,created_at) VALUES ('duplicate','android-owner','android-key','Duplicate','android',1)").run()).rejects.toThrow();
+ await expect(db.prepare("INSERT INTO devices(id,owner_user_id,sign_pub,name,platform,created_at) VALUES ('other','missing','other-key','Other','android',1)").run()).rejects.toThrow();
+ });
+});
diff --git a/cloud/vitest.config.ts b/cloud/vitest.config.ts
index 06ff026f..02f0e260 100644
--- a/cloud/vitest.config.ts
+++ b/cloud/vitest.config.ts
@@ -11,6 +11,7 @@ export default defineConfig(async () => ({
cloudflareTest({
wrangler: { configPath: "./wrangler.toml", environment: "dev" },
miniflare: {
+ d1Databases: ["ANDROID_MIGRATION_DB"],
// The pool's bundled workerd trails wrangler's; pin to the newest date it supports.
compatibilityDate: "2026-08-22",
bindings: {
diff --git a/docs/README.md b/docs/README.md
index 5055cc7e..e6b1ec93 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -11,6 +11,8 @@ Source review, a passing build, local integration tests and production acceptanc
| Understand clients, host, cloud and data ownership | [Architecture](architecture/overview.md) |
| Work on the macOS, Linux and Windows desktop app (Electron) | [Desktop app](architecture/desktop-app.md) |
| Build, install, restart and run checks | [Development](guides/development.md) |
+| Upgrade Sean's local app and private infrastructure | [Local upgrade guide](guides/local-upgrades.md) |
+| Plan and build Android | [Android plan](plans/android-app.md), [Android status](../apps/android/README.md) |
| Test a phone over Cloudflare instead of LAN | [Cloudflare testing](guides/cloudflare-testing.md) |
| Configure dev/main or deploy the services | [Environments and deployment](guides/environments-and-deployment.md) |
| Run the host on a Linux server or cloud VM | [Linux servers](guides/linux-servers.md) |
diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.md
index af485604..aff1edf5 100644
--- a/docs/architecture/file-structure.md
+++ b/docs/architecture/file-structure.md
@@ -48,6 +48,11 @@ Codync/
│ │ ├── src/preload/ # window.codync bridge
│ │ ├── src/renderer/ # React UI: store/, components/, views/
│ │ └── native/ # codync-speech (macOS on-device speech helper)
+│ ├── android/ # Android phone app (Kotlin, Compose), ported from the iPhone app
+│ │ ├── core/ # JVM models, crypto, pairing, encrypted channel, host and cloud clients
+│ │ ├── design/ # Codync's components: palette, type, motion, glass, sheets, menus, dialogs, controls, symbols
+│ │ ├── app/ # Screens, the store (AppStore), notifications, Live updates, Glance widgets
+│ │ └── tools/ # symbols.py (SF Symbol stand-ins), launcher_icon.py, agent_icons.py
│ ├── screen-macos/ # macOS screen helper (Xcode Screen target)
│ └── screen-linux/ # Linux portal/GStreamer screen helper
├── cloud/ # Account API + encrypted relay Worker and Durable Object
@@ -73,6 +78,7 @@ Codync/
- `Screen` (`apps/screen-macos/`) — Codync Screen: capture, input and WebRTC for Remote screen, embedded in the macOS desktop app (`Contents/Library/LoginItems`); starts the computer-use driver it carries in `Contents/Helpers`
- `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`)
+- `apps/android/` — Android app (`com.pokai.Codync.android`, Dev `.dev`; Gradle modules `app`, `core`, `design`; CI `.github/workflows/android.yml`)
- `CodyncKit` (`apps/ios/Kit/`) — the iPhone app's Swift package: `CodyncKit` + `CodyncUI` libraries (tests: `xcodebuild test -scheme CodyncKit-Package` on an iOS simulator)
## Where to make a change
@@ -102,6 +108,10 @@ Codync/
| Cloud routes / authentication / relay | `cloud/src/index.ts`, `api.ts`, `routes/`, `auth.ts`, `relay.ts` |
| Push encryption / APNs delivery / decryption | `host/src/remote/push.rs`, `relay/src/`, `apps/ios/NotificationService/` |
| Widget and activity rendering | `apps/ios/Kit/Sources/CodyncKit/Design/`, `apps/ios/Widgets/` |
+| Android screens (one file per iOS view: `BotListView.kt`, `ChatScreen.kt`, `PairingView.kt`, `SettingsView.kt`, …) | `apps/android/app/src/main/kotlin/com/codync/android/` |
+| Android components and glass | `apps/android/design/` (`Controls.kt`, `Chrome.kt`, `Sheet.kt`, `Menus.kt`, `Dialog.kt`, `Glass.kt`) |
+| Android transport, pairing and wire models | `apps/android/core/` (`EncryptedChannel.kt`, `HostConnector.kt`, `Pairing.kt`, `Compatibility.kt`) |
+| Android widgets, Live updates, push | `apps/android/app/` (`CodyncWidgets.kt`, `WidgetCards.kt`, `LiveUpdateGallery.kt`, `PushService.kt`) |
## Dependency rules
@@ -109,6 +119,7 @@ Codync/
- `CodyncUI` owns the iPhone app's observable stores and screens. App-specific lifecycle, OAuth configuration and device hooks belong in `apps/`.
- Each `BotStore` (Swift, and its TypeScript port in the desktop app) talks to one computer. `AccountStore` aggregates stores and routes by `BotReference`; bare bot IDs are not globally unique.
- The host owns routing, reply counts, permissions and group turn scheduling. Clients render these results; they do not reimplement host policy.
+- Android: `core` is plain JVM (no Android or Compose imports) and `design` holds no I/O; `app` uses both. Like the other clients it renders host state and sends intents, never product logic.
- `cloud/` transports encrypted chat traffic and manages account metadata. `relay/` delivers APNs pushes. The two Workers have separate configuration and tests.
## Names
diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.md
index 841783d1..c76f5ef7 100644
--- a/docs/design/ui-conventions.md
+++ b/docs/design/ui-conventions.md
@@ -53,6 +53,7 @@ The iPhone and the desktop no longer share UI code. `CodyncUI` (`apps/ios/Kit/`)
- The iPhone chat's chrome is in `ThreadView.swift` (`body`, `chrome`, `header`). The iPhone conversation (chat and thread) is a UIKit collection view of hosted SwiftUI rows (`ConversationList.swift`): it loads earlier messages from the computer as the reader scrolls up, runs under the bars and the composer (the list sits in the safe area and reaches past it, so rows never get a safe area of their own), follows the newest message until they scroll away (with a round "Jump to latest" button), and pops each new message in ([chat messages](../features/chat-messages.md)).
- The desktop UI rules (custom controls, no system menus except the tray, icon-only buttons, fill or border) are implemented in `apps/desktop/src/renderer/components/` (`Controls.tsx`, `Overlay.tsx`, `Icon.tsx`).
+- The Android app (`apps/android/`) ports the iPhone screens one to one in Compose. Where iOS uses system UI (the tab bar, menus, sheets, Liquid Glass), Android draws the same look with its `design` module: glass from Kyant's backdrop library (blur, lens refraction and highlight on RenderEffect/RuntimeShader), the iOS sheet with its grabber and drag-to-close, glass menus and context menus, Inter for SF Pro and Material Symbols for SF Symbols (`Symbol("sf.name")`). Android has no Liquid Glass of its own; Material widgets aren't used.
- A change to one lands in the other and the TUI in the same change; see [native client parity](#native-client-parity).
## Shared application controls
diff --git a/docs/features/analytics.md b/docs/features/analytics.md
index 487ffca2..8cc38a76 100644
--- a/docs/features/analytics.md
+++ b/docs/features/analytics.md
@@ -5,8 +5,8 @@ every device; *Share usage analytics* in Settings turns it off. It exists to spo
(failed or stopped turns per agent and platform) and to serve users better. The public promise
lives in `web/app/privacy/page.tsx`: keep it true. The info button beside the switch (terminal
UI: *About usage analytics…*) shows the same promise in the app, in one text per client
-(desktop `views/settings/AnalyticsSheet.tsx`, `CodyncUI/AnalyticsSheet.swift`,
-`host/src/tui/view/analytics.rs`): change all three with the policy.
+(desktop `views/settings/AnalyticsSheet.tsx`, `CodyncUI/AnalyticsSheet.swift`, Android
+`AnalyticsSheet.kt`, `host/src/tui/view/analytics.rs`): change all four with the policy.
## Rules
@@ -16,7 +16,7 @@ UI: *About usage analytics…*) shows the same promise in the app, in one text p
Errors are categories and code locations, never an error's message (see *Error tracking*).
- **Setting per device.** The computer's owner decides for that computer (host kv
`analytics_enabled`, on unless `0`); each iPhone decides for itself (`UserDefaults`
- `analyticsEnabled`, on unless `false`). Turning it off drops anything still queued. A
+ `analyticsEnabled`, on unless `false`; each Android phone in its `codync-analytics` preferences). Turning it off drops anything still queued. A
device that said no to the earlier opt-in question stays off.
- **Identity.** Every device gets a person profile. Signed in to a Codync account: the Clerk
user id. Otherwise a random install id (the host id on a computer, a UUID on the iPhone).
@@ -47,6 +47,8 @@ UI: *About usage analytics…*) shows the same promise in the app, in one text p
- **iPhone** (`CodyncKit` analytics client, no SDK) sends its own app-level events
(`app_opened`, `onboarding_completed`, `computer_paired`, `signed_in`, `signed_out`,
`voice_call_started`) straight to PostHog. Widgets and the notification extension never send.
+ **Android** (`apps/android/.../Analytics.kt`, its port, no SDK) sends the same events with
+ `$lib` `codync-android`; widgets never send.
## Event properties
@@ -80,6 +82,9 @@ builds PostHog's generic `custom` frames (oldest first, the failing one last).
- **iPhone** (`CodyncKit` `CrashReports`): MetricKit's crash diagnostics, delivered on the next
launch, straight to PostHog with the version that crashed. Frames are `binary + offset`
(unsymbolicated; Xcode Organizer has the symbolicated crash). Process `ios`.
+- **Android** (`CrashReports.kt`): an uncaught exception is written down as it happens and sent
+ on the next launch: its type and frames (class, method, file name, line), never the message.
+ Process `android`.
What leaves the device: the error's type (`Panic`, `TypeError`, `EXC_BAD_ACCESS`), how it was
caught, function names, and file names and line numbers inside Codync's code; an absolute path
@@ -115,6 +120,6 @@ join an iPhone's `computer_paired` to the computer's events on `computer` in SQL
## Turning it off
No client asks: sharing starts with the first launch. Every client has the same switch,
-*Share usage analytics* (iPhone and desktop Settings → Privacy, terminal UI `^k`). The App
+*Share usage analytics* (iPhone, Android and desktop Settings, terminal UI `^k`). The App
Store privacy label declares *Product Interaction* and *Coarse Location*, linked to the user, not used
for tracking (the same two in `apps/ios/Resources/PrivacyInfo.xcprivacy`).
diff --git a/docs/guides/dev-app.md b/docs/guides/dev-app.md
index 3f3f0bd7..3ac91d13 100644
--- a/docs/guides/dev-app.md
+++ b/docs/guides/dev-app.md
@@ -28,6 +28,7 @@ Xcode configurations separate environment from optimization: `Debug` and `Releas
| iOS App Group | `group.com.pokai.Codync` | `group.com.pokai.Codync.dev` |
| iOS Keychain group (team prefix omitted) | `com.pokai.Codync` | `com.pokai.Codync.dev` |
| Desktop bundle | `com.pokai.Codync` | `com.pokai.Codync.dev` |
+| Android application ID | `com.pokai.Codync.android` | `com.pokai.Codync.android.dev` |
| Linux package / Windows package cache | `codync-desktop` | `codync-desktop-dev` |
| Desktop account callback | `com.pokai.Codync://callback` | `com.pokai.Codync.dev://callback` |
| Pairing and widget links | `codync://` | `codync-dev://` |
diff --git a/docs/guides/development.md b/docs/guides/development.md
index 6f468401..bc7a47ba 100644
--- a/docs/guides/development.md
+++ b/docs/guides/development.md
@@ -93,8 +93,8 @@ git config core.hooksPath .githooks
It runs CI's checks for each part a commit touches, so a failure shows up before the push:
host (`cargo fmt --check`, clippy, `cargo test` and the memory tests, with CI's pinned Engram
fetched once into `host/target/engram-test-runtime`), desktop, cloud and relay (`npm run typecheck`,
-`npm test`), Linux screen helper formatting, and a parse of the macOS screen helper's Swift
-sources (on macOS). It checks the staged files only, in a copy under `.git/precommit-snapshot`,
+`npm test`), the Android app (core and app unit tests and a Kotlin compile, with JDK 21), Linux
+screen helper formatting, and a parse of the macOS screen helper's Swift sources (on macOS). It checks the staged files only, in a copy under `.git/precommit-snapshot`,
so other agents' uncommitted edits in the same checkout neither break nor rescue a commit; the
host builds into `host/target/precommit`, and its tests are stopped after 5 minutes so a hung
test fails the commit instead of holding it. The npm checks reuse each package's `node_modules`
diff --git a/docs/plans/android-app.md b/docs/plans/android-app.md
new file mode 100644
index 00000000..a6cb2e0f
--- /dev/null
+++ b/docs/plans/android-app.md
@@ -0,0 +1,63 @@
+# Android parity and acceptance
+
+Status: **in review** (PR #151). The Android app is a 1:1 port of the iPhone app: each screen
+is built from its iOS source (`apps/ios/Views`, `apps/ios/Kit/Sources/CodyncUI`) with the
+Android `design` module (see the [Android README](../../apps/android/README.md)). Product
+logic stays in the host. This checklist tracks what's still different and what still needs
+acceptance on real devices.
+
+## Coverage
+
+"Ported" means the iOS screen and flow exist on Android and were walked through on an
+emulator against a real host; device acceptance is listed separately.
+
+| Area | Android | Remaining |
+| --- | --- | --- |
+| Welcome/pairing | Ported: welcome crew and chat glimpse, Install (Mac/Linux) and Scan pages with the camera on the page, paste link, Tailscale note, sign-in | Physical optical scan, camera permission denial |
+| Accounts/access | Ported: account sheet and switcher, Computers & settings, account computer access with its code, access banner | Provider browser round trip on a device; one computer per phone ([multiple computers are future work](../architecture/overview.md)) |
+| Roster | Ported: rows, menus, pin/hide/delete, groups, drag to reorder (host-synced order), computer header | Multiple computers |
+| Conversation/threads | Ported: bubbles, Markdown/code, permissions, reactions, threads, Full conversation, bot-to-bot exchange lines and their conversation, routine notices | Physical keyboard and TalkBack |
+| Composer | Ported: files/photos/paste, `/` commands (Fast mode, New session, skills), @mentions in groups, call/send/stop button | — |
+| Bot and group editors | Ported: avatar, profile, agent and model options, Fast mode, workspace folder picker, permissions, activity, connectors, skills | — |
+| Memory | Ported: search, filters, add/edit, pin, review, history and timeline, export/import, forget all | — |
+| Routines | Ported: list with switches, editor (schedule, webhook panel, run settings), test run, delete | Live provider/routine acceptance |
+| Extensions | Ported: agents (install, sign-in, setup terminal), registry connectors, Composio apps, skills, installed list, custom connector, own skill, credentials, chat connection request card | Real provider OAuth, 1Password |
+| Voice | Ported call bar and Voice chat settings; on-device Android speech | OpenAI Realtime / Gemini Live engines |
+| State/widgets | Ported: Widget (with the animated Add a widget guide), Live update and Status bar pages, Usage sheet, Choose the look; Provider usage, Bots and Team widgets with launcher Edit widget | Physical launcher refresh |
+| Live updates | Android 16 Live updates (`ProgressStyle`), the status bar chip on Android 16 QPR1 (API 36.1) | Background updates need FCM in the deployment |
+| Version check | `VersionMismatch.MIN_HOST`, the host's `minApp`, the update card in the roster and in place of the composer | Set `MIN_HOST` to the first release that ships Android support when it's cut |
+| Remote screen | Not ported | WebRTC view and control |
+| Analytics | Not ported | PostHog with the Settings switch |
+| Packaging | Debug, unsigned R8 release, CI, optional Firebase/private configuration | Play signing, distribution, `versionCode` policy |
+
+## Gates before merge into dev
+
+- [x] `./gradlew :core:test :app:testDebugUnitTest :app:assembleDebug :app:assembleDebugAndroidTest :app:assembleRelease :app:lintDebug` passes (CI and the pre-commit hook run it).
+- [x] Every screen above walked through on an API 36 emulator against a disposable host, in light and dark mode, side by side with the iOS simulator.
+- [x] Live update and its status bar chip on an API 36.1 emulator.
+- [ ] `AppStore.kt` split by responsibility (clean-code size rule), undecodable events stop after one rewind and show *Update this app*, timeouts surface as errors.
+- [ ] Instrumentation suite run on an emulator.
+
+## Before a Play release
+
+- [ ] Physical upgrade keeps the saved account, pinned keys, bots and history.
+- [ ] Physical portrait/landscape/foldable, keyboard, large text and TalkBack.
+- [ ] Provider sign-in/switching, failed sign-out and revocation.
+- [ ] Firebase project and the push Worker's `FCM_SERVICE_ACCOUNT` secret (owner's go-ahead).
+- [ ] Host release gating for Android: like iPhones and the App Store, a release that raises
+ `minApp` must wait while paired Android phones can't get that version from Play
+ ([compatibility](../reference/compatibility.md)).
+
+## Shared deployment
+
+The host accepts Android pairing (older hosts refuse it, and the app asks to update
+Codync on the computer) and counts Android event streams as connected phones, so
+pushes are held while one is open. The cloud accepts Android device records through
+the `0004_android_devices.sql` migration. The push Worker needs the matching Firebase
+service account as an external secret; the client configuration contains no private key.
+
+![Android roster](../screenshots/android-roster.png)
+
+![Android reply thread](../screenshots/android-thread.png)
+
+![Android account](../screenshots/android-account.png)
diff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.md
index 85efe9d2..797a2671 100644
--- a/docs/reference/compatibility.md
+++ b/docs/reference/compatibility.md
@@ -14,7 +14,7 @@ always equal). There is no separate protocol number.
| Floor | Lives in | Meaning |
|---|---|---|
| `minApp` | `host/src/compat.rs` `MIN_APP`, sent in `hello` | The oldest client this host serves correctly. |
-| `minHost` | `apps/ios/Kit/.../Models/Compatibility.swift` `VersionMismatch.minHost`, `apps/desktop/src/shared/compat.ts` `MIN_HOST`, `host/src/compat.rs` `MIN_HOST` (terminal client) | The oldest host this client works with. |
+| `minHost` | `apps/ios/Kit/.../Models/Compatibility.swift` `VersionMismatch.minHost`, `apps/desktop/src/shared/compat.ts` `MIN_HOST`, `apps/android/core/.../Compatibility.kt` `VersionMismatch.MIN_HOST`, `host/src/compat.rs` `MIN_HOST` (terminal client) | The oldest host this client works with. |
On every (re)connect the client reads `hello` and decides, in this order:
@@ -28,11 +28,11 @@ reason to lock someone out.
## What each client does
-| | iPhone and desktop (`BotStore.mismatch`) | Terminal client |
+| | iPhone and desktop (`BotStore.mismatch`); Android (`AppState.mismatch`, `AppStoreConnection.kt`) | Terminal client |
|---|---|---|
| Notice | `UpdateNeededCard` above the computer's bots and in place of the composer; status reads *Needs update* | *needs update* in the status line, with the reason |
-| Update this app | iPhone: App Store page. Desktop: electron-updater check (`apps/desktop/src/main/updates.ts`) | Text only |
-| Update the host | Desktop: its own host is reinstalled (**Restart host**). iPhone: instructions for that computer | `^k` → Check for updates |
+| Update this app | iPhone: App Store page. Desktop: electron-updater check (`apps/desktop/src/main/updates.ts`). Android: text only | Text only |
+| Update the host | Desktop: its own host is reinstalled (**Restart host**). iPhone and Android: instructions for that computer | `^k` → Check for updates |
| Sync while mismatched | Stopped; `hello` is asked again every 30 s and on every reconnect | Continues; sending is blocked |
Drafts are kept while sending is blocked. A host update restarts the host, so the reconnect
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index 6972d022..fa19ce14 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -57,6 +57,7 @@ Shared deterministic [vectors](fixtures/remote-relay-vectors.json) and their [ge
| --- | --- |
| Worker API / authentication / DO | `cloud/src/api.ts`, `routes/`, `auth.ts`, `relay.ts` |
| Cloud schema | `cloud/migrations/` |
+| Android transport / crypto / pairing | `apps/android/core/`; device storage in `apps/android/app/` |
| Host identity / crypto / channel | `host/src/remote/identity.rs`, `crypto.rs`, `channel.rs` |
| Host cloud / relay | `host/src/remote/cloud.rs`, `relay.rs` |
| Swift transports / identity | `apps/ios/Kit/Sources/CodyncKit/Client/` |
diff --git a/docs/screenshots/android-account.png b/docs/screenshots/android-account.png
new file mode 100644
index 00000000..b9b87032
Binary files /dev/null and b/docs/screenshots/android-account.png differ
diff --git a/docs/screenshots/android-roster.png b/docs/screenshots/android-roster.png
new file mode 100644
index 00000000..a44d271a
Binary files /dev/null and b/docs/screenshots/android-roster.png differ
diff --git a/docs/screenshots/android-thread.png b/docs/screenshots/android-thread.png
new file mode 100644
index 00000000..85b3654f
Binary files /dev/null and b/docs/screenshots/android-thread.png differ
diff --git a/host/src/api/events.rs b/host/src/api/events.rs
index 36673b28..49231a58 100644
--- a/host/src/api/events.rs
+++ b/host/src/api/events.rs
@@ -28,19 +28,19 @@ pub fn term_events(hub: &Hub, id: &str) -> Option<impl Stream<Item = Value> + Se
Some(stream::iter(head).chain(live))
}
-/// Counts a connected iOS client (pushes are held while one is connected) for as long as its stream lives.
-struct IosClientGuard(Arc<Hub>);
+/// Counts a connected phone (pushes are held while one is connected) for as long as its stream lives.
+struct PhoneClientGuard(Arc<Hub>);
-impl IosClientGuard {
+impl PhoneClientGuard {
fn new(hub: Arc<Hub>) -> Self {
- hub.ios_clients.fetch_add(1, Ordering::Relaxed);
+ hub.phone_clients.fetch_add(1, Ordering::Relaxed);
Self(hub)
}
}
-impl Drop for IosClientGuard {
+impl Drop for PhoneClientGuard {
fn drop(&mut self) {
- self.0.ios_clients.fetch_sub(1, Ordering::Relaxed);
+ self.0.phone_clients.fetch_sub(1, Ordering::Relaxed);
}
}
@@ -78,7 +78,7 @@ pub fn events_stream(
catch_up.insert(0, hello);
let local = matches!(caller, Caller::Local);
- let guard = Arc::new((client == Some("ios")).then(|| IosClientGuard::new(hub.clone())));
+ let guard = Arc::new(matches!(client, Some("ios" | "android")).then(|| PhoneClientGuard::new(hub.clone())));
let tail = live.filter_map(move |msg| {
let _keep = guard.clone();
async move {
diff --git a/host/src/api/http.rs b/host/src/api/http.rs
index 4ee86c31..3c4411df 100644
--- a/host/src/api/http.rs
+++ b/host/src/api/http.rs
@@ -234,6 +234,30 @@ async fn routine_hook(
mod tests {
use super::*;
+ #[test]
+ fn phone_streams_hold_pushes_until_the_last_one_closes() {
+ let dir = std::env::temp_dir().join(format!("codync-phone-events-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).expect("temp dir");
+ let hub = Hub::new(
+ crate::store::Store::open(std::path::Path::new(":memory:")).expect("store"),
+ "test".into(),
+ crate::remote::identity::Identity::load_or_create(&dir).expect("identity"),
+ "test".into(),
+ 19222,
+ );
+ let desktop = events_stream(&hub, 0, Some("macos"), &Caller::Local).expect("desktop events");
+ assert!(!hub.phone_connected());
+ let android = events_stream(&hub, 0, Some("android"), &Caller::Local).expect("Android events");
+ let ios = events_stream(&hub, 0, Some("ios"), &Caller::Local).expect("iOS events");
+ assert!(hub.phone_connected());
+ drop(android);
+ assert!(hub.phone_connected(), "the iPhone remains connected");
+ drop(ios);
+ assert!(!hub.phone_connected(), "desktop streams do not hold phone alerts");
+ drop(desktop);
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
#[test]
fn only_loopback_counts_as_this_computer() {
let ip = |s: &str| s.parse::<IpAddr>().expect("test addresses are valid");
diff --git a/host/src/api/remote.rs b/host/src/api/remote.rs
index c4ed55c8..04f09c34 100644
--- a/host/src/api/remote.rs
+++ b/host/src/api/remote.rs
@@ -59,6 +59,10 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
}
json!({})
}
+ "unregisterActivity" => {
+ hub.store.remove_activity_ticket(str_arg(&b, "botId")?, caller.device_key())?;
+ json!({})
+ }
"pairing" => pairing(hub).await?,
"devices" => {
let connected = hub.connected.locked().clone();
diff --git a/host/src/hub.rs b/host/src/hub.rs
index 5f1af5fc..feda7931 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -61,7 +61,7 @@ pub struct Hub {
emit_lock: Mutex<()>,
bots: Mutex<HashMap<String, BotHandle>>,
runtime: Mutex<HashMap<String, Runtime>>,
- pub ios_clients: AtomicUsize,
+ pub phone_clients: AtomicUsize,
pub usage: Mutex<Usage>,
keep_awake: Mutex<service::KeepAwake>,
/// Generation of the authorized-device table and pairing offers: bumped on every
@@ -102,7 +102,7 @@ impl Hub {
emit_lock: Mutex::new(()),
bots: Mutex::default(),
runtime: Mutex::default(),
- ios_clients: AtomicUsize::new(0),
+ phone_clients: AtomicUsize::new(0),
usage: Mutex::default(),
keep_awake: Mutex::default(),
auth: watch::Sender::new(0),
@@ -525,8 +525,8 @@ impl Hub {
Ok(removed)
}
- pub fn ios_connected(&self) -> bool {
- self.ios_clients.load(Ordering::Relaxed) > 0
+ pub fn phone_connected(&self) -> bool {
+ self.phone_clients.load(Ordering::Relaxed) > 0
}
}
diff --git a/host/src/remote/channel.rs b/host/src/remote/channel.rs
index 4e14cf14..51522ee6 100644
--- a/host/src/remote/channel.rs
+++ b/host/src/remote/channel.rs
@@ -564,9 +564,9 @@ impl Channel {
}
let b = &v["b"];
let name = b["name"].as_str().map(str::trim).filter(|n| !n.is_empty() && n.chars().count() <= 100);
- let platform = b["platform"].as_str().filter(|p| matches!(*p, "ios" | "macos"));
+ let platform = b["platform"].as_str().filter(|p| matches!(*p, "ios" | "macos" | "android"));
let (Some(name), Some(platform)) = (name, platform) else {
- self.send(err(id, 400, "`name` and `platform` (ios or macos) are required")).await;
+ self.send(err(id, 400, "`name` and `platform` (ios, macos or android) are required")).await;
return protocol;
};
if !self.hub.pairing.locked().attempt(source) {
@@ -724,6 +724,30 @@ mod tests {
key
}
+ #[tokio::test]
+ async fn android_pairing_preserves_authorization_and_one_time_code() {
+ let hub = temp_hub();
+ let key = SigningKey::from_bytes(&crypto::random());
+ let code = hub.pairing.locked().issue().code;
+ let mut phone = Phone::direct(&hub, key.clone());
+ assert!(matches!(phone.hello(&hub, true).await, Out::Msg(v) if v["t"] == "welcome"));
+ let reply = phone.call(1, "pair", json!({"code": code, "name": "Android phone", "platform": "android"})).await;
+ assert_eq!(reply["ok"]["computerId"], hub.identity.computer_id());
+ assert_eq!(phone.recv().await.unwrap_err().0, close::PAIRED);
+ let device = hub.store.device(&phone.dk()).unwrap();
+ assert_eq!(device.platform, "android");
+ assert_eq!(device.source, DeviceSource::Local);
+ assert_eq!(device.scopes, [Scope::Control, Scope::Screen]);
+ assert!(!hub.pairing.locked().open());
+
+ let mut connected = Phone::direct(&hub, key);
+ assert!(matches!(connected.hello(&hub, false).await, Out::Msg(v) if v["t"] == "welcome"));
+ let hello = connected.call(1, "hello", json!({})).await;
+ assert_eq!(hello["ok"]["computerId"], hub.identity.computer_id());
+ let refused = connected.call(2, "setScreenEnabled", json!({"enabled": true})).await;
+ assert_eq!(refused["err"]["status"], 403);
+ }
+
#[tokio::test]
async fn unknown_device_is_rejected() {
let hub = temp_hub();
@@ -823,7 +847,7 @@ mod tests {
p.send(json!({"id": 3, "sub": "events", "b": {"since": hub.store.current_rev(), "client": "ios"}})).await;
let hello = p.recv().await.unwrap();
assert_eq!((hello["id"].as_u64(), hello["ev"]["type"].as_str()), (Some(3), Some("hello")));
- assert!(hub.ios_connected());
+ assert!(hub.phone_connected());
assert!(hub.revoke_device(&dk).unwrap());
let (code, reject) = p.recv().await.unwrap_err();
@@ -832,7 +856,7 @@ mod tests {
assert!(hub.store.push_tickets().is_empty());
assert_eq!(hub.store.activity_tickets("b1").len(), 0);
tokio::time::sleep(Duration::from_millis(50)).await;
- assert!(!hub.ios_connected(), "the events subscription ended with the channel");
+ assert!(!hub.phone_connected(), "the events subscription ended with the channel");
assert!(hub.connected.locked().is_empty());
}
diff --git a/host/src/remote/push.rs b/host/src/remote/push.rs
index 3c403826..d7df043e 100644
--- a/host/src/remote/push.rs
+++ b/host/src/remote/push.rs
@@ -107,7 +107,7 @@ fn faces(hub: &Hub, bot: &BotConfig, from: Option<&str>) -> Vec<Value> {
/// `bot` is the chat the alert opens; `from` is the member bot speaking when that chat is a group.
pub fn notify(hub: &Hub, bot: &BotConfig, from: Option<&str>, title: &str, body: &str, kind: AlertKind) {
purge_dead_tickets(hub);
- if bot.notify == Some(false) || bot.hidden || hub.ios_connected() {
+ if bot.notify == Some(false) || bot.hidden || hub.phone_connected() {
return;
}
if throttled((bot.id.clone(), kind), Duration::from_secs(5)) {
diff --git a/host/src/store/devices.rs b/host/src/store/devices.rs
index 0de13431..8509ee8c 100644
--- a/host/src/store/devices.rs
+++ b/host/src/store/devices.rs
@@ -198,6 +198,14 @@ impl Store {
logged("activity tickets", rows).unwrap_or_default()
}
+ pub fn remove_activity_ticket(&self, bot_id: &str, device_key: &str) -> Result<()> {
+ self.db.locked().execute(
+ "DELETE FROM activity_tickets WHERE bot_id = ?1 AND device_key = ?2",
+ params![bot_id, device_key],
+ )?;
+ Ok(())
+ }
+
/// Forgets a bot's Live Activity tickets (its activity ended); returns them.
pub fn take_activity_tickets(&self, bot_id: &str) -> Vec<String> {
let tickets = self.activity_tickets(bot_id);
@@ -260,6 +268,19 @@ mod tests {
assert_eq!(s.push_tickets().iter().map(|ticket| ticket.ticket.as_str()).collect::<Vec<_>>(), ["other"]);
}
+ #[test]
+ fn ending_one_phone_activity_preserves_other_bots_and_phones() {
+ let s = temp_store();
+ s.add_activity_ticket("one", "bot", "phone").unwrap();
+ s.add_activity_ticket("two", "bot", "other-phone").unwrap();
+ s.add_activity_ticket("three", "other-bot", "phone").unwrap();
+ s.remove_activity_ticket("bot", "phone").unwrap();
+ assert_eq!(s.activity_tickets("bot"), ["two"]);
+ assert_eq!(s.activity_tickets("other-bot"), ["three"]);
+ s.remove_activity_ticket("bot", "phone").unwrap();
+ assert_eq!(s.activity_tickets("bot"), ["two"]);
+ }
+
#[test]
fn registration_replaces_old_keys_and_activity_tokens_for_one_device_only() {
let s = temp_store();
diff --git a/relay/package.json b/relay/package.json
index ce87fe85..384047ff 100644
--- a/relay/package.json
+++ b/relay/package.json
@@ -6,7 +6,7 @@
"scripts": {
"deploy": "wrangler deploy",
"typecheck": "tsc",
- "test": "node --experimental-strip-types --no-warnings test/ticket.test.ts && node --experimental-strip-types --no-warnings test/push.test.ts"
+ "test": "node --experimental-strip-types --no-warnings test/ticket.test.ts && node --experimental-strip-types --no-warnings test/push.test.ts && node --experimental-strip-types --no-warnings test/fcm.test.ts"
},
"dependencies": {
"@fivesheepco/cloudflare-apns2": "^13.0.0"
diff --git a/relay/src/fcm.ts b/relay/src/fcm.ts
new file mode 100644
index 00000000..63dfa994
--- /dev/null
+++ b/relay/src/fcm.ts
@@ -0,0 +1,103 @@
+/** FCM HTTP v1. Credentials stay in the Worker; hosts receive opaque tickets only. */
+export interface ServiceAccount {
+ project_id: string;
+ client_email: string;
+ private_key: string;
+}
+
+export class FcmError extends Error {
+ readonly reason: string;
+ readonly gone: boolean;
+ constructor(reason: string, gone = false) { super(reason); this.reason = reason; this.gone = gone; }
+}
+
+const encoder = new TextEncoder();
+const base64url = (data: Uint8Array) => btoa(String.fromCharCode(...data)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+const encoded = (value: unknown) => base64url(encoder.encode(JSON.stringify(value)));
+const OAUTH_URL = "https://oauth2.googleapis.com/token";
+
+export class FcmClient {
+ private token?: { value: string; expiresAt: number };
+ private refreshing?: Promise<string>;
+ private key?: CryptoKey;
+ private readonly account: ServiceAccount;
+ private readonly send: typeof fetch;
+
+ constructor(account: ServiceAccount, send: typeof fetch = fetch) {
+ this.account = account;
+ // Workers' native fetch requires its global receiver, even when injected.
+ this.send = send.bind(globalThis);
+ if (!account || typeof account.project_id !== "string" || typeof account.client_email !== "string" ||
+ typeof account.private_key !== "string" || !/^[a-z][a-z0-9-]{4,61}[a-z0-9]$/.test(account.project_id) ||
+ !account.client_email.endsWith(".iam.gserviceaccount.com") || !account.private_key.includes("BEGIN PRIVATE KEY")) {
+ throw new FcmError("invalid FCM service account");
+ }
+ }
+
+ private async accessToken(): Promise<string> {
+ if (this.token && this.token.expiresAt > Date.now() + 60_000) return this.token.value;
+ if (this.refreshing) return this.refreshing;
+ this.refreshing = this.refresh();
+ try { return await this.refreshing; }
+ finally { this.refreshing = undefined; }
+ }
+
+ private async refresh(): Promise<string> {
+ if (!this.key) {
+ const pem = this.account.private_key.replace(/\\n/g, "\n").replace(/-----[^-]+-----/g, "").replace(/\s/g, "");
+ const bytes = Uint8Array.from(atob(pem), char => char.charCodeAt(0));
+ this.key = await crypto.subtle.importKey("pkcs8", bytes,
+ { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"]);
+ }
+ const now = Math.floor(Date.now() / 1000);
+ const input = encoded({ alg: "RS256", typ: "JWT" }) + "." + encoded({
+ iss: this.account.client_email, scope: "https://www.googleapis.com/auth/firebase.messaging",
+ aud: OAUTH_URL, iat: now, exp: now + 3600,
+ });
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", this.key, encoder.encode(input));
+ const response = await this.send(OAUTH_URL, {
+ method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: input + "." + base64url(new Uint8Array(signature)) }),
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!response.ok) throw new FcmError("FCM authorization failed");
+ const body = await response.json() as { access_token?: string; expires_in?: number };
+ if (!body.access_token || !Number.isFinite(body.expires_in) || body.expires_in! <= 60) throw new FcmError("invalid FCM authorization response");
+ this.token = { value: body.access_token, expiresAt: Date.now() + Math.min(body.expires_in!, 3600) * 1000 };
+ return body.access_token;
+ }
+
+ async push(token: string, data: Record<string, string>, urgent: boolean, validateOnly = false): Promise<void> {
+ const message = { fid: token, data, android: { priority: urgent ? "HIGH" : "NORMAL", ttl: "3600s" } };
+ if (encoder.encode(JSON.stringify(message)).length > 4096) throw new FcmError("payload too large");
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const accessToken = await this.accessToken();
+ const response = await this.send(`https://fcm.googleapis.com/v1/projects/${this.account.project_id}/messages:send`, {
+ method: "POST", headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
+ body: JSON.stringify({ message, ...(validateOnly ? { validate_only: true } : {}) }), signal: AbortSignal.timeout(15_000),
+ });
+ if (response.ok) return;
+ if (response.status === 401 && attempt === 0) { this.token = undefined; continue; }
+ const failure = await response.json().catch(() => ({})) as {
+ error?: { status?: string; details?: Array<{ "@type"?: string; errorCode?: string }> };
+ };
+ const detail = failure.error?.details?.find(item => item["@type"] === "type.googleapis.com/google.firebase.fcm.v1.FcmError");
+ // Invalid payloads, wrong project/sender and invalid credentials do not revoke a phone.
+ const gone = response.status === 404 && detail?.errorCode === "UNREGISTERED";
+ const reason = detail?.errorCode ?? failure.error?.status ?? `FCM HTTP ${response.status}`;
+ throw new FcmError(reason, gone);
+ }
+ }
+}
+
+let configured: { raw: string; client: FcmClient } | undefined;
+export function fcmClient(raw: string | undefined): FcmClient {
+ if (!raw) throw new FcmError("FCM is not configured");
+ if (configured?.raw === raw) return configured.client;
+ let account: ServiceAccount;
+ try { account = JSON.parse(raw) as ServiceAccount; }
+ catch { throw new FcmError("invalid FCM service account"); }
+ const client = new FcmClient(account);
+ configured = { raw, client };
+ return client;
+}
diff --git a/relay/src/index.ts b/relay/src/index.ts
index 1291c3be..1b8aafce 100644
--- a/relay/src/index.ts
+++ b/relay/src/index.ts
@@ -13,6 +13,7 @@
// generic alert with the host's end-to-end encrypted title/body (`data.sealed`).
import { ApnsClient, Notification, PushType, Priority } from "@fivesheepco/cloudflare-apns2";
+import { FcmError, fcmClient } from "./fcm.ts";
export interface Env {
APNS_TEAM_ID: string;
@@ -20,11 +21,15 @@ export interface Env {
APNS_SIGNING_KEY: string;
/** base64 of 32 random bytes: `openssl rand -base64 32` */
TICKET_KEY: string;
+ /** JSON service account with Firebase Cloud Messaging API Admin permission. */
+ FCM_SERVICE_ACCOUNT?: string;
}
type ApnsEnv = "sandbox" | "production";
type Kind = "alert" | "liveactivity";
-interface TicketPayload { t: string; e: ApnsEnv; k: Kind; b?: string }
+interface ApnsTicket { p?: "apns"; t: string; e: ApnsEnv; k: Kind; b?: string }
+interface FcmTicket { p: "fcm"; t: string; k: Kind; c: string; h: string; b?: string; r?: string }
+type TicketPayload = ApnsTicket | FcmTicket;
const BUNDLE_ID = "com.pokai.Codync.ios";
@@ -50,8 +55,9 @@ async function ticketKey(env: Env): Promise<CryptoKey> {
export async function sealTicket(env: Env, p: TicketPayload): Promise<string> {
const iv = crypto.getRandomValues(new Uint8Array(12));
+ const key = await ticketKey(env);
const ct = new Uint8Array(
- await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await ticketKey(env), new TextEncoder().encode(JSON.stringify(p))),
+ await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, new TextEncoder().encode(JSON.stringify(p))),
);
const out = new Uint8Array(iv.length + ct.length);
out.set(iv);
@@ -62,7 +68,8 @@ export async function sealTicket(env: Env, p: TicketPayload): Promise<string> {
export async function openTicket(env: Env, ticket: string): Promise<TicketPayload | null> {
try {
const bytes = fromB64url(ticket);
- const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, await ticketKey(env), bytes.slice(12));
+ const key = await ticketKey(env);
+ const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(0, 12) }, key, bytes.slice(12));
return JSON.parse(new TextDecoder().decode(pt)) as TicketPayload;
} catch {
return null;
@@ -99,7 +106,22 @@ function client(env: Env, apnsEnv: ApnsEnv, kind: Kind, bundleId?: string): Apns
const json = (body: unknown, status = 200) => Response.json(body, { status });
async function register(req: Request, env: Env): Promise<Response> {
- const body = (await req.json().catch(() => null)) as { token?: string; env?: string; kind?: string; bundleId?: string } | null;
+ const parsed = await req.json().catch(() => null);
+ const body = parsed as { provider?: string; token?: string; env?: string; kind?: string; ctx?: string; computerId?: string; botId?: string; taskId?: string; bundleId?: string } | null;
+ if (body?.provider === "fcm") {
+ if (typeof body.token !== "string" || !/^[A-Za-z0-9_:.-]{20,4096}$/.test(body.token)) return json({ error: "invalid token" }, 400);
+ if (body.kind !== "alert" && body.kind !== "liveactivity") return json({ error: "invalid kind" }, 400);
+ if (typeof body.ctx !== "string" || !/^(local|[a-f0-9]{64})$/.test(body.ctx) ||
+ typeof body.computerId !== "string" || !/^[A-Za-z0-9_-]{22}$/.test(body.computerId) ||
+ (body.kind === "liveactivity" && (typeof body.botId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(body.botId) ||
+ typeof body.taskId !== "string" || !/^[a-f0-9-]{36}$/.test(body.taskId)))) {
+ return json({ error: "invalid context" }, 400);
+ }
+ const ticket = await sealTicket(env, { p: "fcm", t: body.token, k: body.kind, c: body.ctx, h: body.computerId,
+ ...(body.kind === "liveactivity" ? { b: body.botId, r: body.taskId } : {}) });
+ return json({ ticket });
+ }
+ if (body?.provider !== undefined && body.provider !== "apns") return json({ error: "invalid provider" }, 400);
if (typeof body?.token !== "string" || !/^(?:[0-9a-fA-F]{2}){16,100}$/.test(body.token)) return json({ error: "invalid token" }, 400);
if (body.env !== "production" && body.env !== "sandbox") return json({ error: "invalid environment" }, 400);
if (body.kind !== "alert" && body.kind !== "liveactivity") return json({ error: "invalid kind" }, 400);
@@ -157,11 +179,19 @@ export function tokenIsGone(error: { reason?: string; statusCode?: number }): bo
}
async function push(req: Request, env: Env): Promise<Response> {
- const body = (await req.json().catch(() => null)) as PushBody | null;
+ const parsed = await req.json().catch(() => null);
+ const body = parsed as PushBody | null;
const t = body?.ticket ? await openTicket(env, body.ticket) : null;
if (!body || !t) return json({ error: "invalid ticket" }, 403);
// ponytail: no per-ticket rate limit; add a Durable Object counter if tickets get abused.
try {
+ if (t.p === "fcm") {
+ const data = fcmData(t, body);
+ const urgent = t.k === "alert" || body.liveActivity?.event === "end" || body.liveActivity?.contentState?.status === "needsInput";
+ const sender = fcmClient(env.FCM_SERVICE_ACCOUNT);
+ await sender.push(t.t, data, urgent);
+ return json({ ok: true });
+ }
if (t.k === "alert") {
if (!body.alert || typeof body.alert !== "object" ||
(body.alert.title !== undefined && typeof body.alert.title !== "string") ||
@@ -196,6 +226,8 @@ async function push(req: Request, env: Env): Promise<Response> {
}
return json({ ok: true });
} catch (err) {
+ if (err instanceof FcmError) return json({ error: err.reason, gone: err.gone }, err.gone ? 410 : err.reason === "payload too large" ? 413 : 502);
+ if (err instanceof InvalidFcmPayload) return json({ error: "invalid FCM payload" }, 400);
// ApnsError carries APNs' `reason` (e.g. "Unregistered") and `statusCode`.
const e = err as { reason?: string; statusCode?: number; message?: string };
const reason = e.reason ?? e.message ?? String(err);
@@ -211,11 +243,32 @@ async function push(req: Request, env: Env): Promise<Response> {
export function latestTicketIndices(tickets: Array<TicketPayload | null>): Set<number> {
const latest = new Map<string, number>();
tickets.forEach((ticket, index) => {
- if (ticket) latest.set(`${ticket.b ?? BUNDLE_ID}:${ticket.e}:${ticket.k}:${ticket.t.toLowerCase()}`, index);
+ if (ticket?.p === "fcm") latest.set(`fcm:${ticket.k}:${ticket.b ?? ""}:${ticket.t}`, index);
+ else if (ticket) latest.set(`apns:${ticket.b ?? BUNDLE_ID}:${ticket.e}:${ticket.k}:${ticket.t.toLowerCase()}`, index);
});
return new Set(latest.values());
}
+class InvalidFcmPayload extends Error {}
+
+/** Data-only messages let Android open sealed text locally even in the background. */
+export function fcmData(ticket: FcmTicket, body: PushBody): Record<string, string> {
+ if (ticket.k === "alert") {
+ const data = body.data;
+ if (!body.alert || typeof body.alert.title !== "string" || typeof body.alert.body !== "string" ||
+ !data || typeof data.sealed !== "string" || typeof data.botId !== "string" ||
+ data.ctx !== ticket.c || data.computerId !== ticket.h) throw new InvalidFcmPayload();
+ return { kind: "alert", ctx: ticket.c, computerId: ticket.h, botId: data.botId, sealed: data.sealed,
+ title: body.alert.title.slice(0, 120), body: body.alert.body.slice(0, 400), category: body.category ?? "" };
+ }
+ if (!body.liveActivity || !ticket.b || !ticket.r) throw new InvalidFcmPayload();
+ let aps: Record<string, unknown>;
+ try { aps = liveActivityAps(body.liveActivity); } catch { throw new InvalidFcmPayload(); }
+ return { kind: "task", ctx: ticket.c, computerId: ticket.h, botId: ticket.b, taskId: ticket.r,
+ event: String(aps.event), timestamp: String(aps.timestamp),
+ staleDate: String(aps["stale-date"] ?? aps["dismissal-date"]), status: String(body.liveActivity.contentState?.status) };
+}
+
export async function pushBatch(req: Request, env: Env, deliver = push): Promise<Response> {
const body = await req.json().catch(() => null) as { notifications?: PushBody[] } | null;
const notifications = body?.notifications;
diff --git a/relay/test/fcm.test.ts b/relay/test/fcm.test.ts
new file mode 100644
index 00000000..8fbb03e3
--- /dev/null
+++ b/relay/test/fcm.test.ts
@@ -0,0 +1,88 @@
+import assert from "node:assert/strict";
+import { FcmClient, FcmError, fcmClient } from "../src/fcm.ts";
+import worker, { fcmData, latestTicketIndices, openTicket } from "../src/index.ts";
+
+const pair = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048,
+ publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]);
+const keyBytes = await crypto.subtle.exportKey("pkcs8", pair.privateKey);
+const account = { project_id: "test-codync", client_email: "[email protected]",
+ private_key: "-----BEGIN PRIVATE KEY-----\n" + btoa(String.fromCharCode(...new Uint8Array(keyBytes))) + "\n-----END PRIVATE KEY-----" };
+for (const invalid of ["private-secret-not-json", "null", "{}", '{"project_id":42}']) {
+ assert.throws(() => fcmClient(invalid), error => error instanceof FcmError && error.reason === "invalid FCM service account");
+}
+let exchanges = 0;
+let sends = 0;
+let failure: { status: number; code: string; detail?: string } | undefined;
+const sender: typeof fetch = async function(this: unknown, url, options) {
+ assert.equal(this, globalThis);
+ if (String(url) === "https://oauth2.googleapis.com/token") {
+ exchanges++;
+ const fields = new URLSearchParams(String(options?.body));
+ const assertion = fields.get("assertion")!;
+ const parts = assertion.split(".");
+ const decode = (value: string) => Uint8Array.from(Buffer.from(value, "base64url"));
+ const verified = await crypto.subtle.verify("RSASSA-PKCS1-v1_5", pair.publicKey, decode(parts[2]), new TextEncoder().encode(parts[0] + "." + parts[1]));
+ assert.equal(verified, true);
+ const claims = JSON.parse(Buffer.from(parts[1], "base64url").toString());
+ assert.equal(claims.scope, "https://www.googleapis.com/auth/firebase.messaging");
+ assert.equal(claims.aud, "https://oauth2.googleapis.com/token");
+ assert.equal(claims.exp - claims.iat, 3600);
+ return Response.json({ access_token: "test-access", expires_in: 3600 });
+ }
+ assert.equal(String(url), "https://fcm.googleapis.com/v1/projects/test-codync/messages:send");
+ assert.equal(new Headers(options?.headers).get("Authorization"), "Bearer test-access");
+ const payload = JSON.parse(String(options?.body));
+ assert.equal(payload.message.fid, "CaseSensitiveToken");
+ assert.equal("notification" in payload.message, false);
+ assert.deepEqual(payload.message.data, { sealed: "ciphertext" });
+ sends++;
+ if (failure) return Response.json({ error: { status: failure.code, details: failure.detail ? [
+ { "@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError", errorCode: failure.detail },
+ ] : [] } }, { status: failure.status });
+ return Response.json({ name: "projects/test-codync/messages/test" });
+};
+const client = new FcmClient(account, sender);
+await Promise.all([client.push("CaseSensitiveToken", { sealed: "ciphertext" }, true), client.push("CaseSensitiveToken", { sealed: "ciphertext" }, false)]);
+assert.equal(exchanges, 1);
+assert.equal(sends, 2);
+failure = { status: 404, code: "NOT_FOUND", detail: "UNREGISTERED" };
+await assert.rejects(client.push("CaseSensitiveToken", { sealed: "ciphertext" }, true), error => error instanceof FcmError && error.gone);
+for (const error of [
+ { status: 400, code: "INVALID_ARGUMENT", detail: "INVALID_ARGUMENT" },
+ { status: 403, code: "PERMISSION_DENIED", detail: "SENDER_ID_MISMATCH" },
+ { status: 404, code: "NOT_FOUND" },
+ { status: 503, code: "UNAVAILABLE" },
+]) {
+ failure = error;
+ await assert.rejects(client.push("CaseSensitiveToken", { sealed: "ciphertext" }, true), error => error instanceof FcmError && !error.gone);
+}
+await assert.rejects(client.push("CaseSensitiveToken", { sealed: "x".repeat(4096) }, true), /payload too large/);
+assert.equal(exchanges, 1);
+
+const ticket = { p: "fcm" as const, t: "CaseSensitiveToken", k: "alert" as const, c: "local", h: "A".repeat(22) };
+const alert = { alert: { title: "Codync", body: "A bot needs you" }, data: { botId: "bot", computerId: ticket.h, ctx: "local", sealed: "ciphertext" } };
+assert.equal(fcmData(ticket, alert).sealed, "ciphertext");
+assert.throws(() => fcmData(ticket, { ...alert, data: { ...alert.data, ctx: "other" } }));
+assert.throws(() => fcmData(ticket, { ...alert, data: { ...alert.data, sealed: undefined } }));
+const task = { ...ticket, k: "liveactivity" as const, b: "bot", r: "00112233-4455-6677-8899-aabbccddeeff" };
+const taskData = fcmData(task, { liveActivity: { event: "update", contentState: { status: "working", activity: "" } } });
+assert.equal(taskData.kind, "task");
+assert.equal(taskData.botId, "bot");
+assert.equal("activity" in taskData, false);
+assert.throws(() => fcmData(task, { liveActivity: { event: "update", contentState: { status: "working", activity: "private" } } }));
+assert.deepEqual([...latestTicketIndices([
+ ticket, { ...ticket, t: "casesensitivetoken" }, { ...ticket },
+ task, { ...task, b: "other-bot" },
+ { t: "ab", e: "sandbox", k: "alert" }, { t: "AB", e: "sandbox", k: "alert" },
+])], [2, 1, 3, 4, 6]);
+
+const env = { TICKET_KEY: btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))) } as any;
+const registered = await worker.fetch(new Request("https://relay.test/register", { method: "POST", body: JSON.stringify({
+ provider: "fcm", token: "A_CaseSensitiveFCMToken:123", kind: "alert", ctx: "local", computerId: ticket.h,
+}) }), env);
+assert.equal(registered.status, 200);
+const result = await registered.json() as { ticket: string };
+const opened = await openTicket(env, result.ticket);
+assert.equal(opened?.p, "fcm");
+assert.equal(opened?.t, "A_CaseSensitiveFCMToken:123");
+console.log("FCM ticket, payload, OAuth and error tests ok");
diff --git a/relay/tsconfig.json b/relay/tsconfig.json
index 00bf28fc..6b2e8247 100644
--- a/relay/tsconfig.json
+++ b/relay/tsconfig.json
@@ -6,7 +6,8 @@
"lib": ["ESNext"],
"types": ["@cloudflare/workers-types"],
"strict": true,
- "noEmit": true
+ "noEmit": true,
+ "allowImportingTsExtensions": true
},
"include": ["src"]
}
diff --git a/web/app/privacy/page.tsx b/web/app/privacy/page.tsx
index 57f784ef..77c9457b 100644
--- a/web/app/privacy/page.tsx
+++ b/web/app/privacy/page.tsx
@@ -30,7 +30,7 @@ export default function Privacy() {
<Section title="Data we collect">
<p className="mb-2">
- Only usage analytics. They are on by default; turn them off on each iPhone and each computer in Settings (Share usage analytics), and that device stops sending right away.
+ Only usage analytics. They are on by default; turn them off on each phone and each computer in Settings (Share usage analytics), and that device stops sending right away.
</p>
<ul className="list-disc pl-5 space-y-2">
<li><strong>What we record:</strong> which features you use, such as opening the app, creating or deleting a bot, sending a message (with the number of attachments, not the files), starting a routine or a voice call, and installing a connector from the catalog. Each event carries the app version, the platform and the agent and model a bot uses.</li>
@@ -54,7 +54,7 @@ export default function Privacy() {
</Section>
<Section title="Data retention">
- Everything lives on your devices. Delete a bot to remove its conversation; uninstall the host and delete <code>~/.codync</code> to remove all of it. Deleting the iPhone app removes its cache. Turning analytics off stops new events from being sent.
+ Everything lives on your devices. Delete a bot to remove its conversation; uninstall the host and delete <code>~/.codync</code> to remove all of it. Deleting the phone app removes its cache. Turning analytics off stops new events from being sent.
</Section>
<Section title="Children's privacy">